http://stackoverflow.com/comment/80719069
score: 0
type: AnswerComment
has text: Sorry, did I slip again? It just seems more comprehensible if it's a variable hiding a true/false. Maybe I just worded it poorly? I could of course name it `different` and it would read like an ordinary sentence.
type: Comment
comment on: http://stackoverflow.com/a/46885272

http://stackoverflow.com/a/46872719
has body: How about file=open('IH.txt','r') text="" for i in range(6): text += file.readLine() print(text) file.close() read() reads the entire file. readline() reads only a line. The loop has 5 iterations and in each iteration, the next line from the file is appended to text via concatenation. You might also want to do exception handling.
answers question: http://stackoverflow.com/q/46872547
has comment: http://stackoverflow.com/comment/80692806
downvote count: 0
has comment: http://stackoverflow.com/comment/80700675
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/80700918
score: 2
has comment: http://stackoverflow.com/comment/80699946
has comment: http://stackoverflow.com/comment/80700685

http://stackoverflow.com/a/62919721
upvote count: 3
type: Answer
score: 3
downvote count: 0
has body: I also encountered this error when I tried to generate the convex Hull of groups of 2D points. The error message looks like this: cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:137: error: (-215:Assertion failed) total &gt;= 0 &amp;&amp; (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull' The reason turned out to be that my input points were float number instead of integer. So I use numpy.astype(np.int) to change the input points' data type.
answers question: http://stackoverflow.com/q/46849668

http://stackoverflow.com/comment/80461386
score: 0
has text: Jezrael, have a look at:: https://stackoverflow.com/questions/46758107/plotting-a-multiple-column-in-pandas-converting-strings-to-floats
comment on: http://stackoverflow.com/a/46756542
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80448336
type: Comment
comment on: http://stackoverflow.com/a/46751218
has text: this will retain only last word-length occurrences. so new_dict will have 'my' and skip 'is'.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80706029
type: AnswerComment
comment on: http://stackoverflow.com/a/46879406
has text: It worked well, thanks for the help. As dumb as it sounds In kept trying to put the string after the print statement before asking the question. Thanks for the fix alfasin.
type: Comment
score: 1

http://stackoverflow.com/comment/80682477
type: QuestionComment
comment on: http://stackoverflow.com/q/46867536
has text: Ive tried iterating through the python and splitting on white space but receive errors whenver i try to. And i meant average sentance length.
score: 0
type: Comment

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

http://stackoverflow.com/a/46892142
score: 3
type: AcceptedAnswer
has body: You are never picking a random choice for the computer. Instead, you calculate a new random in every if statement. Try: computer_choice = random.choice(a) And then replace every future random.choice(a) with computer_choice
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46892078
downvote count: 0
answers question: http://stackoverflow.com/q/46892078

http://stackoverflow.com/comment/80851649
score: 0
type: Comment
has text: Thanks @georgexsh. Indeed this seems to be a bug. I try at the moment to work around it by using my own ˋdispatchˋ function which injects the unknown args as a list to ˋnamespace_objˋ, but it is pretty cumbersome. Might instead try to move this functionality into a custom parser object...
type: AnswerComment
comment on: http://stackoverflow.com/a/46912858

http://stackoverflow.com/comment/80694175
score: 0
type: Comment
type: QuestionComment
has text: Similar to https://stackoverflow.com/q/17138088/407651. Try this: `input_string = u'Suspended|€ 2,000.00'`.
comment on: http://stackoverflow.com/q/46870889

http://stackoverflow.com/a/72467833
type: Answer
answers question: http://stackoverflow.com/q/46894174
has body: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == KEYDOWN: if event.key == K_SPACE and y_change == 0: # if spacebar is pressed and y_change is 0 y_change = 18 # set y_change to 18 if y_change &gt; 0 and player_y == 200: # if y_change is greater than 0 and player_y is 200 player_y -= y_change y_change -= gravity if player_y &gt; 200: player_y = 200 if player_y == 200 and y_change &lt; 0: y_change = 0
has comment: http://stackoverflow.com/comment/128020417
score: 0

http://stackoverflow.com/q/46863666
has comment: http://stackoverflow.com/comment/80674846
upvote count: 1
has title: If an item in a list is selected, then print a specific string
has comment: http://stackoverflow.com/comment/80674831
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46863760
favorite count: 0
has body: Bit of a beginner here. I want my code to return a specific string if a specific item from a list is selected. import random # carrots # yarn list = ['bunny', 'kitty'] random.choice (list) So if say 'bunny' is selected, then I want it to post: bunny - carrots But i don't want "bunny" to ever be paired with anything other than "carrots", so no "yarn". How do I go about this?
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80674912
type: Question
has comment: http://stackoverflow.com/comment/80674797
has comment: http://stackoverflow.com/comment/80674943
accepted answer: http://stackoverflow.com/a/46863760
has comment: http://stackoverflow.com/comment/80674823
score: 0

http://stackoverflow.com/a/46792333
has comment: http://stackoverflow.com/comment/80531804
score: 1
answers question: http://stackoverflow.com/q/46791931
downvote count: 0
has body: You're re-assigning the valueHolder and nameHolder identifiers in your loops instead of adding elements to the lists. Try this: for row in value: valueHolder.append(row.text) for row in name: nameHolder.append(row.text) To combine the lists you could use a map, such as in combinations = list(map(lambda x,y: [x,y], nameHolder, valueHolder))
type: Answer
upvote count: 1

http://stackoverflow.com/comment/80677712
has text: I have upgraded to the latest version of nbconvert, but now I get a different error: TypeError: validate() got an unexpected keyword argument 'relax_add_props'
comment on: http://stackoverflow.com/a/46859271
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46900437
type: Question
has body: So I have made a Scrapy Splash request like this: def start_requests(self): lua_script = ''' function main(splash) local url = splash.args.url assert(splash:go(url)) assert(splash:wait(0.5)) return { cookies = splash:get_cookies(), } end ''' yield SplashRequest(self.start_urls[0], self.parse, endpoint='render.html', args={'wait': 1, 'lua_source': lua_script},) The problems is how do I get the cookies that I've set to be returned using the lua script?
has answer: http://stackoverflow.com/a/46900613
score: 4
has title: How to get cookie generated from a Scrapy Splash request?
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46900613
tagged with: scrapy-splash
tagged with: python
tagged with: lua
type: AnsweredQuestion
tagged with: splash-js-render
tagged with: scrapy

http://stackoverflow.com/q/46891408
tagged with: django
upvote count: 1
downvote count: 1
type: AnsweredQuestion
type: Question
tagged with: apache
answer count: 1
has answer: http://stackoverflow.com/a/46892380
accepted answer: http://stackoverflow.com/a/46892380
favorite count: 0
score: 0
has title: django: Setting environment variables in /etc/apache2/envvar is not working
tagged with: python
has body: I have a Django (v1.11.6) app on my Ubuntu server having Python 3.5 (not using virtualenv). However, I want to set environment variables in mod_wsgi for Django. Since I'm not using virtualenv I set then in /etc/apache2/envvar. But apache2 service can't get them. In settings.py I have SECRET_KEY = get_env_variable("GA_SECRET_KEY") but apache raises the following error: [Mon Oct 23 14:03:29.180611 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] SECRET_KEY = os.environ("GA_SECRET_KEY") [Mon Oct 23 14:03:29.180630 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] TypeError: '_Environ' object is not callable Do you know how to fix this?

http://stackoverflow.com/comment/80741164
comment on: http://stackoverflow.com/q/46896727
type: Comment
type: QuestionComment
has text: for Joran: ok it works! can you explain why (sorry in the last i write that it doesnt)? thanks
score: 0

http://stackoverflow.com/a/46904112
has body: first check if the image exists in the folder dir1 and the if it exists copy the image from the dir1 to dir2. for img in list1: if os.path.exists(dir1+img): shutil.copy(dir1+img, dir2+img) else: print "Image %s doesn't exist"%img
answers question: http://stackoverflow.com/q/46903397
score: 1
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/47159311
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/46852824
answers question: http://stackoverflow.com/q/46852824
score: 1
has body: Note: your get('/foo', 1) is an anonymous generator object, Task(get('/foo', 1)) is an anonymous Task object. GC is short for python garbage collection/collector The reference chain of your original code is: selector --> # socket_fd anonymous Task(get('/foo', 1)) --> anonymous get('/foo', 1) --> s So the anonymous Task(get('/foo', 1)) object is collected by GC as soon as it finishes. This is because: Python GC will collect the memory of an object as soon as it finds the object's reference count == 0. But python GC is not running as a thread so maybe not the moment right after the object's reference count decreases to 0. So then the anonymous get('/foo', 1) will be collected, then will be s. At here, s is collected, closed and its corresponding socket #fd number (#368 in your example) has been released. But the socket #fd number (#368) has been registered to selector. Then you run Task(get('/bar',2)), a new socket s tries to apply for a "new" fd, because #368 is available (as long as the other processes in your system has not claimed it), you will get #368 as socket fd agian. un-comment arr.append(self.__init__) in Task.step() After you un-comment arr.append(self.__init__) in Task.step() method, the global arr hold a reference to Task(get('/foo', 1)) . Then Task(get('/foo', 1)) has a reference to get('/foo', 1). Then get('/foo', 1) has a reference to your local socket s. This reference chain is like: arr --> anonymous Task(get('/foo', 1)) --> anonymous get('/foo', 1) --> s arr is valid through your program, so s will not be collected by GC. Later s = socket.socket() will not get the same fd because it is still held by s. use s instead of s.fileno() If you use selector.register(s ..) instead of selector.register(s.fileno()..), the global selector will hold a reference to your local s, the reference chain is: selector --> s Although the two anonymous objects have gone, your get('/foo', 1))::s and get('/bar', 2))::s are still held by the global selector. So don't worry …

http://stackoverflow.com/comment/80640718
score: 0
type: Comment
type: QuestionComment
has text: help content? __dir__ is the implementation of `dir()` and should print attributes dict of the object
comment on: http://stackoverflow.com/q/46846533

http://stackoverflow.com/comment/80838347
type: AnswerComment
comment on: http://stackoverflow.com/a/46872344
has text: it's working but every time I opened my terminal I have to set this path. What is the permanent solution?
score: 0
type: Comment

http://stackoverflow.com/comment/80627603
type: AnswerComment
comment on: http://stackoverflow.com/a/46836665
type: Comment
score: 1
has text: Many thanks. When I try to import the wine dataset, I get an error "cannot import name load_wine". I tried to do this with load_iris and it worked no problem, even running the knn.fit. I'm thinking there's an error with that particular dataset, or when I try to import manually it's a different file type.

http://stackoverflow.com/q/46828031
type: Question
has body: When plotting correlations, this code &gt;&gt;&gt; import seaborn as sns &gt;&gt;&gt; iris = sns.load_dataset("iris") &gt;&gt;&gt; g = sns.pairplot(iris) results in the following pairplot: http://seaborn.pydata.org/_images/seaborn-pairplot-1.png What if I just want to show the first row out of those four (i.e. correlations of 'sepal_length' vs all other features)? How can I plot that? Could pairplot be used but with some modifications? Thanks
tagged with: python
has title: matplotlib (seaborn): plot correlations between one variable vs multiple others
tagged with: correlation
score: 0
answer count: 1
tagged with: plot
has answer: http://stackoverflow.com/a/46830119
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/46830119
type: AnsweredQuestion

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

http://stackoverflow.com/q/46758894
upvote count: 0
has comment: http://stackoverflow.com/comment/80464552
answer count: 1
has answer: http://stackoverflow.com/a/46759148
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80463524
type: UnansweredQuestion
tagged with: python
tagged with: append
has comment: http://stackoverflow.com/comment/80463356
has comment: http://stackoverflow.com/comment/80463218
has body: I am trying to make a text based adventure game in python, as i am a beginner my programming isn't that great so what i have done is great. I was wondering if you are able to append a list from a different module. For example at the shop i would import the inventory module and be able to append the inventory list from the shop module. H.Moss
downvote count: 2
has comment: http://stackoverflow.com/comment/80463234
type: Question
score: -2
has title: How to append lists from a different module in PYTHON 3

http://stackoverflow.com/comment/80673200
type: QuestionComment
comment on: http://stackoverflow.com/q/46862849
has text: Whats not working everything is fine in my PC
score: 0
type: Comment

http://stackoverflow.com/comment/80461333
type: QuestionComment
comment on: http://stackoverflow.com/q/46756322
score: 0
type: Comment
has text: @Andersson It was not pasted before. Mobile problems :P I am doing it now

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/46805662
tags question: http://stackoverflow.com/q/46848912
tags question: http://stackoverflow.com/q/46838233
tags question: http://stackoverflow.com/q/46855434
tags question: http://stackoverflow.com/q/46839703
tags question: http://stackoverflow.com/q/46882674
tags question: http://stackoverflow.com/q/46798413
tags question: http://stackoverflow.com/q/46854753
tags question: http://stackoverflow.com/q/46864776
tags question: http://stackoverflow.com/q/46818431
tags question: http://stackoverflow.com/q/46797123
tags question: http://stackoverflow.com/q/46897773
tags question: http://stackoverflow.com/q/46875745
tags question: http://stackoverflow.com/q/46855180
tags question: http://stackoverflow.com/q/46804573
type: Tag
tags question: http://stackoverflow.com/q/46793377
tags question: http://stackoverflow.com/q/46872329
tags question: http://stackoverflow.com/q/46843440
tags question: http://stackoverflow.com/q/46824027
tags question: http://stackoverflow.com/q/46837716
tags question: http://stackoverflow.com/q/46846437
tags question: http://stackoverflow.com/q/46786650
tags question: http://stackoverflow.com/q/46750948
tags question: http://stackoverflow.com/q/46809355
tags question: http://stackoverflow.com/q/46898430
tags question: http://stackoverflow.com/q/46834895
tags question: http://stackoverflow.com/q/46873195
tags question: http://stackoverflow.com/q/46814099
tags question: http://stackoverflow.com/q/46802099
tags question: http://stackoverflow.com/q/46751571
tags question: http://stackoverflow.com/q/46876897
tags question: http://stackoverflow.com/q/46762918

http://stackoverflow.com/comment/80744526
comment on: http://stackoverflow.com/a/46898566
has text: Hey, buddy. Thanks. Buuut my problem is that I need to change the original structure to import to MongoDB. As you can see in my example, the original JSON returns a multidimensional attributes for `place` and I need to restructure to one-level dictionary (and some fields are optionals).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46795601
has answer: http://stackoverflow.com/a/46795664
has comment: http://stackoverflow.com/comment/80537858
has answer: http://stackoverflow.com/a/46795687
score: -1
answer count: 2
downvote count: 2
upvote count: 1
has title: converting string to int using map dosen't include zero
favorite count: 0
linked to: http://stackoverflow.com/q/134934
tagged with: python-3.x
type: UnansweredQuestion
has body: My input to this is in the format 07:05:09PM expected output: 19:05:09 output got: 19:5:9 def timeConversion(s): if "AM" in s: print(s[1:8]) else: string=s.split(':') print(string) string.append(string[2][0:2]) string.remove(string[2]) print(string) date=list(map(int, string)) print(date) a=date[0]+12 b='%s:%s:%s' % (a, date[1], date[2]) return b My question is when I convert the date from string to int using map the zero is not picked up, is there any way to get the integer as such???
tagged with: python
linked to: http://stackoverflow.com/q/36913684
has comment: http://stackoverflow.com/comment/80537859
linked to: http://stackoverflow.com/q/34688196
type: Question

http://stackoverflow.com/comment/80581531
has text: Hmm, Thanks! But Actually I want to use mongo aggregation framework(I mentioned it in the post) to get output like that
comment on: http://stackoverflow.com/a/46812987
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80624942
type: Comment
type: QuestionComment
has text: You can also assume the suffix will always be numerical, if that helps.
score: 0
comment on: http://stackoverflow.com/q/46838487

http://stackoverflow.com/q/46837492
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80622665
linked to: http://stackoverflow.com/q/3906137
tagged with: io
duplicate of: http://stackoverflow.com/q/3906137
has comment: http://stackoverflow.com/comment/80622636
score: 1
has comment: http://stackoverflow.com/comment/80622637
favorite count: 0
tagged with: python-3.x
type: Question
has body: I am trying to get Python 3.5 to look in a file for a variable. I have tried to convertusername to str(username) but to no avail. Here is the offending piece of code: if str(username) in fi.read(): hasAccount = True print("found username") else: hasAccount = False print("notfound") Any ideas? This one has me absolutely baffled. Thanks P.S. I have already used with open("usernames.txt", "a+")as fi: earlier in the code. P.P.P.S. People were asking for an MCVE, so I hope this counts: with open("usernames.txt", "a+")as fi:#opens usernames file as "fi" and closes once finished with open("userinfos.txt", "a+") as f:#opens userinfos file as "f" and closes once finished with open("quizzes.txt", "a+") as fil: listofinfos = ["surname", "yeargroup"]#list with information apart from name and age if True:#will always run name = input("Enter your name:") age = input("Enter your age:") username = name[:3]+age#shortens name variable to first 3 letters and concatenates with age if str(username) in fi.read(): hasAccount = True print("found username") else: hasAccount = False print("notfound")
has title: Python not looking in file for string?
has comment: http://stackoverflow.com/comment/80622619
tagged with: python
has comment: http://stackoverflow.com/comment/80622662
has comment: http://stackoverflow.com/comment/80622822
has comment: http://stackoverflow.com/comment/80622750
upvote count: 1
has comment: http://stackoverflow.com/comment/80622635
has comment: http://stackoverflow.com/comment/80622765
has comment: http://stackoverflow.com/comment/80622577
has comment: http://stackoverflow.com/comment/80622710

http://stackoverflow.com/a/61383659
answers question: http://stackoverflow.com/q/46815231
has body: Windows 10 + Visual Studio Code - "CMD + SHIFT + P" from within visual studio code and search for "Select Interpreter" clicking on this will show a list of available python interpreters and versions installed on your system that are detected by visual studio code and your currently selected environment. (Visual Studio Code usually incorrectly defaults to 32 bit interpreter) Ensure you have the correct python environment (where you have the required libraries &amp; "packages" installed) This should fix your import issue if you have the libraries installed. Use the appropriate cmd line tool to install packages. If you are using Anaconda - use Conda Install or use pip etc...
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/46778617
tagged with: decimal
answer count: 3
has answer: http://stackoverflow.com/a/46778793
downvote count: 0
accepted answer: http://stackoverflow.com/a/46778760
has answer: http://stackoverflow.com/a/46778778
tagged with: precision
favorite count: 0
possible better answer: http://stackoverflow.com/a/46778778
tagged with: python
has title: Python Decimal precision at the console - weird
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/80503138
has answer: http://stackoverflow.com/a/46778760
type: Question
has body: Having imported math and decimal in 3. I'm OK with the first output In[39]: Decimal(sqrt(2)) Out[39]: Decimal('1.4142135623730951454746218587388284504413604736328125') but then slightly flummoxed by In[40]: Decimal(str(sqrt(2))) Out[40]: Decimal('1.4142135623730951') the really confused by... In[41}: getcontext().prec=2 In[42]: Decimal(str(sqrt(2))) Out[42]: Decimal('1.4142135623730951') Why isn't the output precision set to 2 for future Decimal Out[] lines after the prec=2? I thought Decimal() casts the input whether float string or int as a decimal with the precision set?

http://stackoverflow.com/comment/80666725
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46859508
has text: I tried that, and None creates this error: `TypeError: invalid result from HugeTable.GetValue(), NoneType cannot be converted to a C/C++ wxString in this context`
score: 0

pyqt
type: Tag
tags question: http://stackoverflow.com/q/46853383
tags question: http://stackoverflow.com/q/46895943
tags question: http://stackoverflow.com/q/46837947
tags question: http://stackoverflow.com/q/46818396
tags question: http://stackoverflow.com/q/46840315
tags question: http://stackoverflow.com/q/46869472
tags question: http://stackoverflow.com/q/46758447
tags question: http://stackoverflow.com/q/46878419
tags question: http://stackoverflow.com/q/46859945
tags question: http://stackoverflow.com/q/46752701
tags question: http://stackoverflow.com/q/46773581
tags question: http://stackoverflow.com/q/46888362
tags question: http://stackoverflow.com/q/46868452
tags question: http://stackoverflow.com/q/46889571
tags question: http://stackoverflow.com/q/46818102
tags question: http://stackoverflow.com/q/46874619
tags question: http://stackoverflow.com/q/46855815
tags question: http://stackoverflow.com/q/46854121
tags question: http://stackoverflow.com/q/46894556
tags question: http://stackoverflow.com/q/46778410
tags question: http://stackoverflow.com/q/46795315
tags question: http://stackoverflow.com/q/46807436
tags question: http://stackoverflow.com/q/46839732
tags question: http://stackoverflow.com/q/46814961
tags question: http://stackoverflow.com/q/46878763
tags question: http://stackoverflow.com/q/46833723
tags question: http://stackoverflow.com/q/46869530
tags question: http://stackoverflow.com/q/46869883
tags question: http://stackoverflow.com/q/46840770
tags question: http://stackoverflow.com/q/46755141
tags question: http://stackoverflow.com/q/46868432
tags question: http://stackoverflow.com/q/46845441
tags question: http://stackoverflow.com/q/46883799
tags question: http://stackoverflow.com/q/46830464
tags question: http://stackoverflow.com/q/46900584
tags question: http://stackoverflow.com/q/46768314
tags question: http://stackoverflow.com/q/46854394
tags question: http://stackoverflow.com/q/46837491
tags question: http://stackoverflow.com/q/46781292
tags question: http://stackoverflow.com/q/46851971
tags question: http://stackoverflow.com/q/46791395
tag name: pyqt
tags question: http://stackoverflow.com/q/46778623
tags question: http://stackoverflow.com/q/46900213
tags question: http://stackoverflow.com/q/46825989
tags question: http://stackoverflow.com/q/46785577

http://stackoverflow.com/comment/80771744
type: AnswerComment
comment on: http://stackoverflow.com/a/46902176
type: Comment
score: 0
has text: Gave me the error: TypeError: int() argument must be a string or a number, not 'generator'

http://stackoverflow.com/comment/115420725
comment on: http://stackoverflow.com/a/46755405
has text: In the above code, if I am keeping 'binary=True' while vectorizing the text, am getting different Mutual Information results. Ideally, mutual information on categorical variables works solely based on the presence or nor right, irrespective of the count?
score: 0
type: AnswerComment
type: Comment

selenium
tags question: http://stackoverflow.com/q/46889844
tags question: http://stackoverflow.com/q/46774876
tags question: http://stackoverflow.com/q/46776610
tags question: http://stackoverflow.com/q/46774701
tags question: http://stackoverflow.com/q/46758649
tags question: http://stackoverflow.com/q/46770697
tags question: http://stackoverflow.com/q/46867341
tags question: http://stackoverflow.com/q/46798038
tags question: http://stackoverflow.com/q/46795098
tags question: http://stackoverflow.com/q/46844771
tags question: http://stackoverflow.com/q/46895686
tags question: http://stackoverflow.com/q/46822195
tags question: http://stackoverflow.com/q/46881560
tags question: http://stackoverflow.com/q/46778765
tags question: http://stackoverflow.com/q/46786278
tags question: http://stackoverflow.com/q/46836336
tags question: http://stackoverflow.com/q/46803702
tags question: http://stackoverflow.com/q/46760758
tags question: http://stackoverflow.com/q/46751028
tags question: http://stackoverflow.com/q/46783333
tags question: http://stackoverflow.com/q/46758229
tags question: http://stackoverflow.com/q/46888006
tags question: http://stackoverflow.com/q/46856934
tags question: http://stackoverflow.com/q/46881673
tags question: http://stackoverflow.com/q/46862430
tags question: http://stackoverflow.com/q/46860669
tags question: http://stackoverflow.com/q/46788478
tag name: selenium
tags question: http://stackoverflow.com/q/46852584
tags question: http://stackoverflow.com/q/46754929
tags question: http://stackoverflow.com/q/46817873
tags question: http://stackoverflow.com/q/46784644
tags question: http://stackoverflow.com/q/46774120
tags question: http://stackoverflow.com/q/46793444
tags question: http://stackoverflow.com/q/46894503
tags question: http://stackoverflow.com/q/46753638
tags question: http://stackoverflow.com/q/46887762
tags question: http://stackoverflow.com/q/46830631
tags question: http://stackoverflow.com/q/46842724
tags question: http://stackoverflow.com/q/46825440
tags question: http://stackoverflow.com/q/46795927
tags question: http://stackoverflow.com/q/46783339
tags question: http://stackoverflow.com/q/46790702
tags question: http://stackoverflow.com/q/46869895
tags question: http://stackoverflow.com/q/46854971
tags question: http://stackoverflow.com/q/46755470
tags question: http://stackoverflow.com/q/46756322
tags question: http://stackoverflow.com/q/46782154
tags question: http://stackoverflow.com/q/46874039
tags question: http://stackoverflow.com/q/46763675
tags question: http://stackoverflow.com/q/46847696
tags question: http://stackoverflow.com/q/46830790
tags question: http://stackoverflow.com/q/46891254
tags question: http://stackoverflow.com/q/46867510
tags question: http://stackoverflow.com/q/46792079
tags question: http://stackoverflow.com/q/46791043
tags question: http://stackoverflow.com/q/46773924
tags question: http://stackoverflow.com/q/46903491
tags question: http://stackoverflow.com/q/46866093
tags question: http://stackoverflow.com/q/46798192
tags question: http://stackoverflow.com/q/46776659
tags question: http://stackoverflow.com/q/46798527
tags question: http://stackoverflow.com/q/46822744
tags question: http://stackoverflow.com/q/46820559
tags question: http://stackoverflow.com/q/46811568
tags question: http://stackoverflow.com/q/46858082
tags question: http://stackoverflow.com/q/46811465
tags question: http://stackoverflow.com/q/46779904
tags question: http://stackoverflow.com/q/46830036
tags question: http://stackoverflow.com/q/46900878
tags question: http://stackoverflow.com/q/46787989
tags question: http://stackoverflow.com/q/46844555
type: Tag
tags question: http://stackoverflow.com/q/46832964
tags question: http://stackoverflow.com/q/46820353
tags question: http://stackoverflow.com/q/46775666
tags question: http://stackoverflow.com/q/46888108
tags question: http://stackoverflow.com/q/46851646
tags question: http://stackoverflow.com/q/46829641
tags question: http://stackoverflow.com/q/46895043

http://stackoverflow.com/a/48367811
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/46758958
score: 3
downvote count: 0
has body: This work for me: Copy relevant deployment folder from the \models\slim directory paste it to Python\Lib\site-packages directory then run again.It will work!

http://stackoverflow.com/comment/80649991
type: Comment
has text: Thanks for your comment! I guess pythonl lists would be slower than C arrays right? I've never used malloc nor free before, do you know how the code would need to look like?
type: AnswerComment
comment on: http://stackoverflow.com/a/46851063
score: 0

facebook-graph-api
tags question: http://stackoverflow.com/q/46751336
tag name: facebook-graph-api
tags question: http://stackoverflow.com/q/46805634
tags question: http://stackoverflow.com/q/46809778
tags question: http://stackoverflow.com/q/46774437
type: Tag

http://stackoverflow.com/a/46797304
has comment: http://stackoverflow.com/comment/80543544
downvote count: 0
has body: There is no such thing in Jupyter as 'highligh and run'. At least I am not aware of it. Run the cell after commenting the other lines out using CTRL + /, split cells and execute only the chosen ones or use a debugger (e.g. pudb, it works in Jupyter) to change variables values on the fly (while debugging).
answers question: http://stackoverflow.com/q/46797224
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/46870075
accepted answer: http://stackoverflow.com/a/46870254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46870284
has answer: http://stackoverflow.com/a/46870289
tagged with: list
tagged with: sum
score: 0
has body: I've posted a question similar to this, but I'm still having trouble with several things. I have a list of tuples that looks like this: [(1, 0.5, 'min'), (2, 3, 'NA'), (3, 6, 'NA'), (4, 40, 'NA'), (5, 90, 'NA'), (6, 130.8, 'max'), (7, 129, 'NA'), (8, 111, 'NA'), (9, 8, 'NA'), (10, 9, 'NA'), (11, 0.01, 'min'), (12, 9, 'NA'), (13, 40, 'NA'), (14, 90, 'NA'), (15, 130.1, 'max'), (16, 112, 'NA'), (17, 108, 'NA'), (18, 90, 'NA'), (19, 77, 'NA'), (20, 68, 'NA'), (21, 0.9, 'min'), (22, 8, 'NA'), (23, 40, 'NA'), (24, 90, 'NA'), (25, 92, 'NA'), (26, 130.4, 'max')] I am running experiments for which each experiment has exactly one "min" and one "max" value. I want to sum up the elements in the first element up to only one "min" and "max." For example, this small dataset has 3 experiments because there are 3 mins and three maxes. The output would look like: exp = [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] I would also like to keep track of the values being added to the list as well so that I also have this output: exp_values = [[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]] I am having trouble trying to get started and only have a general idea so far: times = [] sum_ for item in tup_list: if item[2] != "min": sum_ += item[0] times.append(sum_)
has answer: http://stackoverflow.com/a/46870261
has title: Python calculating values in lists in intervals
type: Question
linked to: http://stackoverflow.com/q/46869112
possible better answer: http://stackoverflow.com/a/46870261
tagged with: iteration
tagged with: tuples
has answer: http://stackoverflow.com/a/46870254
has comment: http://stackoverflow.com/comment/80687594
has comment: http://stackoverflow.com/comment/80687603
tagged with: python
answer count: 4

http://stackoverflow.com/a/46833531
has comment: http://stackoverflow.com/comment/90461736
accepted answer of: http://stackoverflow.com/q/46826497
answers question: http://stackoverflow.com/q/46826497
score: 70
has comment: http://stackoverflow.com/comment/97341958
has comment: http://stackoverflow.com/comment/90491262
has comment: http://stackoverflow.com/comment/80640062
has comment: http://stackoverflow.com/comment/125626423
type: AcceptedAnswer
downvote count: 0
upvote count: 70
type: Answer
has body: You can set environment variables when an environment is activated by editing the activate.d/env_vars.sh script. See here: https://conda.io/docs/user-guide/tasks/manage-environments.html#macos-and-linux The key portions from that link are: Locate the directory for the conda environment in your Terminal window, such as /home/jsmith/anaconda3/envs/analytics. Enter that directory and create these subdirectories and files: cd /home/jsmith/anaconda3/envs/analytics mkdir -p ./etc/conda/activate.d mkdir -p ./etc/conda/deactivate.d touch ./etc/conda/activate.d/env_vars.sh touch ./etc/conda/deactivate.d/env_vars.sh Edit ./etc/conda/activate.d/env_vars.sh as follows: #!/bin/sh export MY_KEY='secret-key-value' export MY_FILE=/path/to/my/file/ Edit ./etc/conda/deactivate.d/env_vars.sh as follows:: #!/bin/sh unset MY_KEY unset MY_FILE When you run conda activate analytics, the environment variables MY_KEY and MY_FILE are set to the values you wrote into the file. When you run conda deactivate, those variables are erased.

http://stackoverflow.com/comment/80664993
type: Comment
score: 0
has text: It is filled in the scan function. If the list "dispositivos_serie" is empty it will return 0, otherwise it will return the list itself. And then in the method reader() i retrieve the data with the line: "dispositivos = q.get()" and then i use those print to see if it retrieved the data correctly.
type: QuestionComment
comment on: http://stackoverflow.com/q/46852457

http://stackoverflow.com/q/46900804
tagged with: flask
score: 0
has body: my goal is to be able to use beutifulsoup4 with Python3.4 in a flask web-app all with a elastic-beanstalk server and be able to use beautifulsoup within my main script. I have succeeded in getting a elastic beanstalk web app with flask and python 3.4 up and running smoothly with this code: from flask import Flask import time # print a nice greeting. def say_hello(username = "World"): return ' Hello %s! \n' % username # some bits of text for the page. header_text = ''' \n EB Flask Test \n ''' instructions = ''' Hint: This is a RESTful web service! Append a username to the URL (for example: /Thelonious) to say hello to someone specific. \n''' home_link = ' Back \n' footer_text = ' \n ' # EB looks for an 'application' callable by default. application = Flask(__name__) # add a rule for the index page. application.add_url_rule('/', 'index', (lambda: header_text + say_hello() + instructions + footer_text)) # add a rule when the page is accessed with a name appended to the site # URL. application.add_url_rule('/<username>', 'hello', (lambda username: header_text + say_hello(username) + home_link + footer_text)) if __name__ == "__main__": # Setting debug to True enables debug output. This line should be # removed before deploying a production app. application.debug = True application.run() requirements file looks like this: flask==0.12.2 beautifulsoup4==4.6 lxml==4.1 up until this point every thing is OK with no errors, but once I import beautifulsoup in line 3 of the python code the web page gives me this error: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. if anyone is able to provide advice or let me know if i am being to broad pleas let me know:) thanks again, j…
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/80748666
has title: can't use elastic-beanstalk and beautiful soup
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/80788567
tagged with: amazon-web-services

http://stackoverflow.com/comment/80499214
has text: Have you tried `chart_data/` without the leading `/` ?
score: 0
comment on: http://stackoverflow.com/q/46776746
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80539987
has text: It doesnt really that much
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46796467

http://stackoverflow.com/comment/80511326
comment on: http://stackoverflow.com/q/46782289
has text: @Zero I've reopened it, go ahead and post your answer.
score: 0
type: Comment
type: QuestionComment

python
tags question: http://stackoverflow.com/q/46902318
tags question: http://stackoverflow.com/q/46885888
tags question: http://stackoverflow.com/q/46779578
tags question: http://stackoverflow.com/q/46881079
tags question: http://stackoverflow.com/q/46814207
tags question: http://stackoverflow.com/q/46900658
tags question: http://stackoverflow.com/q/46870718
tags question: http://stackoverflow.com/q/46880929
tags question: http://stackoverflow.com/q/46898009
tags question: http://stackoverflow.com/q/46886937
tags question: http://stackoverflow.com/q/46848642
tags question: http://stackoverflow.com/q/46890431
tags question: http://stackoverflow.com/q/46840776
tags question: http://stackoverflow.com/q/46820178
tags question: http://stackoverflow.com/q/46883778
tags question: http://stackoverflow.com/q/46860234
tags question: http://stackoverflow.com/q/46818732
tags question: http://stackoverflow.com/q/46750152
tags question: http://stackoverflow.com/q/46884338
tags question: http://stackoverflow.com/q/46752277
tags question: http://stackoverflow.com/q/46803077
tags question: http://stackoverflow.com/q/46843833
tags question: http://stackoverflow.com/q/46852081
tags question: http://stackoverflow.com/q/46897377
tags question: http://stackoverflow.com/q/46786664
tags question: http://stackoverflow.com/q/46751438
tags question: http://stackoverflow.com/q/46807776
tags question: http://stackoverflow.com/q/46815435
tags question: http://stackoverflow.com/q/46823096
tags question: http://stackoverflow.com/q/46876388
tags question: http://stackoverflow.com/q/46900804
tags question: http://stackoverflow.com/q/46749573
tags question: http://stackoverflow.com/q/46869214
tags question: http://stackoverflow.com/q/46790702
tags question: http://stackoverflow.com/q/46754940
tags question: http://stackoverflow.com/q/46759151
tags question: http://stackoverflow.com/q/46902995
tags question: http://stackoverflow.com/q/46788734
tags question: http://stackoverflow.com/q/46774416
tags question: http://stackoverflow.com/q/46850111
tags question: http://stackoverflow.com/q/46822610
tags question: http://stackoverflow.com/q/46854596
tags question: http://stackoverflow.com/q/46751223
tags question: http://stackoverflow.com/q/46757639
tags question: http://stackoverflow.com/q/46793194
tags question: http://stackoverflow.com/q/46887030
tags question: http://stackoverflow.com/q/46829568
tags question: http://stackoverflow.com/q/46776193
tags question: http://stackoverflow.com/q/46825278
tags question: http://stackoverflow.com/q/46796108
tags question: http://stackoverflow.com/q/46762265
tags question: http://stackoverflow.com/q/46774309
tags question: http://stackoverflow.com/q/46815710
tags question: http://stackoverflow.com/q/46895885
tags question: http://stackoverflow.com/q/46804602
tags question: http://stackoverflow.com/q/46750954
tags question: http://stackoverflow.com/q/46858070
tags question: http://stackoverflow.com/q/46754214
tags question: http://stackoverflow.com/q/46860219
tags question: http://stackoverflow.com/q/46863628
tags question: http://stackoverflow.com/q/46776628
tags question: http://stackoverflow.com/q/46749022
tags question: http://stackoverflow.com/q/46860970
tags question: http://stackoverflow.com/q/46893594
tags question: http://stackoverflow.com/q/46864263
tags question: http://stackoverflow.com/q/46820292
tags question: http://stackoverflow.com/q/46829684
tags question: http://stackoverflow.com/q/46838913
tags question: http://stackoverflow.com/q/46835245
tags question: http://stackoverflow.com/q/46814749
tags question: http://stackoverflow.com/q/46792118
tags question: http://stackoverflow.com/q/46878312
tags question: http://stackoverflow.com/q/46807436
tags question: http://stackoverflow.com/q/46785786
tags question: http://stackoverflow.com/q/46821301
tags question: http://stackoverflow.com/q/46877845
tags question: http://stackoverflow.com/q/46758555
tags question: http://stackoverflow.com/q/46901509
tags question: http://stackoverflow.com/q/46835607
tags question: http://stackoverflow.com/q/46783974

http://stackoverflow.com/a/79001270
has body: For me the answer from @smarlowucf was almost sufficient, I just needed to give true as a return function: @patch('flask_jwt_extended.view_decorators.verify_jwt_in_request', lambda *_: True) def test_cameras(client): #...
type: Answer
answers question: http://stackoverflow.com/q/46846762
score: 0

http://stackoverflow.com/comment/80559027
comment on: http://stackoverflow.com/a/46805904
type: AnswerComment
type: Comment
has text: Please read my annotations. Also, from OP's requirements: (1) represent quantities; (2) represent bags -- i.e. quantities are bound to the kind, not to the bag; the bag just bundles together different kinds. This is in analogy to using any other type: You say *integer w/ value 3*, not *3 integers* to represent the compound.
score: 1

http://stackoverflow.com/comment/80689113
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46860205
has text: @Tangfeifan no problem, feel free to link to a new question here if you make a new question!
score: 0

http://stackoverflow.com/a/46919545
downvote count: 0
answers question: http://stackoverflow.com/q/46773522
has body: 2 options: Stick to session.add_request_init_listener From the source code: a) BoundStatement https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L560 The passed values are stored in raw_values, you can try to extract it b) BatchStatement https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L676 It stores all the statements and parameters used to construct this object in _statements_and_parameters. Seems it can be fetched although it’s not a public property c) Only this hook is called, I didn’t manage to find any other hooks https://github.com/datastax/python-driver/blob/master/cassandra/cluster.py#L2097 But it has nothing to do with queries actual execution - it's just a way to inspect what kind of queries has been constructed and maybe add additional callbacks/errbacks Approach it from a different angle and use traces https://datastax.github.io/python-driver/faq.html#how-do-i-trace-a-request https://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResponseFuture.get_all_query_traces Request tracing can be turned on for any request by setting trace=True in Session.execute_async(). View the results by waiting on the future, then ResponseFuture.get_query_trace() Here's an example of BatchStatement tracing using option 2: bs = BatchStatement() bs.add_all(['insert into test.test(test_type, test_desc) values (%s, %s)', 'insert into test.test(test_type, test_desc) values (%s, %s)', 'delete from test.test where test_type=%s', 'update test.test set test_desc=%s where test_type=%s'], [['hello1', 'hello1'], ['hello2', 'hello2'], ['hello2'], ['hello100', 'hello1']]) res = session.execute(bs, trace=True) trace = res.get_query_trace() for event in trace.events: if event.description.startswith('Parsing'): print event.description It produces the following output: Parsing insert into test.test(test_type, test_desc) values ('hello1', 'hello1') Parsing insert into test.test(test_type, test_desc) values ('hello2', …
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/81272894
has comment: http://stackoverflow.com/comment/80788143
accepted answer of: http://stackoverflow.com/q/46773522
has comment: http://stackoverflow.com/comment/80788108
type: AcceptedAnswer

http://stackoverflow.com/q/46783124
accepted answer: http://stackoverflow.com/a/46783213
answer count: 1
downvote count: 0
has title: Nginx + uWSGI worker is killed by signal 6 during a request
favorite count: 0
has answer: http://stackoverflow.com/a/46783213
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: uwsgi
has body: nginx + uwsgi + flask DAMN ! worker 15 (pid: 17149) died, killed by signal 6 :( trying respawn ... Respawned uWSGI worker 15 (new pid: 30157) what's the meaning of singal 6? And how can I find all the singal meanings? Which I only knew is that the singal 9 meansit received a SIGKILL, thanks!
type: Question

http://stackoverflow.com/q/46834086
answer count: 1
tagged with: pythonpath
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: specify the python interpreter path in python script
has comment: http://stackoverflow.com/comment/80615948
has body: I have a python script which I am distributing in several nodes. I have python 2.6 installed in /usr/bin by default and have python 2.7 in my /opt directory in all the nodes. Now when I run the script from my current node I can set the path to python 2.7 interpreter from terminal but I am unable to manage it in the rest of the nodes where this script is getting distributed. I have added the shebang at the start of script like - #!/opt/python2.7/bin/python But its still not working. How can I change the python interpreter/python path at the beginning of the script itself.
score: 2
has comment: http://stackoverflow.com/comment/80616103
upvote count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/46834476
type: Question
tagged with: shebang
has comment: http://stackoverflow.com/comment/80616239
has comment: http://stackoverflow.com/comment/80616196
has comment: http://stackoverflow.com/comment/80615831
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80615968

http://stackoverflow.com/q/46900584
has comment: http://stackoverflow.com/comment/80780011
answer count: 1
has comment: http://stackoverflow.com/comment/80787405
has comment: http://stackoverflow.com/comment/80783085
has comment: http://stackoverflow.com/comment/80782524
favorite count: 0
has title: how can I make QGridLayout() resizable in both horizontal and vertical directions?
tagged with: qgridlayout
tagged with: python
has comment: http://stackoverflow.com/comment/80783192
has answer: http://stackoverflow.com/a/46920360
accepted answer: http://stackoverflow.com/a/46920360
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/80750829
has comment: http://stackoverflow.com/comment/80781888
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/80787741
upvote count: 2
has body: I can successfully get the layout correctly with the code below, how can I resize this QGridLayout horizontally and vertically? self._s_q0= QLabel(u'what is your favorite color?') self._e_q0 = QLineEdit(self) self._e_q0.setText("yellow is the best color I can think of") self._s_q1= QLabel(u'what is your favorite animal?') self._e_q1 = QLineEdit(self) self._e_q1.setText("cat or dog") self._s_q2= QLabel(u'do you like swimming?') self._e_q2 = QLineEdit(self) self._e_q2.setText("not at all") self._s_q3= QLabel(u'what date is it today?') self._e_q3 = QLineEdit(self) self._e_q3.setText("i dont know, you can ask Tom, he has a cellphone with him right now") self._groupData = QGroupBox("100 questions list", self) self._groupData_layout = QGridLayout() self._groupData.setLayout(self._groupData_layout) self._groupData_layout.addWidget(self._s_q0, 0, 0) self._groupData_layout.addWidget(self._e_q0, 0, 1) self._groupData_layout.addWidget(self._s_q1, 1, 0) self._groupData_layout.addWidget(self._e_q1, 1, 1) self._groupData_layout.addWidget(self._s_q2, 2, 0) self._groupData_layout.addWidget(self._e_q2, 2, 1) self._groupData_layout.addWidget(self._s_q3, 3, 0) self._groupData_layout.addWidget(self._e_q3, 3, 1) ----------------------- Add more description. I can get the layout correctly, the layout generated by code now is like below. The width of this layout is too wide, how can I resize it smaller but not change the font size, how can I add a scorll bar to this QGridLayout? Same for height, there are 100 questions, QGridLayout will be too long to show them all. How can I resize the height of QGridLayout, scroll bar? Below image is the final result I want Only show partial of the layout to save space for UI. Drag scroll bar to show other part of this layout. I don't know how to do it in code, just edit picture with paint.
has comment: http://stackoverflow.com/comment/80782888
has comment: http://stackoverflow.com/comment/80787487
tagged with: pyqt

http://stackoverflow.com/q/46902801
has body: I have the following variables: InputNumber (user defined from 1 to 6), nameofstate (list of 2 names, let's call them X and Y) list[state][protein][counts][x] list[state][protein][counts][y], where x and y are lists that will equal the length of InputNumber So where InputNumber = 3 list[state][protein][counts][x] = [a,b,c] list[state][protein][counts][y] = [r,s,t] Where InputNumber = 4 list[state][protein][counts][x] = [a,b,c,d] list[state][protein][counts][y] = [r,s,t,u] I want to create new columns for these counts, but I can't figure out how to make dynamic column headers: Name X1 X2 X3 Y1 Y2 Y3 Name X1 X2 X3 X4 Y1 Y2 Y3 Y4 Name a b c r s t Name a b c d r s t u Here is the code I have for my headers: listheaders = [str(nameofstate[0]) + str(x + 1) for x in range(0, InputNumber), str(nameofstate[1]) + str(x + 1) for x in range(0, InputNumber)] with open("PATH and NAME" + ".csv", 'w') as myfile: wr = csv.writer(myfile, delimiter=',', lineterminator='\n') wr.writerow(["Name", (i for i in listheaders[0]), (e for e in listheaders[1]]) for name in anotherlist: perform the same iterative code My problem is with the generator expression - I can't wrap my head around how to tell it to unpack the entries in listheaders.
answer count: 1
has comment: http://stackoverflow.com/comment/80796666
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80753575
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80752388
tagged with: list
has title: Python: write to csv, create headers for dynamic number of output columns
has answer: http://stackoverflow.com/a/46903355
type: Question

http://stackoverflow.com/comment/80496920
has text: @chepner Cool, now add a proper answer so future users can benefit.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46775606

http://stackoverflow.com/comment/80700675
score: 0
has text: @UKcodeNovice What do you want to do after reading the lines? Would it be okay to make the lines as a list?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46872719

http://stackoverflow.com/q/46763469
has answer: http://stackoverflow.com/a/46763534
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80472150
has body: I have been trying to build a regex which can capture: All letter strings, such as 'abc', 'def' Strings with letters and numbers such as '123a', 'a23b', 'df4' but not to capture pure numbers such as: '123' '123.23' Any help is appreciated!
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/46763500
has title: Regular Expression: Matching letters or letters with numbers only
accepted answer: http://stackoverflow.com/a/46763534
type: AnsweredQuestion
downvote count: 2
possible better answer: http://stackoverflow.com/a/46763500
type: Question
score: -2

http://stackoverflow.com/a/46888138
score: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/80723262
has comment: http://stackoverflow.com/comment/101855813
has body: Python has the option of an else: clause for while loops. This is called if you do not call break, so these are equivalent: while condition: while second_condition: if condition1: break if condition1: continue do_something_if_no_break() and: while condition: while second_condition: if condition1: break else: do_something_if_no_break()
accepted answer of: http://stackoverflow.com/q/46887990
answers question: http://stackoverflow.com/q/46887990
has comment: http://stackoverflow.com/comment/80723316
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80723425
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/101842489

http://stackoverflow.com/comment/80660003
type: Comment
type: QuestionComment
score: 0
has text: @Actuary I was thinking to create a dictionary list of all possible header columns and then read the data and output the rows if the column exist for that row
comment on: http://stackoverflow.com/q/46855183

http://stackoverflow.com/comment/80673441
type: Comment
has text: Why do you consider 5.9, 12.6, and 8.9 to be odd numbers? Strictly speaking the categories "even" and "odd" apply to whole numbers, it's not clear how to extend them to handle non-integers.
comment on: http://stackoverflow.com/q/46862849
score: 0
type: QuestionComment

windows
tags question: http://stackoverflow.com/q/46760589
tags question: http://stackoverflow.com/q/46853112
tags question: http://stackoverflow.com/q/46898404
tags question: http://stackoverflow.com/q/46853024
tags question: http://stackoverflow.com/q/46758210
tags question: http://stackoverflow.com/q/46871570
tags question: http://stackoverflow.com/q/46755445
tags question: http://stackoverflow.com/q/46876110
tags question: http://stackoverflow.com/q/46873212
tags question: http://stackoverflow.com/q/46749584
tags question: http://stackoverflow.com/q/46769620
tags question: http://stackoverflow.com/q/46869895
tags question: http://stackoverflow.com/q/46846518
tags question: http://stackoverflow.com/q/46870241
tags question: http://stackoverflow.com/q/46818993
tags question: http://stackoverflow.com/q/46824604
tags question: http://stackoverflow.com/q/46776588
tags question: http://stackoverflow.com/q/46890172
tags question: http://stackoverflow.com/q/46840481
type: Tag
tags question: http://stackoverflow.com/q/46808459
tags question: http://stackoverflow.com/q/46895718
tags question: http://stackoverflow.com/q/46826969
tags question: http://stackoverflow.com/q/46835221
tags question: http://stackoverflow.com/q/46844621
tags question: http://stackoverflow.com/q/46810824
tags question: http://stackoverflow.com/q/46896093
tags question: http://stackoverflow.com/q/46798241
tags question: http://stackoverflow.com/q/46772252
tag name: windows
tags question: http://stackoverflow.com/q/46821216
tags question: http://stackoverflow.com/q/46798448

http://stackoverflow.com/q/46884197
score: -2
has comment: http://stackoverflow.com/comment/80716784
has comment: http://stackoverflow.com/comment/80715789
has title: How to know process interrupted in python?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80715768
has answer: http://stackoverflow.com/a/46884502
has comment: http://stackoverflow.com/comment/80715651
has body: from my debug log , I found my process have been interrupted , I have set try-catch in my code as below, try: print "update query : ........" query = ("Update Logs set id = "+str(id)+" where Sid = '"+str(id)+"'") cursor.execute(query) conn.commit() except (MySQLdb.Error, MySQLdb.Warning) as e: sqlerrlogs = open("/log/mysqlerr.log","a") sqlerrlogs.write(str(datetime.now())) sqlerrlogs.write('\n') sqlerrlogs.write(e) sqlerrlogs.write('\n\n') but from my log , after print "update query : ........" , there's no error in my log ,how to fix my code in order to know what's happened ? my python version is 2.7
downvote count: 3
tagged with: mysql
upvote count: 1
has comment: http://stackoverflow.com/comment/80715814
type: Question
tagged with: try-catch

http://stackoverflow.com/comment/80453355
type: QuestionComment
has text: You should post your code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46753845

http://stackoverflow.com/q/46890439
downvote count: 1
type: Question
tagged with: audio
has body: I've been attempting to get an mp3 file run due to python, but i can get it to work, I'm not sure whether the os module can't run an mp3 or i'm just missing something.
has answer: http://stackoverflow.com/a/46891289
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/80728177
has comment: http://stackoverflow.com/comment/80728121
answer count: 1
tagged with: unicode
favorite count: 0
tagged with: python
has title: I keep getting a unicode error message when running some os-module code on python(opening an mp3)
type: UnansweredQuestion

http://stackoverflow.com/comment/80652978
score: 1
has text: bad idea to click pkg-button without additional specification, as it could be not unique
type: AnswerComment
comment on: http://stackoverflow.com/a/46851735
type: Comment

http://stackoverflow.com/a/46881251
score: 0
answers question: http://stackoverflow.com/q/46881079
has body: Try this: infile = open("ALE.txt", "r") outfile = open("ALE_sorted.txt", "w") master_data = [] # Load in data from the infile and calculate the win percentage. for line in infile: data = line.strip().split(', ') wins = int(data[2]) percentage = 162 / wins data.append(str(round(percentage, 3))) master_data.append(data) # Sort by the last column in reverse order by value and store the # sorted values and original indices in a list of tuples. sorted_column = sorted([(float(data[-1]), index) for index, data in \ enumerate(master_data)], reverse = True) # Reassign master_data according to the sorted positions. master_data = [master_data[data[1]] for data in sorted_column] # Write each line to the outfile. for data in master_data: outfile.write(str(", ".join(data) + "\n")) infile.close() outfile.close() Where the contents of infile are the following: Baltimore, 93, 69 Boston, 69, 93 New York, 95, 67 Tampa Bay, 90, 72 Toronto, 73, 89 The resultant outfile contains the following sorted by the values of the newly generated fourth column from highest to lowest: New York, 95, 67, 2.418 Baltimore, 93, 69, 2.348 Tampa Bay, 90, 72, 2.25 Toronto, 73, 89, 1.82 Boston, 69, 93, 1.742
type: Answer
has comment: http://stackoverflow.com/comment/80710434
has comment: http://stackoverflow.com/comment/80710270
has comment: http://stackoverflow.com/comment/80710051
has comment: http://stackoverflow.com/comment/80710594

http://stackoverflow.com/a/46864656
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46864498
has body: That will fix all your issues with loop. User=['name123'] username=raw_input("Enter username : ") while username in User: username=raw_input("Username already taken.\nEnter another username :") P.S. I'm strongly recommend you to read Dive Into Python and The Zen of Python
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46864498
score: 1

http://stackoverflow.com/q/46761851
tagged with: python
tagged with: dictionary
has body: I am writing a code to serve as a gradebook for a class I teach. While I have a working code without classes, I am learning and trying to incorporate classes into my code. I have a class StudentSpecs. There are a lot of things defined in the class (such as name and ID number) but the relevant parts are: class AstronomyLab154L: class StudentSpecs: def __init__(self, points=None, grade=None): self.points = points self.grade = grade def __str__(self): return "\nTotal Points: %s \nGrade: %s" %(self.points, self.grade) def set_points(self, points): self.points = points def set_grade(self, grade): self.grade = grade def get_points(self, points): return self.points def get_grade(self, grade): return self.grade Using this, my code (available upon request but left out to shorten the post) will read a .csv file (via MS Excel) and create an instance of the StudentSpecs class for each row in the file (each row is a different student, each column represents different assignment scores). So, I can access the total points and letter grade of each student in a loop like so. ## classroom = list of student instances for student in classroom: print(student.points, student.grade) ## example of output 88.0 B 94.0 A 82.5 B- 52.0 F My goal is to create a histogram of the classroom data, such that the x-axis ticklabels (centered at bins) will store letter-grades and the y-axis will store the number of students with the corresponding letter-grade. I can make the histogram using numpy and matplotlib. But, I don't know how to apply Counter to my class instance. My attempt is below. from collections import Counter def display_classroom_specs(classroom): ## initialize dict since Counter is a dict grade_counts = {} ## update dictionary for each student in classroom for student in classroom: grade_counts += Counter(student.grade) ## y-axis of histogram return grade_counts print(display_classroom_specs(classroom)) ## throws an error TypeError: unsupported operand type(s) for +=: 'dict' and 'Counte…
has comment: http://stackoverflow.com/comment/80469122
tagged with: instance
has comment: http://stackoverflow.com/comment/80469283
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46761905
tagged with: class
answer count: 2
possible better answer: http://stackoverflow.com/a/46761889
downvote count: 0
tagged with: counter
has answer: http://stackoverflow.com/a/46761889
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46761905
has title: How can I apply a Counter to multiple class instances called in a loop?

http://stackoverflow.com/comment/80614235
score: 1
comment on: http://stackoverflow.com/q/46832760
type: Comment
type: QuestionComment
has text: What does the output of `print tweets_df['lang']` look like?

http://stackoverflow.com/comment/80451163
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46752629
score: 0
has text: It is probably because your system didn't initialize the $HOME environment variable yet, or it points to a location which "Pictures" is not exists in. It is highly depends on where you put your script in and in what stage it is been executed. I'd suggest you to use hard coded path to the folder or alternatively, to execute the script in other way (`.bashrc` for example).

http://stackoverflow.com/a/46902069
upvote count: 7
answers question: http://stackoverflow.com/q/46901975
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80750930
has comment: http://stackoverflow.com/comment/80750903
accepted answer of: http://stackoverflow.com/q/46901975
score: 7
has body: if your list data like this: data = ['I want to make everything lowercase', '', ''] data = [k.lower() for k in data] if your list data is a list of string list: data = [['I want to make everything lowercase'], ['']] data = [[k.lower()] for l in data for k in l] the fact is that list don't has attribute 'items'

pandas
tags question: http://stackoverflow.com/q/46778674
tags question: http://stackoverflow.com/q/46904135
tags question: http://stackoverflow.com/q/46842554
tags question: http://stackoverflow.com/q/46775615
tags question: http://stackoverflow.com/q/46842225
tags question: http://stackoverflow.com/q/46900483
tags question: http://stackoverflow.com/q/46806827
tags question: http://stackoverflow.com/q/46794812
tags question: http://stackoverflow.com/q/46790390
tags question: http://stackoverflow.com/q/46860038
tags question: http://stackoverflow.com/q/46771137
tags question: http://stackoverflow.com/q/46831363
tags question: http://stackoverflow.com/q/46854545
tags question: http://stackoverflow.com/q/46758104
tags question: http://stackoverflow.com/q/46800447
tags question: http://stackoverflow.com/q/46850934
tags question: http://stackoverflow.com/q/46827814
tags question: http://stackoverflow.com/q/46869116
tags question: http://stackoverflow.com/q/46777637
tags question: http://stackoverflow.com/q/46780792
tags question: http://stackoverflow.com/q/46830951
tags question: http://stackoverflow.com/q/46751581
tags question: http://stackoverflow.com/q/46784330
tags question: http://stackoverflow.com/q/46749573
tags question: http://stackoverflow.com/q/46812223
tags question: http://stackoverflow.com/q/46854065
tags question: http://stackoverflow.com/q/46855602
tags question: http://stackoverflow.com/q/46762265
tags question: http://stackoverflow.com/q/46798252
tags question: http://stackoverflow.com/q/46770482
tags question: http://stackoverflow.com/q/46822149
tags question: http://stackoverflow.com/q/46755672
tags question: http://stackoverflow.com/q/46813478
tags question: http://stackoverflow.com/q/46852242
tags question: http://stackoverflow.com/q/46768344
tags question: http://stackoverflow.com/q/46894493
tags question: http://stackoverflow.com/q/46818223
tags question: http://stackoverflow.com/q/46769786
tags question: http://stackoverflow.com/q/46900659
tags question: http://stackoverflow.com/q/46822985
tags question: http://stackoverflow.com/q/46823312
tags question: http://stackoverflow.com/q/46816874
tags question: http://stackoverflow.com/q/46771055
tags question: http://stackoverflow.com/q/46767724
tags question: http://stackoverflow.com/q/46901513
tags question: http://stackoverflow.com/q/46819260
tags question: http://stackoverflow.com/q/46871767
tags question: http://stackoverflow.com/q/46810102
tags question: http://stackoverflow.com/q/46805907
tags question: http://stackoverflow.com/q/46821135
tags question: http://stackoverflow.com/q/46882092
tags question: http://stackoverflow.com/q/46869884
tags question: http://stackoverflow.com/q/46882047
tags question: http://stackoverflow.com/q/46852296
tags question: http://stackoverflow.com/q/46762597
tags question: http://stackoverflow.com/q/46818429
tags question: http://stackoverflow.com/q/46858499
tags question: http://stackoverflow.com/q/46840790
tags question: http://stackoverflow.com/q/46768675
tags question: http://stackoverflow.com/q/46841659
tags question: http://stackoverflow.com/q/46846761
tags question: http://stackoverflow.com/q/46773779
tags question: http://stackoverflow.com/q/46898256
tags question: http://stackoverflow.com/q/46884648
tags question: http://stackoverflow.com/q/46888890
tags question: http://stackoverflow.com/q/46879672
tags question: http://stackoverflow.com/q/46774069
tags question: http://stackoverflow.com/q/46873354
tags question: http://stackoverflow.com/q/46810889
tags question: http://stackoverflow.com/q/46823941
tags question: http://stackoverflow.com/q/46801833
tags question: http://stackoverflow.com/q/46814225
tags question: http://stackoverflow.com/q/46762633
tags question: http://stackoverflow.com/q/46822808
tags question: http://stackoverflow.com/q/46896105
tags question: http://stackoverflow.com/q/46892046
tags question: http://stackoverflow.com/q/46774792
tags question: http://stackoverflow.com/q/46826617
tags question: http://stackoverflow.com/q/46758107
tags question: http://stackoverflow.com/q/46893448

http://stackoverflow.com/comment/80744859
comment on: http://stackoverflow.com/q/46898719
has text: @xanoetux `pip` is supporting `python` - and sof is about programming. `Server Fault` tends towards networking and sysadmin. While that often includes installation of *system* software it is not so much about installing/configuring *programming* tools.
type: Comment
type: QuestionComment
score: 1

pycharm
tags question: http://stackoverflow.com/q/46894762
tags question: http://stackoverflow.com/q/46858185
tags question: http://stackoverflow.com/q/46904931
tag name: pycharm
tags question: http://stackoverflow.com/q/46847281
tags question: http://stackoverflow.com/q/46875156
tags question: http://stackoverflow.com/q/46827310
tags question: http://stackoverflow.com/q/46850735
tags question: http://stackoverflow.com/q/46850810
tags question: http://stackoverflow.com/q/46848562
tags question: http://stackoverflow.com/q/46798099
tags question: http://stackoverflow.com/q/46828437
tags question: http://stackoverflow.com/q/46869092
tags question: http://stackoverflow.com/q/46751800
tags question: http://stackoverflow.com/q/46855551
tags question: http://stackoverflow.com/q/46817583
tags question: http://stackoverflow.com/q/46782963
tags question: http://stackoverflow.com/q/46893461
tags question: http://stackoverflow.com/q/46882513
tags question: http://stackoverflow.com/q/46836564
tags question: http://stackoverflow.com/q/46903166
tags question: http://stackoverflow.com/q/46749327
tags question: http://stackoverflow.com/q/46874171
tags question: http://stackoverflow.com/q/46896457
tags question: http://stackoverflow.com/q/46777128
tags question: http://stackoverflow.com/q/46752540
tags question: http://stackoverflow.com/q/46894094
type: Tag
tags question: http://stackoverflow.com/q/46881560
tags question: http://stackoverflow.com/q/46815231
tags question: http://stackoverflow.com/q/46749434

http://stackoverflow.com/comment/80557878
score: 0
type: Comment
type: QuestionComment
has text: I tried that but to no avail. IPython shell, though, succeeds also in importing the packages... something is changing when I get to the notebook environment.
comment on: http://stackoverflow.com/q/46804725

http://stackoverflow.com/q/46894768
tagged with: python
score: 0
tagged with: tcp
answer count: 2
tagged with: server
has answer: http://stackoverflow.com/a/46895478
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46896506
has title: TCP socket reads out of turn
has body: I am using TCP with Python sockets, transfering data from one computer to another. However the recv command reads more than it should in the serverside, I could not find the issue. client.py while rval: image_string = frame.tostring() sock.sendall(image_string) rval, frame = vc.read() server.py while True: image_string = "" while len(image_string) &lt; message_size: data = conn.recv(message_size) image_string += data The length of the message is 921600 (message_size) so it is sent with sendall, however when recieved, when I print the length of the arrived messages, the lengths are sometimes wrong, and sometimes correct. 921600 921600 921923 # wrong 922601 # wrong 921682 # wrong 921600 921600 921780 # wrong As you see, the wrong arrivals have no pattern. As I use TCP, I expected more consistency, however it seems the buffers are mixed up and somehow recieving a part of the next message, therefore producing a longer message. What is the issue here ? I tried to add just the relevant part of the code, I can add more if you wish, but the code performs well on localhost but fails on two computers, so there should be no errors besides the transmitting part. Edit1: I inspected this question a bit, it mentions that all send commands in the client may not be recieved by a single recv in the server, but I could not understand how to apply this to practice.
type: Question
accepted answer: http://stackoverflow.com/a/46895478
linked to: http://stackoverflow.com/q/17667903
tagged with: sockets
possible better answer: http://stackoverflow.com/a/46896506

http://stackoverflow.com/comment/80758052
has text: So, it would mean we are not sure if Python does multithreading. I guess in Java => JVM maps app threads (or JVM threads?) to OS threads?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46905653
type: Comment

http://stackoverflow.com/a/46750494
type: AcceptedAnswer
type: Answer
score: 3
has body: It does work with python 3 perhaps just install it with pip pip install pulp Make sure you are running the right pip for your anaconda install
downvote count: 0
has comment: http://stackoverflow.com/comment/80446976
accepted answer of: http://stackoverflow.com/q/46749315
upvote count: 3
answers question: http://stackoverflow.com/q/46749315

http://stackoverflow.com/a/46878832
accepted answer of: http://stackoverflow.com/q/46878699
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Redirect STDOUT to a file-like object temporarily and call your function. Then read the entire contents of the buffer and call textwrap.indent to indent every line: import io, textwrap from contextlib import redirect_stdout output = io.StringIO() with redirect_stdout(output): func() print(textwrap.indent(output.getvalue(), '\t'), end='') outputs some text: this print with tab and this print with tab
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46878699

http://stackoverflow.com/q/46752488
has title: How to set python version for pip in virtualenv?
has comment: http://stackoverflow.com/comment/80463036
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/46758875
has comment: http://stackoverflow.com/comment/80463060
has body: Need to run some project that require installing packages available only for Python 2.7 (I can't change packages). I'm running Ubuntu 17.04 with Python 3.5.3 . I created virtual environment by issuing next command: sudo virtualenv --python=/usr/bin/python2.7 env Seems like I have version I need: (env) serv@serv:/var/m$ python -V Python 2.7.13 But when I'm trying to install packages(those only for Python 2.7) it DOESN'T look like my virtualenv is using python 2.7 what is more interested, it refers to already installed packages(I supposed that virtualenv won't have any packages,except for some default as pip). Installing mysql-python (this usually error occurs only when installing from python 3): ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-fi75i_pl/mysql-python/ When I'm installing package for Python3 - SQLAlchemy: Requirement already satisfied: SQLAlchemy in /home/loraserver/.local/lib/python3.5/site-packages What can I do to run my code from Python 2.7 environment? EDIT 1: I'm installing mysql-python by: pip install mysql-python This gives me Permission denied. When I'm trying : sudo pip install mysql-python It gives me error the same from installing python on python3.
has comment: http://stackoverflow.com/comment/80450731
has answer: http://stackoverflow.com/a/46758867
has comment: http://stackoverflow.com/comment/80462965
possible better answer: http://stackoverflow.com/a/46758867
has answer: http://stackoverflow.com/a/46758875
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80463083
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80451151
tagged with: python

bokeh
tags question: http://stackoverflow.com/q/46885052
tags question: http://stackoverflow.com/q/46786505
tags question: http://stackoverflow.com/q/46772282
type: Tag
tags question: http://stackoverflow.com/q/46844834
tags question: http://stackoverflow.com/q/46859431
tags question: http://stackoverflow.com/q/46899348
tags question: http://stackoverflow.com/q/46770189
tags question: http://stackoverflow.com/q/46831371
tags question: http://stackoverflow.com/q/46811416
tags question: http://stackoverflow.com/q/46793444
tag name: bokeh
tags question: http://stackoverflow.com/q/46846753

http://stackoverflow.com/a/46867064
has body: Rather, use pandas to read the csv: import pandas as pd df = pd.read_csv(csvfile) for additional options to read csv, refer to: pandas read csv
accepted answer of: http://stackoverflow.com/q/46867009
has comment: http://stackoverflow.com/comment/80682086
has comment: http://stackoverflow.com/comment/80681865
answers question: http://stackoverflow.com/q/46867009
has comment: http://stackoverflow.com/comment/80681951
type: Answer
has comment: http://stackoverflow.com/comment/80682112
has comment: http://stackoverflow.com/comment/80681888
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/46812789
has body: The assignment to slices of SymPy arrays are missing, you can go around this lack by using numpy. Import NumPy as: import numpy Convert the SymPy array to a NumPy array (of type object, so as to contain SymPy expressions): In [18]: A_numpy = numpy.array(A.tolist()).astype(object) Run a modified version of your for loop: In [19]: for i in range(a.shape[0]): ...: A_numpy[:, :, i] = [[cos(theta[i]), -sin(theta[i])*cos(alpha[i]), s ...: in(theta[i])*sin(alpha[i]), a[i]*cos(theta[i])], [sin(theta[i]), cos(th ...: eta[i])*cos(alpha[i]), -cos(theta[i])*sin(alpha[i]), a[i]*sin(theta[i]) ...: ], [0, sin(alpha[i]), cos(alpha[i]), d[i]], [0, 0, 0, 1]] ...: Convert the resulting NumPy array back to a SymPy array: In [20]: A = Array(A_numpy) Print it's contents: In [21]: A Out[21]: ⎡⎡cos(θ₁) -1 1 cos(θ₄) ⎤ ⎡sin(θ₁) 0 0 sin(θ₄) ⎤ ⎡0 0 0 0⎤ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢⎢ 0 0 0 -sin(θ₄) ⎥ ⎢ 0 0 1 cos(θ₄) ⎥ ⎢1 1 0 0⎥ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢⎢sin(θ₁) 0 0 0 ⎥ ⎢-cos(θ₁) 1 0 0 ⎥ ⎢0 0 1 1⎥ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎣⎣ 0 0 a₃ -a₄⋅cos(θ₄)⎦ ⎣ 0 0 0 -a₄⋅sin(θ₄)⎦ ⎣0 d₂ 0 0⎦ ⎡0 0 0 0⎤⎤ ⎢ ⎥⎥ ⎢0 0 0 0⎥⎥ ⎢ ⎥⎥ ⎢0 0 0 0⎥⎥ ⎢ ⎥⎥ ⎣1 1 1 1⎦⎦
downvote count: 0
has comment: http://stackoverflow.com/comment/80575343
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46796005
score: 1

http://stackoverflow.com/comment/81257227
has text: That's a really nice solution. Thank you!(can't upvote with this account due to low reputation, I'll vote with my normal account). Is it possible to access the `request` object in the `pytest_generate_tests` function. I would like to mock functions in a specific module which I define in a variable in a testing module.
type: AnswerComment
comment on: http://stackoverflow.com/a/46816470
type: Comment
score: 1

http://stackoverflow.com/q/46895678
has answer: http://stackoverflow.com/a/46915100
tagged with: python
tagged with: logging
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46897719
accepted answer: http://stackoverflow.com/a/46897719
has body: Consider the following logging example. There are two python files, myapp.py and mylib.py. # myapp.py import logging import mylib class customAdapter(logging.LoggerAdapter): def process(self, msg, kwargs): return '[%s] %s' % (self.extra['connid'], msg), kwargs def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO) logger = logging.getLogger('test') adapter = customAdapter(logger,{'connid': 123}) adapter.info('Started') mylib.do_something() adapter.info('Finished') if __name__ == '__main__': main() # mylib.py import logging def do_something(): lgr = logging.getLogger('test') lgr.info('Doing something') When you execute myapp.py, you get the following output to the log file: INFO:test:[123] Started INFO:test:Doing something INFO:test:[123] Finished I'm trying to get the log in inherit the contextual information acquired from the parent code. Desired output: INFO:test:[123] Started INFO:test:[123] Doing something INFO:test:[123] Finished Is this possible? (notice that "[123]" is included in line 2 of the log) Here are a few other relevant pieces of information: I'm using python 3.5 I'm trying to avoid passing any arguments to the "do_something" function. In actual use, the value for "connid" will be dynamic. This will be used in a django view. Replace main() for the django view.
favorite count: 0
upvote count: 3
has title: Python Logging: Inherit contextual information
possible better answer: http://stackoverflow.com/a/46915100

http://stackoverflow.com/a/46824485
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If I understand your question correctly, you can write your DEFAULT_STRING to a file as it is. When you want to use it to do any formatting, you would read the first line of that file and call format on that string just as in your example. You can either replace the named placeholders in DEFAULT_STRING with positional ones (e.g. {0}, {1}) or you can parse the names from the string by looking for characters between "{" and "}" and build a **kwargs dictionary to pass into .format() using the names as keys and values as in your example.
accepted answer of: http://stackoverflow.com/q/46824280
score: 1
answers question: http://stackoverflow.com/q/46824280
upvote count: 1

http://stackoverflow.com/q/46902367
has body: i=np.arange(1,4,dtype=np.int) a=np.arange(9).reshape(3,3) and a &gt;&gt;&gt;array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) a[:,0:1] &gt;&gt;&gt;array([[0], [3], [6]]) a[:,0:2] &gt;&gt;&gt;array([[0, 1], [3, 4], [6, 7]]) a[:,0:3] &gt;&gt;&gt;array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) Now I want to vectorize the array to print them all together. I try a[:,0:i] or a[:,0:i[:,None]] It gives TypeError: only integer scalar arrays can be converted to a scalar index
has answer: http://stackoverflow.com/a/46902425
favorite count: 0
has answer: http://stackoverflow.com/a/75235255
has answer: http://stackoverflow.com/a/59510314
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53192374
tagged with: python
tagged with: vectorization
has title: numpy array TypeError: only integer scalar arrays can be converted to a scalar index
score: 77
has answer: http://stackoverflow.com/a/48244173
downvote count: 0
has answer: http://stackoverflow.com/a/56108687
linked to: http://stackoverflow.com/q/1422149
type: Question
tagged with: numpy
tagged with: indexing
answer count: 8
has answer: http://stackoverflow.com/a/55369841
linked to: http://stackoverflow.com/q/48513824
has answer: http://stackoverflow.com/a/53143332
upvote count: 77

http://stackoverflow.com/q/46804503
score: 0
tagged with: pandas
upvote count: 1
has body: I try to plot a bar plot of a pivot_table with the following code: fig=plt.figure(figsize=(10,10)) ax1=fig.add_subplot(111) ax1.bar(Products.index,Products["Amount"].values) The pivot table is like: Amount Material 454T006S R 167 134:11 0.000000 3457T006S R IE216 167 246:1 4.500000 67T009S R 1510K304:1 36.000000 7676009S R IE216 1510K304:1 30.500000 676T012S 167 246:1 1.000000 2324T012S R 1510 111 6.000000 1516T012S R 1510 151 50.500000 1516T012S R 1510 20:1 26.500000 But it returns: unsupported operand type(s) for -: 'str' and 'float' What am I doing wrong?
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/46804537
accepted answer: http://stackoverflow.com/a/46804537
tagged with: bar-chart
has title: Barplot returns unsupported operand type(s) for -: 'str' and 'float'

http://stackoverflow.com/q/46837658
answer count: 4
score: 14
has body: I was checking the version of OpenCV installed previously in a system. I tried to check using from cv2 import __version__ Its gave me the following error No module named cv2 When I tried import cv, it's not giving me error. Is there a way to know the version?
has answer: http://stackoverflow.com/a/54929520
downvote count: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/75052872
has title: Checking version of OpenCV (cv)
upvote count: 15
tagged with: python-import
favorite count: 0
has answer: http://stackoverflow.com/a/46838421
tagged with: importerror
has answer: http://stackoverflow.com/a/46838826
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80601541
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46826822
has text: @Uriel We are sure.

http://stackoverflow.com/comment/80539742
score: 0
comment on: http://stackoverflow.com/q/46796126
type: Comment
type: QuestionComment
has text: @klutt we implemennt most of our algorithms in Python but some of them need to run in an ARM mcu as well. the output needs to be the same in every implementation, for the same input

http://stackoverflow.com/a/46924063
has body: I found the one-liner finally: os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts)),"d") wouldnt hve been possible without others answers though. thanks a lot.
answers question: http://stackoverflow.com/q/46904428
score: 0
type: Answer

http://stackoverflow.com/comment/80704392
has text: Yes, you can add a lot of different stuff in Python: lists, tuples, strings, integers, floats, anything that has the `__add__` magic method.
score: 0
comment on: http://stackoverflow.com/q/46877025
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/46813627
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/46823586
answer count: 2
tagged with: mocking
has body: The TestCase docs specify that assert methods can take an optional msg keyword argument to specify a message to add context to the assertion: All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also longMessage). Is there a way to do this with the unittest.mock assert methods, in particular assert_any_call?
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46823586
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/72997134
has answer: http://stackoverflow.com/a/72997134
has title: How to pass a `msg` to unittest.mock assert methods?
tagged with: unit-testing
type: Question

http://stackoverflow.com/q/46762947
accepted answer: http://stackoverflow.com/a/46763183
score: -1
possible better answer: http://stackoverflow.com/a/46763119
has title: Get last three letters in dict python
has answer: http://stackoverflow.com/a/46763183
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/80471296
has body: An example like: text = ' "west best worst first tapping snapping in a pest the straining singing forest living' a_dict = get_last_three_letters_dict(text) remove_less_than_2(a_dict) print("1.") print_dict_in_key_order(a_dict) text = 'Kublai Khan does not necessarily believe everything Marco Polo says when he describes the cities visited on his expeditions but the emperor of the Tartars does continue listening to the young Venetian with greater attention and curiosity than he shows any other messenger or explorer of his' a_dict = get_last_three_letters_dict(text) remove_less_than_2(a_dict) print("2.") print_dict_in_key_order(a_dict) I'm trying to convert the string to lower case and then returns a dictionary object which has keys which are the last three letters of any words in the string of text with length greater than 2, and corresponding values which are the number of words in the parameter string of text which end with these last three letters. The testing code removes any pairs in the resulting dictionary where the last three letters occur just the once in the string of text, I tried the function below, it doesn't work. def get_last_three_letters_dict(sentence): sentence = dict(sentence) tails = [] for letter in sentence: if len(name) &gt; 2: tails.append(name[-3:].lower()) return (''.join(tails) + ":") expected: 1. est : 4 ing : 5 rst : 2 2. han : 2 his : 2 ing : 2 oes : 2 the : 4
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46763119
type: AnsweredQuestion
downvote count: 1
type: Question

http://stackoverflow.com/comment/80583266
type: AnswerComment
type: Comment
score: 0
has text: Okay, looks like I have data in the database _before_ restarting. So something about the start process is clearing the database
comment on: http://stackoverflow.com/a/46816807

http://stackoverflow.com/comment/80526239
comment on: http://stackoverflow.com/a/46776679
type: Comment
has text: Ahh, I'm on windows 7. Is this one of those cases where windows needs a funky work around?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80674524
comment on: http://stackoverflow.com/a/46863477
type: Comment
has text: How about after the last `elif` statement, it should say: `else: return 'N/A'`
score: 0
type: AnswerComment

http://stackoverflow.com/q/46800147
tagged with: pipeline
has comment: http://stackoverflow.com/comment/82411144
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/46801622
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am using GridSearchCV with a pipeline as follows: grid = GridSearchCV( Pipeline([ ('reduce_dim', PCA()), ('classify', RandomForestClassifier(n_jobs = -1)) ]), param_grid=[ { 'reduce_dim__n_components': range(0.7,0.9,0.1), 'classify__n_estimators': range(10,50,5), 'classify__max_features': ['auto', 0.2], 'classify__min_samples_leaf': [40,50,60], 'classify__criterion': ['gini', 'entropy'] } ], cv=5, scoring='f1') grid.fit(X,y) How do I now retrieve PCA details like components and explained_variance from the grid.best_estimator_ model? Furthermore, I also want to save the best_estimator_ to a file using pickle and later load it. How do I retrieve the PCA details from this loaded estimator? I suspect it will be the same as above.
type: Question
has title: sklearn - How to retrieve PCA components and explained variance from inside a Pipeline passed to GridSearchCV
tagged with: grid-search
accepted answer: http://stackoverflow.com/a/46801622
upvote count: 2

http://stackoverflow.com/q/46779708
favorite count: 0
has comment: http://stackoverflow.com/comment/80505413
has body: I am trying to program a DHT11 temperature and Humidity sensor using my Raspberry Pi 3 model B. I am using a Python script on the shell, but it is not working because here because of a syntax error. I am trying to run it on the raspberry pi terminal and the error message is in the print statement.
has comment: http://stackoverflow.com/comment/80505660
tagged with: sensors
tagged with: python
has comment: http://stackoverflow.com/comment/80505429
has comment: http://stackoverflow.com/comment/80505438
type: AnsweredQuestion
has title: Python script: Syntax error
score: -5
has comment: http://stackoverflow.com/comment/80505492
downvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/80505419
has answer: http://stackoverflow.com/a/46791764
upvote count: 0
tagged with: temperature
answer count: 1
tagged with: raspberry-pi3
accepted answer: http://stackoverflow.com/a/46791764

http://stackoverflow.com/comment/80478475
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46766077
type: Comment
has text: How I understand the question (I admit it is a bit vague), the first number in the output array always defaults to zero as there are no larger numbers before the first number of the input array. Of course we could set output as [] and set the range as (0, len(foo)), it would work as well and do the same thing. I just chose to do it like this.

http://stackoverflow.com/comment/80657964
has text: Let me know if the issue is resolved with my earlier comment
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46837679
score: 0

http://stackoverflow.com/comment/80455329
type: Comment
type: QuestionComment
score: 0
has text: try printing linesInBytes before sending it and see what it contains, please read https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal
comment on: http://stackoverflow.com/q/46754943

http://stackoverflow.com/comment/80655444
score: 0
type: Comment
type: QuestionComment
has text: Run it, the .exe (what's unclear about *show some output of calling your python3.6 in the console*?)
comment on: http://stackoverflow.com/q/46853873

http://stackoverflow.com/q/46832125
answer count: 2
downvote count: 1
has title: Why does the PHP code function differently than the Python code?
has answer: http://stackoverflow.com/a/46832326
favorite count: 0
has answer: http://stackoverflow.com/a/46832318
tagged with: python
tagged with: php
type: AnsweredQuestion
score: 1
tagged with: computer-science
type: Question
linked to: http://stackoverflow.com/q/22598547
has comment: http://stackoverflow.com/comment/80613213
accepted answer: http://stackoverflow.com/a/46832326
has comment: http://stackoverflow.com/comment/80611977
possible better answer: http://stackoverflow.com/a/46832318
has body: PHP program $x = (False or 123) echo $x python code x= (False or 123) print(x) In php answer is 1 and in python answer is 123. Why is that?
upvote count: 2

http://stackoverflow.com/comment/80710391
comment on: http://stackoverflow.com/a/46881541
has text: fair enough. added.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80457060
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46755129
has text: In any case, I'd guess that `canvas.drawPolygon(triangle1, canvas)` the error. Rest seems fine.
type: Comment

http://stackoverflow.com/a/46795572
type: Answer
has body: p = int(input("Input a number: ")) n = int(input("Input a number: ")) for i in range(1, p+1): s = n%p v = n - s k = (v//p) if s == 0: print(f'{n} nuts = {k} nuts for cow#{i} and no nuts for the snake') if s == 1: print(f'{n} nuts = {k} nuts for cow#{i} and 1 nut for the snake') if s &gt; 1: print(f'{n} nuts = {k} nuts for cow#{i} and {s} nuts for the snake') n = k*(p-1)
score: 0
answers question: http://stackoverflow.com/q/46780307

django
tags question: http://stackoverflow.com/q/46902966
tags question: http://stackoverflow.com/q/46770630
tags question: http://stackoverflow.com/q/46877639
tags question: http://stackoverflow.com/q/46902357
tags question: http://stackoverflow.com/q/46880999
tags question: http://stackoverflow.com/q/46877090
tags question: http://stackoverflow.com/q/46817450
tags question: http://stackoverflow.com/q/46756381
tags question: http://stackoverflow.com/q/46749405
tags question: http://stackoverflow.com/q/46818255
tags question: http://stackoverflow.com/q/46902711
tags question: http://stackoverflow.com/q/46776746
tags question: http://stackoverflow.com/q/46898796
tags question: http://stackoverflow.com/q/46818431
tags question: http://stackoverflow.com/q/46806223
tags question: http://stackoverflow.com/q/46889366
tags question: http://stackoverflow.com/q/46817346
tags question: http://stackoverflow.com/q/46820315
tags question: http://stackoverflow.com/q/46810058
tags question: http://stackoverflow.com/q/46816707
tags question: http://stackoverflow.com/q/46792488
tags question: http://stackoverflow.com/q/46756833
tags question: http://stackoverflow.com/q/46819866
tags question: http://stackoverflow.com/q/46772796
tags question: http://stackoverflow.com/q/46755329
tags question: http://stackoverflow.com/q/46750706
tags question: http://stackoverflow.com/q/46773329
tags question: http://stackoverflow.com/q/46890365
tags question: http://stackoverflow.com/q/46877209
tags question: http://stackoverflow.com/q/46820876
tags question: http://stackoverflow.com/q/46805903
tags question: http://stackoverflow.com/q/46818891
tags question: http://stackoverflow.com/q/46761498
tags question: http://stackoverflow.com/q/46875745
tags question: http://stackoverflow.com/q/46759730
tags question: http://stackoverflow.com/q/46837068
tags question: http://stackoverflow.com/q/46855180
tags question: http://stackoverflow.com/q/46767186
tags question: http://stackoverflow.com/q/46763462
tags question: http://stackoverflow.com/q/46841727
tags question: http://stackoverflow.com/q/46804573
tags question: http://stackoverflow.com/q/46761148
tags question: http://stackoverflow.com/q/46877593
tags question: http://stackoverflow.com/q/46784426
tags question: http://stackoverflow.com/q/46905022
tags question: http://stackoverflow.com/q/46861946
tags question: http://stackoverflow.com/q/46849588
tags question: http://stackoverflow.com/q/46826297
tags question: http://stackoverflow.com/q/46891472
tags question: http://stackoverflow.com/q/46755451
tags question: http://stackoverflow.com/q/46797382
tags question: http://stackoverflow.com/q/46834082
tags question: http://stackoverflow.com/q/46825734
tags question: http://stackoverflow.com/q/46863105
type: Tag
tags question: http://stackoverflow.com/q/46885308
tags question: http://stackoverflow.com/q/46756237
tags question: http://stackoverflow.com/q/46860302
tags question: http://stackoverflow.com/q/46875587
tags question: http://stackoverflow.com/q/46855434
tags question: http://stackoverflow.com/q/46828093
tags question: http://stackoverflow.com/q/46832186
tags question: http://stackoverflow.com/q/46837552
tags question: http://stackoverflow.com/q/46893226
tags question: http://stackoverflow.com/q/46869405
tags question: http://stackoverflow.com/q/46875205
tags question: http://stackoverflow.com/q/46898515
tags question: http://stackoverflow.com/q/46879368
tags question: http://stackoverflow.com/q/46849849
tags question: http://stackoverflow.com/q/46855553
tags question: http://stackoverflow.com/q/46764574
tags question: http://stackoverflow.com/q/46873618
tags question: http://stackoverflow.com/q/46898217
tags question: http://stackoverflow.com/q/46755423
tags question: http://stackoverflow.com/q/46787651
tags question: http://stackoverflow.com/q/46769067
tags question: http://stackoverflow.com/q/46793377
tags question: http://stackoverflow.com/q/46847900
tags question: http://stackoverflow.com/q/46829997
tags question: http://stackoverflow.com/q/46822797

http://stackoverflow.com/a/46839474
has comment: http://stackoverflow.com/comment/80646602
has comment: http://stackoverflow.com/comment/80645780
score: 0
has body: I know it looks strange, however I like the idea of passing data as iterable in pathos. To achieve what you are looking for you must pass the elements as a separate iterable item. Here is an example: def g(self): pool = pt.multiprocessing.ProcessPool() def _h(a, b, c): k = self.f(a, b, c) return k/2 result = [pool.amap(_h, (i,),( j,),(k,))) for i in range(3) for j in range(5) for k in range(7)] return result Please notice the strange way of passing parameters here: pool.amap(_h, (i,),( j,),(k,)) You can get an idea why it is done so if you trace _pool.map_async(star(f), zip(*args)) call a bit. In general, you might want to call your function multiple times with different parameters. Here is what I've done to demonstrate it: def g(self): pool = pt.multiprocessing.ProcessPool() def _h(a, b, c): print('a: {0} b: {1}. c: {2}'.format(a, b, c)) k = self.f(a, b, c) return k/2 return [pool.amap(_h, (1,4), (2,5), (3,6))] Even when I called function once explicitly it got executed twice. Output: a: 1 b: 2. c: 3 a: 4 b: 5. c: 6 Hope this helps.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80645689
has comment: http://stackoverflow.com/comment/80633443
has comment: http://stackoverflow.com/comment/80647300
type: Answer
answers question: http://stackoverflow.com/q/46791359

http://stackoverflow.com/a/46843032
answers question: http://stackoverflow.com/q/46836227
downvote count: 0
upvote count: 2
has body: Your immediate error has to do with the fact that the Euler algorithm you are using for integration becomes unstable at the step size you are using. The ultimate problem is actually using the Euler algorithm. The code below uses scipy.integrate.odeint to handle the integration and does a better job due to being able to do variable step sizes. Some of the integration is still not perfect, but at least we get some results. import numpy import scipy.integrate import matplotlib.pyplot as plt def derivatives(states, t, r): x, y = states return [r*x - y + x*y**2, x + r*y + y**3] def trajectories(r): initial_conditions = [0.1, 0.1] times = numpy.linspace(0, 100, 1000) result = scipy.integrate.odeint(derivatives, initial_conditions, times, args=(r,)) xresult, yresult = result.T plt.plot(xresult, yresult) plt.axis('image') plt.axis([-3, 3, -3, 3]) plt.title('r = ' + str(r)) fig = plt.figure(figsize=(18,6)) rs = [-1, -0.1, 0, .1, 1] for i, r in enumerate(rs, 1): # Avoid for i in range(len(rs)) fig.add_subplot(1, len(rs), i) trajectories(r) plt.show() Result:
type: Answer
score: 2

http://stackoverflow.com/comment/80477112
comment on: http://stackoverflow.com/q/46765859
score: 0
type: Comment
type: QuestionComment
has text: ok, thank you. let me rephrase that.

http://stackoverflow.com/comment/80669964
comment on: http://stackoverflow.com/a/46860942
type: Comment
score: 0
type: AnswerComment
has text: In my knowledge, `selenium` is the only popular option as of now, `requests`, `urllib`, etc are network libraries mainly used to get, send REST API end points and hence they are not developed to render dynamic javascript objects.

http://stackoverflow.com/comment/80663291
comment on: http://stackoverflow.com/q/46857779
has text: thanks, how can I change it too integers?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46810479
has comment: http://stackoverflow.com/comment/80568647
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80568932
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80568563
has answer: http://stackoverflow.com/a/46811195
linked to: http://stackoverflow.com/q/26944274
upvote count: 0
has body: When I run my below query and there is no data in the values such as ["VT","NCR","N","DT","RD"], the query fails. With the error message of ValueError: dict contains fields not in fieldnames: ‘VT’ Is there a way to say if there is no data in any of the values still carry on running the query to grab data for the values that have data in python? For example: the ‘TRY’, ‘CATCH’, or ’PASS’ method? I have been struggling on this for days, could someone show me how to do this? My Code: from datetime import datetime from elasticsearch import Elasticsearch import csv es = Elasticsearch(["9200"]) res = es.search(index="search", body= { "_source": ["VT","NCR","N","DT","RD"], "query": { "bool": { "must": [{"range": {"VT": { "gte": "now/d", "lte": "now+1d/d"}}}, {"wildcard": {"user": "mike*"}}]}}},size=10) csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv' header_names = { 'VT': 'Date', 'NCR': 'ExTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'} with open(csv_file, 'w', newline='') as f: header_present = False for doc in res['hits']['hits']: my_dict = doc['_source'] if not header_present: w = csv.DictWriter(f, my_dict.keys()) w.writerow(header_names,) header_present = True w.writerow(my_dict)
has comment: http://stackoverflow.com/comment/80568763
has comment: http://stackoverflow.com/comment/80568599
type: Question
has comment: http://stackoverflow.com/comment/80568722
has comment: http://stackoverflow.com/comment/80568808
has comment: http://stackoverflow.com/comment/80569135
score: -2
has comment: http://stackoverflow.com/comment/80569040
has comment: http://stackoverflow.com/comment/80568192
has title: Code fails to run when there is no data
has comment: http://stackoverflow.com/comment/80568833
downvote count: 2
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80568631
has comment: http://stackoverflow.com/comment/80568170
tagged with: elasticsearch
answer count: 1

http://stackoverflow.com/q/46820109
has answer: http://stackoverflow.com/a/50466895
tagged with: python
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: win32com
score: 1
has answer: http://stackoverflow.com/a/46820149
answer count: 2
downvote count: 0
has title: Import error with win32com.gen_py
has body: I'm developing a Python application that can interface with Outlook and send emails on Outlook's behalf. Because of this, I need the use of the win32com library, in order to use win32com.client. In addition to this, the same Python script will also have to access a MySQL database using the Oracle mysql-connector. Because of this, Python34 must be used as this is the only version I managed to get working with the sql-connector. Now here comes the crux of the issue. I have installed win32com (as it is not pre-installed with Python34) and it installed with no errors, and I can import win32com fine within python. However, when importing win32com.client, it gives the below error message: &gt;&gt;&gt; import win32com.client Traceback (most recent call last): File "C:\Python34\lib\site-packages\win32com\client\gencache.py", line 60, in __init__ _LoadDicts() File "C:\Python34\lib\site-packages\win32com\client\gencache.py", line 110, in _LoadDicts f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb") FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python34\\lib\\site-packages\\win32com\\gen_py\\dicts.dat' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\win32com\client\gencache.py", line 143, in GetGeneratePath os.stat(fname) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Python34\\lib\\site-packages\\win32com\\gen_py\\__init__.py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python34\lib\site-packages\win32com\client\__init__.py", line 11, in &lt;module&gt; from . import gencache File "C:\Python34\lib\site-packages\win32com\client\gencache.py", line 666, in &lt;module&gt; __init__() File "C:\Python34\lib\site-packages\win32com\client\gencache.py", line 62, in __init__ Rebuild() File "C:\Python34\lib\site-packages\win…
favorite count: 0

hiveql
tag name: hiveql
tags question: http://stackoverflow.com/q/46818020
type: Tag

http://stackoverflow.com/comment/80769324
comment on: http://stackoverflow.com/a/46902553
score: 0
type: AnswerComment
has text: According to [this post](https://stackoverflow.com/questions/26140502/python-invalid-format-string), your option `%s` doesn't exist. I don't understand why it works for me, which prints the Unix time stamp. That's a good question I should ask. Anyway, check available options [here](https://docs.python.org/2/library/time.html#time.strftime)
type: Comment

http://stackoverflow.com/q/46789812
has comment: http://stackoverflow.com/comment/80528416
tagged with: numpy
has body: I am trying to access a matrix and print/modify only a few columns of it. Please think of it as writing down a 3x5 matrix A on paper, and copying down A without the 2nd column to get a 3x4 matrix B. To reiterate, I want to read a matrix from file such as this: [[1 2 3 4 5] [6 7 8 9 10] [11 12 13 14 15]] And print into a text file, like this: 1 3 4 5 6 8 9 10 11 13 14 15 I have used numpy.loadtxt to load a matrix A. Then, I am able to save to file just the first n columns by using the following: numpy.savetxt(fil_buffer, A[0:-1,0:n], format, delimiter, newline) as described on this link. Unable to do the same if I want to print, say, only the p-th column appended and m-th to n-th columns. Question: Is there a general method to carry out such procedures in python?
has comment: http://stackoverflow.com/comment/80526041
tagged with: matrix
has title: Printing/Accessing specific columns of a matrix, as a matrix in python
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
type: Question

http://stackoverflow.com/q/46799234
tagged with: python
has answer: http://stackoverflow.com/a/46799496
favorite count: 0
has comment: http://stackoverflow.com/comment/80545548
linked to: http://stackoverflow.com/q/2632520
type: UnansweredQuestion
tagged with: python-requests
score: 7
has title: Fastest way to loop over Pandas DataFrame for API calls
has comment: http://stackoverflow.com/comment/80545545
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/80545538
downvote count: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/80545656
has body: My objective is to make a call to an API for each row in a Pandas DataFrame, which contains a List of strings in the response JSON, and creating a new DataFrame with one row per response. My code basically looks like this: i = 0 new_df = pandas.DataFrame(columns = ['a','b','c','d']) for index,row in df.iterrows(): url = 'http://myAPI/' d = '{"SomeJSONData:"' + row['data'] + '}' j = json.loads(d) response = requests.post(url,json = j) data = response.json() for new_data in data['c']: new_df.loc[i] = [row['a'],row['b'],row['c'],new_data] i += 1 This works fine, but I'm making about 5500 API calls and writing about 6500 rows to the new DataFrame so it takes a while, maybe 10 minutes. I was wondering if anyone knew of a way to speed this up? I'm not too familiar with running parallel for loops in Python, could this be done while maintaining thread safety?

http://stackoverflow.com/q/46831644
type: Question
has title: django haystack elasticsearch wont give correct result
has body: I have a problem with django-haystack elasticsearch. I have a search for question where one field is study_level which is an int of 1 to 13. When I try to make a search to include question within a range like 10-12 it also gives questions with other study_level. It seems like study_level don't matter in the search. I have this index class QuestionIndex(indexes.SearchIndex, indexes.Indexable): """ A Haystack search index for Questions. """ text = indexes.EdgeNgramField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') user_id = indexes.IntegerField(model_attr='user_id') question = indexes.EdgeNgramField(model_attr='question', boost=1.15) study_level = indexes.IntegerField(model_attr='study_level') is_answered = indexes.IntegerField(model_attr='is_answered') is_archived = indexes.BooleanField(model_attr='is_archived') created_at = indexes.DateTimeField(model_attr='created_at') tags = indexes.MultiValueField() schools = indexes.MultiValueField() answers = indexes.IntegerField(indexed=False) has_answer = indexes.IntegerField(indexed=False) content = indexes.CharField(indexed=False) content_short = indexes.CharField(indexed=True) def get_model(self): return Question def prepare_study_level(self, obj): study_level = obj.study_level There is more def prepare_x but study_level is where my problem is. Then it is used in this code class QuestionSearch(object): # Plain old Python object for question search. MAX_RESULT_LENGTH = 12 def __init__(self, user, query='', limit=MAX_RESULT_LENGTH, subjects=[], study_level_min=None, study_level_max=None): self.user = user self.query = query self.limit = limit self.subjects = subjects self.study_level_min = study_level_min self.study_level_max = study_level_max # Swaps the min and max values if they are in the wrong order. if study_level_min and study_level_max and study_level_min &gt; study_level_max: self.study_level_min = study_level_max self.study_level_max = study_level_min self.schools = None # Signal val…
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/46850105
tagged with: django-haystack
tagged with: elasticsearch
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/80634406
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46843224
has text: It's a weird problem. @AndyHayden. The print c_df.dtypes works though it gives weird results

http://stackoverflow.com/comment/80638094
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46844090
has text: You might be interested in [subprocess](https://docs.python.org/3/library/subprocess.html) to run your script.
type: Comment

http://stackoverflow.com/q/46791309
score: 0
has comment: http://stackoverflow.com/comment/80529140
type: UnansweredQuestion
tagged with: python
has body: I'm deploying a flask server with gulp, and after the gulp command is launched, everything goes fine until the following line: import flask as I get the error ImportError: No module named flask . Adding the lines before the import command import sys print(sys.executable) I get printed /usr/bin/python which, launched on console, corresponds to a python 2.7.12 interpreter, and the command 'import flask' within the console doesn't give any error!! I can find many python interpreters (2, 3 and virtenvs on my machine) but it seems each of them has flask installed.
has comment: http://stackoverflow.com/comment/80530672
answer count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/80534649
type: Question
has title: pip and multiple python version issues in ubuntu 16.04

http://stackoverflow.com/q/46791281
type: Question
has body: Hello I want to merge two dataframes which I load in in Excel. I convert the column which should be merged to "str". Suprsingly the code merges the first row but then returns NaN values.... The code I use is: ListA=pd.read_excel(inpath,sheetname="Tabelle2") ListA["Stücklistenkomponente"]=ListA["Material"].astype(np.str) ListB=pd.read_excel(inpath,sheetname="Tabelle1") ListB["Stücklistenkomponente"]=ListB["Material"].astype(np.str) print(ListA.dtypes) print(ListB.dtypes) Material object Material object The shape of the two dataframes is: ListA Material R 22B 2.0 7.72 11.0 Lo X 127 1.5x4.64x4[G16.05.01] CL L 431 2x6,96x5.5 Y 9999 L 431 2x5,96x5.5 p F 631 2x6,96x5.5 a N 431 2x6,96x5.5 v J 431 2x6,96x5.5 O 431 2x6,96x5.5 VM 431 2x6,96x5.5 L ListB Material InnerDiameter OuterDiameter Length R 22B 2.0 7.72 11.0 Lo 2 6 8 X 127 1.5x4.64x4[G16.05.01] CL 2 7 12 L 431 2x6,96x5.5 Y 5 8 13 9999 0 0 0 L 431 2x5,96x5.5 p 6 9 15 F 631 2x6,96x5.5 a 8 5 26 N 431 2x6,96x5.5 v 9 1 3 J 431 2x6,96x5.5 12 6 89 O 431 2x6,96x5.5 5 4 12 VM 431 2x6,96x5.5 L 4 12 7 It returns: Material InnerDiameter OuterDiameter Lenth R 22B 2.0 7.72 11.0 Lo 2 6 8 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 So what am I doing wrong? I think the solution is to convert both columns to dtype string but this is not working.... Appreciate any help!
accepted answer: http://stackoverflow.com/a/46791336
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
tagged with: merge
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46791336
has title: Merge returns NaN except for first row
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/80498669
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46776501
has text: Can you provide a bit more description? Error message?
score: 0

http://stackoverflow.com/comment/135709670
has text: This is exactly what I was searching for when I needed to filter the results of a 12-element input, `set(permutations())` degrades heavily on this, while `distinct_permutations` returns instantly.
score: 0
comment on: http://stackoverflow.com/a/72969842
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46812081
has comment: http://stackoverflow.com/comment/80571509
has answer: http://stackoverflow.com/a/46812612
has comment: http://stackoverflow.com/comment/80571873
type: Question
tagged with: arrays
score: 0
tagged with: pandas
has title: Efficient way to store arrays and check if they exists in Python
answer count: 1
has body: I'm trying to make a vision based reinforcement learning bot for tic-tac-toe and stuck with how could I save the data and retrieve it fast. So saving data as lists for example start point is [0, 0, 0, 0, 0, 0, 0, 0, 0], and starting policy for that [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]. QUESTION IS: In what format should I save the current state and policy so I can access it fast for checking if the state already exists and for updating the policies? I was thinking of pandas and pickle, but found it a bit hard to implement with lists.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10465390
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/80571462

http://stackoverflow.com/q/46848912
tagged with: django-admin
downvote count: 0
has comment: http://stackoverflow.com/comment/80645200
has title: Django on Production doesn't display all fields of my Models in Django Admin
tagged with: postgresql
has body: I'm working on a Django 1.10 &amp; Python 3.6 project, I have deployed it on compute engine successfully with gunicorn.My project is working fine but I have one issue there, I have two models as "Articles" &amp; "TaggedArticle", I have specified all fields from TaggedArticle in admin.py but it doesn't display in Django admin, rather it's displaying all fields in Django admin on my local system. After deployment now I'm using Postgresql instead of SQLite. Update: Fields are not displaying only in detail view of TaggedArticle in Django Admin Here are my models: Article Model: class Article(models.Model): link = models.URLField(max_length=255) category = models.CharField(max_length=255, choices=Categories) TaggedArticle Model: class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) Here's my admin.py for TaggedArticle: User = get_user_model() admin.site.unregister(User) class InlineTaggedArticle(admin.TabularInline): model = TaggedArticle class CustomAdmin(UserAdmin): date_hierarchy = 'date_joined' inlines = [InlineTaggedArticle, ] list_display = list(UserAdmin.list_display) + ['totol_tagged_article'] def totol_tagged_article(self, obj): return obj.tagging.all().count() admin.site.register(User, CustomAdmin) class TaggedArticleAdmin(admin.ModelAdmin): date_hierarchy = 'created_at' fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email'] list_display = ['link', 'user', 'email'] list_filter = ['user', 'email'] model = Tagged admin.site.register(Tagged, TaggedArticleAdmin) Only category_fit &amp; article fields are displaying in Djan…
answer count: 1
has comment: http://stackoverflow.com/comment/80647298
tagged with: python
has comment: http://stackoverflow.com/comment/80645853
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85308569
has comment: http://stackoverflow.com/comment/85341730
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/85424998
linked to: http://stackoverflow.com/q/46824027
has comment: http://stackoverflow.com/comment/80645777
score: 1
tagged with: django-models
type: Question
has comment: http://stackoverflow.com/comment/80645704
has answer: http://stackoverflow.com/a/46849108
has comment: http://stackoverflow.com/comment/80645249

http://stackoverflow.com/comment/80631552
has text: You're wasted in coal mining.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46840246

http://stackoverflow.com/comment/138884879
comment on: http://stackoverflow.com/a/78771237
type: Comment
has text: you should focus on the solution, without telling what was not working for you.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80722250
type: QuestionComment
has text: Yes, two snippets in the answer are the complete code that reproduces the problem for me. I'm running Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]) on Windows 7.
comment on: http://stackoverflow.com/q/46843749
score: 0
type: Comment

http://stackoverflow.com/comment/80507825
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46766406
has text: Thanks for pointing me to the right documentation - I'll try this out!

http://stackoverflow.com/comment/80691957
comment on: http://stackoverflow.com/a/46872289
has text: 32 bit means [that there is just an extra byte used as padding in BMP](https://stackoverflow.com/questions/7369649/how-to-convert-32-bit-bmp-to-contain-alpha-channel) (8 bit pr. channel). It's not related to the bitness of your python installation. My guess is that the BMP loader in pygame doesn't support 32-bit BMPs (.. which are kind of useless, as there are many formats that do everything BMP does, but does it better)
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80617636
has text: `Queue`s maybe thread-safe. but the results can still be "jumbled" in the sense of being out-of-order because of different subprocesses finishing at different times and basically adding their result to it in a random order.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46834777

http://stackoverflow.com/q/46781195
score: 13
has body: Given a dataframe: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; lol = [['a', 1, 1], ['b', 1, 2], ['c', 1, 4], ['c', 2, 9], ['b', 2, 10], ['x', 2, 5], ['d', 2, 3], ['e', 3, 5], ['d', 2, 10], ['a', 3, 5]] &gt;&gt;&gt; df = pd.DataFrame(lol) &gt;&gt;&gt; df.rename(columns={0:'value', 1:'key', 2:'something'}) value key something 0 a 1 1 1 b 1 2 2 c 1 4 3 c 2 9 4 b 2 10 5 x 2 5 6 d 2 3 7 e 3 5 8 d 2 10 9 a 3 5 The goal is to keep the last N rows for the unique values of the key column. If N=1, I could simply use the .drop_duplicates() function as such: &gt;&gt;&gt; df.drop_duplicates(subset='key', keep='last') value key something 2 c 1 4 8 d 2 10 9 a 3 5 How do I keep the last 3 rows for each unique values of key? I could try this for N=3: &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; unique_keys = {k:[] for k in df['key']} &gt;&gt;&gt; for idx, row in df.iterrows(): ... k = row['key'] ... unique_keys[k].append(list(row)) ... &gt;&gt;&gt; &gt;&gt;&gt; df = pd.DataFrame(list(chain(*[v[-3:] for k,v in unique_keys.items()]))) &gt;&gt;&gt; df.rename(columns={0:'value', 1:'key', 2:'something'}) value key something 0 a 1 1 1 b 1 2 2 c 1 4 3 x 2 5 4 d 2 3 5 d 2 10 6 e 3 5 7 a 3 5 But there must be a better way...
accepted answer: http://stackoverflow.com/a/46781256
type: AnsweredQuestion
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/46781436
has answer: http://stackoverflow.com/a/46781256
type: Question
answer count: 2
downvote count: 0
has title: Keeping the last N duplicates in pandas
upvote count: 13
tagged with: pandas
tagged with: drop-duplicates
has answer: http://stackoverflow.com/a/46781436
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/80458640
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46754943
type: Comment
has text: @JLev bytes must be sent over the connection. Python 3 strings are Unicode so they must be encoded.

http://stackoverflow.com/comment/80700011
type: AnswerComment
comment on: http://stackoverflow.com/a/46873873
type: Comment
has text: I suggest that you start with `display = yield protocol.write_registers(5, dd, unit=1)`, we if you then get the correct characters and length, then worry about the byte order if, as I suspect they will be, they are pair-swapped.
score: 0

http://stackoverflow.com/comment/80711402
score: 0
has text: This worked great @Sam17, exexution time is 0.27 secs. Can you explain how this line works. I am new to python
type: Comment
comment on: http://stackoverflow.com/a/46882029
type: AnswerComment

http://stackoverflow.com/a/46869834
has body: When implementing a QThread the task to be performed should be done in the run () method, if you want to update the GUI with data provided by the thread should not be done directly but through signals since the GUI should only be updated in the main thread called by this the GUI thread. class DownloadThread(QThread): dataChanged = pyqtSignal(int, str, str, str) Started, Paused, Resume, Stopped = range(4) downloadError = pyqtSignal() downloadFinished = pyqtSignal() def __init__(self, parent=None): QThread.__init__(self, parent) self.state = DownloadThread.Stopped self.params = {"url": "", "save_location": ""} def setParams(self, params): self.params = params def setState(self, state): self.state = state def run(self): obj = SmartDL(self.params["url"], progress_bar=False) try: obj.start(blocking=False) while True: self.dataChanged.emit(obj.get_progress() * 100, str(obj.get_dl_size(human=True)), str(obj.get_speed(human=True)), str(obj.get_eta(human=True))) time.sleep(0.2) if self.state == DownloadThread.Paused: obj.pause() if self.state == DownloadThread.Resume: obj.unpause() self.state = DownloadThread.Started if obj.isFinished(): break if self.state == DownloadThread.Stopped: obj.stop() self.progressBar.setValue(0) break if obj.isSuccessful(): # os.rename(obj.get_dest(), save_location) shutil.move(obj.get_dest(), self.params["save_location"]) if self.state == DownloadThread.Started: self.downloadFinished.emit() except: self.downloadError.emit() You should avoid using global variables in addition that you can reduce several variables that are all updated at once by only one variable so I had to modify the GUI code. class MainApp(QMainWindow, FORM_CLASS): def __init__(self, parent=None): # ... self.Handle_Buttons() self.download = DownloadThread(self) self.download.dataChanged.connect(self.onDataChanged) self.download.downloadError.connect(self.errorDownload) self.download.downloadFinished.connect(self.successfulDownload) def closeEvent(self, evnt): # ... def Handle_Ui…
accepted answer of: http://stackoverflow.com/q/46869472
answers question: http://stackoverflow.com/q/46869472
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/80739562
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46895899
has text: `reduce` is not in the default namespace in Python 3.
score: 0

http://stackoverflow.com/a/46813879
has body: You access the values of dictionarys withdictname[key], so in your code it would be if podane_znaczenie == slownik[key]: print ('Yes!')
score: 0
answers question: http://stackoverflow.com/q/46813733
type: Answer

http://stackoverflow.com/comment/80677252
comment on: http://stackoverflow.com/q/46864449
score: 0
type: Comment
type: QuestionComment
has text: I observed that y takes different values @Reti43 and I didnt come with an explanation yet why is that..

http://stackoverflow.com/a/46779867
has body: Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)
upvote count: 1
answers question: http://stackoverflow.com/q/46779833
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/46814272
tagged with: python
has body: I am writing a small chat app with python using bash commands. I'm using nc to accomplish this but I want to be able to append a username before the user's message. How do I go about doing this without breaking the connection? The command I'm using to connect is just nc -l -p 1234 -q 0 and the desired outcome is that when the person sends something it would look like: &lt;User1&gt; Hello Thank you!
has title: How to print text while netcat is listening at a port?
has comment: http://stackoverflow.com/comment/80586611
has comment: http://stackoverflow.com/comment/80575894
type: Question
answer count: 2
tagged with: network-programming
has answer: http://stackoverflow.com/a/46814443
has answer: http://stackoverflow.com/a/46846940
score: 0
tagged with: bash
tagged with: scripting
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/80686503
comment on: http://stackoverflow.com/a/46869566
type: Comment
has text: Great! I don't think so. If something happen just post question here.
score: 0
type: AnswerComment

python-3.x
tags question: http://stackoverflow.com/q/46758210
tags question: http://stackoverflow.com/q/46900044
tags question: http://stackoverflow.com/q/46822985
tags question: http://stackoverflow.com/q/46807337
tags question: http://stackoverflow.com/q/46756606
tags question: http://stackoverflow.com/q/46782989
tags question: http://stackoverflow.com/q/46886903
tags question: http://stackoverflow.com/q/46767724
tags question: http://stackoverflow.com/q/46867308
tags question: http://stackoverflow.com/q/46798399
tags question: http://stackoverflow.com/q/46808236
tags question: http://stackoverflow.com/q/46866387
tags question: http://stackoverflow.com/q/46839127
tags question: http://stackoverflow.com/q/46785504
tags question: http://stackoverflow.com/q/46752942
tags question: http://stackoverflow.com/q/46851216
tags question: http://stackoverflow.com/q/46890203
tags question: http://stackoverflow.com/q/46819942
tags question: http://stackoverflow.com/q/46826822
tags question: http://stackoverflow.com/q/46758447
tags question: http://stackoverflow.com/q/46762377
tags question: http://stackoverflow.com/q/46841466
tags question: http://stackoverflow.com/q/46832501
tags question: http://stackoverflow.com/q/46770709
tags question: http://stackoverflow.com/q/46819300
tags question: http://stackoverflow.com/q/46777114
tags question: http://stackoverflow.com/q/46751271
tags question: http://stackoverflow.com/q/46806265
tags question: http://stackoverflow.com/q/46876043
tags question: http://stackoverflow.com/q/46900020
tags question: http://stackoverflow.com/q/46870692
tags question: http://stackoverflow.com/q/46822070
tags question: http://stackoverflow.com/q/46824459
tags question: http://stackoverflow.com/q/46814202
tags question: http://stackoverflow.com/q/46846149
tags question: http://stackoverflow.com/q/46835610
tags question: http://stackoverflow.com/q/46871570
tags question: http://stackoverflow.com/q/46891886
tags question: http://stackoverflow.com/q/46782841
tags question: http://stackoverflow.com/q/46888006
tags question: http://stackoverflow.com/q/46880264
tags question: http://stackoverflow.com/q/46832561
tags question: http://stackoverflow.com/q/46863560
tags question: http://stackoverflow.com/q/46780008
tags question: http://stackoverflow.com/q/46802586
tags question: http://stackoverflow.com/q/46861242
tags question: http://stackoverflow.com/q/46852090
tags question: http://stackoverflow.com/q/46897717
tags question: http://stackoverflow.com/q/46834779
tags question: http://stackoverflow.com/q/46761697
tags question: http://stackoverflow.com/q/46799741
tags question: http://stackoverflow.com/q/46841569
tags question: http://stackoverflow.com/q/46855184
tags question: http://stackoverflow.com/q/46791869
tags question: http://stackoverflow.com/q/46856379
tags question: http://stackoverflow.com/q/46796451
tags question: http://stackoverflow.com/q/46890703
tags question: http://stackoverflow.com/q/46797973
tags question: http://stackoverflow.com/q/46781032
tags question: http://stackoverflow.com/q/46862568
tags question: http://stackoverflow.com/q/46811416
tags question: http://stackoverflow.com/q/46855519
tags question: http://stackoverflow.com/q/46870452
tags question: http://stackoverflow.com/q/46902154
tags question: http://stackoverflow.com/q/46862074
tags question: http://stackoverflow.com/q/46772609
tags question: http://stackoverflow.com/q/46824205
tags question: http://stackoverflow.com/q/46829758
tags question: http://stackoverflow.com/q/46902398
tags question: http://stackoverflow.com/q/46855947
tags question: http://stackoverflow.com/q/46895030
tags question: http://stackoverflow.com/q/46863394
tags question: http://stackoverflow.com/q/46801543
tags question: http://stackoverflow.com/q/46844803
tags question: http://stackoverflow.com/q/46822402
tags question: http://stackoverflow.com/q/46752283
tags question: http://stackoverflow.com/q/46807876
tags question: http://stackoverflow.com/q/46818581
tags question: http://stackoverflow.com/q/46770018
tags question: http://stackoverflow.com/q/46807798

http://stackoverflow.com/a/46810155
type: Answer
has comment: http://stackoverflow.com/comment/80567680
upvote count: 5
has comment: http://stackoverflow.com/comment/80568279
accepted answer of: http://stackoverflow.com/q/46810056
answers question: http://stackoverflow.com/q/46810056
score: 5
type: AcceptedAnswer
downvote count: 0
has body: You can do: definition = ['basename', 'dirname', 'supports_unicode_filenames'] condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] d = {'definition': definition, 'condition': condition } Note that you should avoid using the variable name dict, which is a builtin object. But to be honest, what you're trying to do is not good practice if you're doing this at scale. You should rethink the design of your object.
has comment: http://stackoverflow.com/comment/80567967

http://stackoverflow.com/q/46899718
downvote count: 0
score: 1
has title: Regex not working for the last few letters of String
has answer: http://stackoverflow.com/a/46899755
accepted answer: http://stackoverflow.com/a/46899755
type: Question
possible better answer: http://stackoverflow.com/a/46899850
has body: This is what my header looks like header = "GET method P2P-DI/1.0\n" +"Host: "+ host+ "\nOS: " + OS + "\nStatus: 404" I was successfully able to get method by doing this: method = re.search('GET (.*?) P2P-DI/1\.0.*',header).group(1) I'm trying to just retrieve the Status Code '404'. Which returns None has no group error status = re.search('GET .*Status: ([0-9][0-9][0-9]?)',header).group(1)
has answer: http://stackoverflow.com/a/46899850
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/comment/80513276
comment on: http://stackoverflow.com/a/46783482
type: Comment
score: 0
type: AnswerComment
has text: Why pivot_table? It aggregate values - not necessary here

http://stackoverflow.com/q/46868111
tagged with: crash
has comment: http://stackoverflow.com/comment/80683548
answer count: 1
favorite count: 0
has body: I know this might not be a python question but it is an emergency, I had at least 3,000 lines of code and right when I was saved my file my laptop crashed. And I worked on this file everyday, so I saved it everyday. When I turned my computer on and opened that file I was working in, it was completely blank and empty. There was no code, but the file size was the same. Please, I am in a desperate need to recover my file, is there any way I can get it back?
has title: Python file after sudden crash empty
tagged with: python
tagged with: python-idle
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/46868421
upvote count: 1
has comment: http://stackoverflow.com/comment/80683577
type: Question
score: -1
has comment: http://stackoverflow.com/comment/80683586

http://stackoverflow.com/comment/80564775
has text: Actually: 1/ the import should be outside the function, 2/ `x` is an int so `int(x-1)` and `int(x+1)` is redundant, and 3/ `p == x-1 or p == x+1` can be simplified to `abs(p-x) == 1`.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46808684
type: AnswerComment

http://stackoverflow.com/comment/80588080
type: QuestionComment
comment on: http://stackoverflow.com/q/46820189
type: Comment
has text: Is the graphic package installed? run pip install graphics in the shell
score: 0

http://stackoverflow.com/a/46869668
accepted answer of: http://stackoverflow.com/q/46869642
answers question: http://stackoverflow.com/q/46869642
has comment: http://stackoverflow.com/comment/80686578
score: 0
type: AcceptedAnswer
type: Answer
has body: Two things. In the vowel function, there's no need for a loop. You're sending a single character so you simply need to check it: def vowel(c): if c.lower() in 'aeiou': return True else: return False Or: def vowel(c): return True if c.lower() in 'aeiou' else False Then, in repeated, don't use c is not vowel(c). That compares if the identity of c, the character, is or isn't equal to True/False. Just use the value returned from vowel directly and conditionally add to result: def repeated(s, k): result = '' for c in s: if not vowel(c): result += (c * k) else: result += c return result

http://stackoverflow.com/q/46754615
type: Question
has comment: http://stackoverflow.com/comment/80454874
has answer: http://stackoverflow.com/a/46754703
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46754680
has answer: http://stackoverflow.com/a/46754752
has title: Python prints { } instead of an empty space - tkinter
tagged with: label
accepted answer: http://stackoverflow.com/a/46754752
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/80455307
tagged with: python-3.x
tagged with: tkinter
score: 0
has answer: http://stackoverflow.com/a/46754680
has body: In this simple example, I would like the label to be displayed as "1 3": import tkinter window = tkinter.Tk() A = [1," ", 3] label = tkinter.Label(window, text = A[0:]) label.pack() window.mainloop() However, python displays "1 { } 3" instead. Where is the problem?

http://stackoverflow.com/a/46840892
answers question: http://stackoverflow.com/q/46840848
score: 6
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/46840848
has body: You can do this with advanced indexing and numpy broadcasting: m = np.argmax(a, axis=1) a[np.arange(a.shape[0])[:,None], m, np.arange(a.shape[2])] #array([[7, 6], # [5, 4]]) m = np.argmax(a, axis=1) Create arrays of 1st, 2nd and 3rd dimensions indices: ind1, ind2, ind3 = np.arange(a.shape[0])[:,None], m, np.arange(a.shape[2]) ​ Because of the dimension mismatch, the three arrays will broadcast, which result in each to be as follows: for x in np.broadcast_arrays(ind1, ind2, ind3): print(x, '\n') #[[0 0] # [1 1]] #[[0 1] # [1 0]] #[[0 1] # [0 1]] And since all indices are integer arrays, it triggers advanced indexing, so elements with indices (0, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1) are picked up, i.e. one element from each array combined as the index.

http://stackoverflow.com/comment/106263427
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49328226
type: AnswerComment
has text: Does this answer help [SO:a/47859122](https://stackoverflow.com/a/47859122)?

http://stackoverflow.com/q/46786173
tagged with: scrapy
has body: This is a piece of code and the entire concatenated text field is not seen in the csv file instead the first letter is seen. Also the name field is returned perfectly. Q: Does this have something to do with settings.py file where we can mention/specify settings related to particular spider? Because if a particular text element of a particular class is extracted then the text field is filled in the csv file. Using Scrapy version: 1.4.0 on a Macbook Pro def parse(self, response): #text text = u''.join(response.xpath('//div[contains(@id, "tab-")]//p//text()').extract()) #name names = response.css('div.inner.html-content h1::text').extract()
has title: Concatenated all the tags using u' '.join in scrapy but unable to export that particular columns to a csv file
type: Question
tagged with: export-to-csv
score: 0
has comment: http://stackoverflow.com/comment/80585831
has comment: http://stackoverflow.com/comment/80682101
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80634123
tagged with: web-scraping

http://stackoverflow.com/comment/80670866
score: 0
comment on: http://stackoverflow.com/q/46859615
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57627158
upvote count: 7
type: Answer
downvote count: 0
has body: Fairly new to Django/Python, but this is how I solved it. Save large file to AWS, open it with Pillow, then resize and save in memory. Then push to AWS using default_storage just as the django-storages help docs suggest. Note that img.thumbnail will retain aspect with just the longer edge of the image set to 1000 pixels. image is the Django model ImageField. from django.core.files.storage import default_storage from io import BytesIO .. def save(self, *args, **kwargs): #run save of parent class above to save original image to disk super().save(*args, **kwargs) memfile = BytesIO() img = Image.open(self.image) if img.height &gt; 1000 or img.width &gt; 1000: output_size = (1000, 1000) img.thumbnail(output_size, Image.ANTIALIAS) img.save(memfile, 'JPEG', quality=95) default_storage.save(self.image.name, memfile) memfile.close() img.close()
accepted answer of: http://stackoverflow.com/q/46890838
answers question: http://stackoverflow.com/q/46890838
score: 7
type: AcceptedAnswer

http://stackoverflow.com/comment/80533241
type: QuestionComment
comment on: http://stackoverflow.com/q/46792270
score: 0
type: Comment
has text: If I just use the path "/" the file is saved to C:\. However i want to save the file to my static folder that is located in the same folder like my python app.

http://stackoverflow.com/a/46901612
has body: If you have multiple rules, this becomes cumbersome. As long as your replacements are done on single characters, you can make this easy with str.translate. That, however, doesn't solve the problem of chained replacements, so you'll have to make use of a while loop that runs until there are no more changes. def applyRules(string, rules): mapping = str.maketrans(dict(x.split(':') for x in rules)) while True: new = string.translate(mapping) if string == new: break string = new return new In [1308]: applyRules('bbbbb', ['b:c', 'c:d']) Out[1308]: 'ddddd' Single Character Replacement For replacement involving a single character, the solution simplifies. You could use a dictionary with get: def applyRules(char, rules): mapping = dict(x.split(':') for x in rules) while True: new = mapping.get(char, char) if char == new: break char = new return new This should be much simpler.
answers question: http://stackoverflow.com/q/46901524
has comment: http://stackoverflow.com/comment/80752267
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46901524
has comment: http://stackoverflow.com/comment/80752510
has comment: http://stackoverflow.com/comment/80752570
has comment: http://stackoverflow.com/comment/80752471
type: Answer
has comment: http://stackoverflow.com/comment/80753615
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80752729

http://stackoverflow.com/comment/80686203
comment on: http://stackoverflow.com/a/46869467
type: AnswerComment
type: Comment
score: 1
has text: Your welcome, please don't forget to follow the questing asking guides next time, for the benefit of the website and therefore yourself.

http://stackoverflow.com/comment/117980278
type: Comment
has text: This only covers pan events, not zoom or reset.
comment on: http://stackoverflow.com/a/59004889
type: AnswerComment
score: 0

export
tags question: http://stackoverflow.com/q/46870844
type: Tag
tag name: export
tags question: http://stackoverflow.com/q/46864457
tags question: http://stackoverflow.com/q/46840135
tags question: http://stackoverflow.com/q/46859615

http://stackoverflow.com/a/46833805
type: AcceptedAnswer
downvote count: 0
has body: Python is an off-side rule language: Python Reference Manual (link) Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements. In contrast to others such as curly-bracket languages, indentation is (generally) not stylistic, but required in order to group statements. Therefore, your code should look like this: def make_doctor(name): return "Doctor" + name full_name = input() print(make_doctor(full_name))
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/46833644
answers question: http://stackoverflow.com/q/46833644
upvote count: 1

http://stackoverflow.com/a/46829220
downvote count: 0
has comment: http://stackoverflow.com/comment/80606117
score: 5
type: Answer
has body: You could convert your list to a dict with enumerate(sequence, start=1): dict(enumerate(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], 1)) # {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'} Then, your query is a easy as dict.get(): wdays = {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'} def word(num): return wdays.get(num, 'Error') Here's an example: &gt;&gt;&gt; word(3) 'Tuesday' &gt;&gt;&gt; word(10) 'Error' &gt;&gt;&gt; word('garbage') 'Error' Depending on what you want to do with the string, it might not be a good idea to return 'Error' instead of simply throwing an Error. Otherwise, you'll have to check if the string looks like a week-day or is equal to 'Error' every time you use this function.
answers question: http://stackoverflow.com/q/46829055
has comment: http://stackoverflow.com/comment/80606964
upvote count: 5
has comment: http://stackoverflow.com/comment/80605867

http://stackoverflow.com/q/46835757
has answer: http://stackoverflow.com/a/46835961
has comment: http://stackoverflow.com/comment/80620274
type: Question
has comment: http://stackoverflow.com/comment/80619180
has comment: http://stackoverflow.com/comment/80619260
has title: Python- Sorting a list of lists by multiple indices, where inner lists may include "None"
has comment: http://stackoverflow.com/comment/80619384
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80619107
tagged with: sorting
linked to: http://stackoverflow.com/q/12971631
has body: I am attempting to sort a list of lists by each index of the inner list. (All inner lists are the same length.) The goal is to sort the rows by the last column (the last index of the inner lists) first, then by the previous column/index and so on. Input: [ ['2016', 'E', None, '68', '94'], ['2016', 'A', None, '91', '25'], ['2016', 'C', None, '74', '25'], ['2017', 'C', None, '55', '20'], ['2015', 'D', None, '20', '14'], ['2016', 'B', None, '66', '66'], ['2017', 'E', None, '29', '41'], ['2017', 'F', None, '61', '22'], ['2015', 'A', None, '17', '96'] ] Output: [ ['2015', 'A', None, '17', '96'], ['2015', 'D', None, '20', '14'], ['2016', 'A', None, '91', '25'], ['2016', 'B', None, '66', '66'], ['2016', 'C', None, '74', '25'], ['2016', 'E', None, '68', '94'], ['2017', 'C', None, '55', '20'], ['2017', 'E', None, '29', '41'], ['2017', 'F', None, '61', '22'] ] I have the following piece of code that I'm trying to use for this: def sort_table(column_count, rows) for i in range(len(column_count) - 1, -1, -1): rows = sorted(rows, key=operator.itemgetter(i)) return rows However, it seems to be thrown by the fact that there are or can be None values in the list. I keep getting the error TypeError: '&lt;' not supported between instances of 'NoneType' and 'str'. Is there a correct way to handle this?
tagged with: python
has answer: http://stackoverflow.com/a/46835937
accepted answer: http://stackoverflow.com/a/46835937
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/46835961

http://stackoverflow.com/q/46834247
type: Question
has body: With the Sample, the target is: Compute the funtions in each value of 'A', in other words, compute something in all values of the variables in all B values in each A label.: import numpy as np import pandas as pd df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) def var1(x): return max(x)-min(x) def var2(x): return (max(x)-min(x))/max(x) def var3(x): return (max(x)-min(x))/ len(x) df = df.groupby(['A','B']).agg({'C': var1, 'D': [var2, var3]}) Target The Output would look like this: A var1 var2 var3 bar 0.000000 -0.000000 0.000000 foo 1,008986 -0.8572265 0.3015905 functions like: def var1(x): return max(x)-min(x) def var2(x): return (max(x)-min(x))/max(x) def var3(x): return (max(x)-min(x))/ len(x) def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1)
has title: summarizing multiindex pandas dataframe
score: 0
tagged with: pandas
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/46834346
accepted answer: http://stackoverflow.com/a/46834346

http://stackoverflow.com/comment/80663532
comment on: http://stackoverflow.com/a/46852262
type: AnswerComment
has text: Are you sure your program is in a state where it should be outputting messages? `tail`ing on a file descriptor won't give you any old messages, it will only print new ones. Consider either writing to a file via https://docs.python.org/2/library/stdtypes.html?highlight=write#file.write, or use shell redirection via `./foo.py >> bar.txt` and then run `tail -f bar.txt` from a terminal
type: Comment
score: 2

http://stackoverflow.com/q/46796846
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/70551115
has body: When i am using turtle module to draw a circle with this simple function: def draw_shape(self): canvas = Screen() t = Turtle() t.circle(self.r) canvas.exitonclick() For the first time when i call this function it opens a new window and draw a circle, i click on it to exit and when i try to again call this function from menu in console i got an error: Original exception was: Traceback (most recent call last): File "main.py", line 136, in &lt;module&gt; main() File "main.py", line 132, in main OPTIONS[user_input][1](shapes) File "main.py", line 48, in handle_sixth_menu_option t = Turtle() File "/usr/lib/python3.6/turtle.py", line 3816, in __init__ visible=visible) File "/usr/lib/python3.6/turtle.py", line 2557, in __init__ self._update() File "/usr/lib/python3.6/turtle.py", line 2660, in _update self._update_data() File "/usr/lib/python3.6/turtle.py", line 2646, in _update_data self.screen._incrementudc() File "/usr/lib/python3.6/turtle.py", line 1292, in _incrementudc raise Terminator turtle.Terminator
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/45534458
has title: Python turtle.Terminator error
downvote count: 0
tagged with: python-3.6
tagged with: python-turtle
has answer: http://stackoverflow.com/a/47725856
tagged with: python
linked to: http://stackoverflow.com/q/45534458
favorite count: 0
has comment: http://stackoverflow.com/comment/130305830
tagged with: turtle-graphics
type: UnansweredQuestion

http://stackoverflow.com/comment/80609522
has text: Your generator version will lose any entries in `accumulator` that aren't also in `keys`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46831040

http://stackoverflow.com/q/46863993
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/14921777
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80698104
has comment: http://stackoverflow.com/comment/80675685
has comment: http://stackoverflow.com/comment/80676270
tagged with: sqlalchemy
type: Question
has body: In the following sample, there is an sqlalchemy model module: meta = MetaData(naming_convention={ "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" }) class Base(object): "Modify base to add standard columns across tables" @declared_attr def __tablename__(cls): return cls.__name__ id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.utcnow()) class MixinLabel(object): label = Column(String, nullable=False) Base = declarative_base(metadata=meta, cls=Base) class Block(Base, MixinLabel): descendantId = Column(Integer, ForeignKey('BlockGroup.id')) groupId = Column(Integer, ForeignKey('BlockGroup.id')) position = Column(Integer) # one-to-one _descendant = relationship('BlockGroup', cascade='all, delete-orphan', single_parent=True, foreign_keys=[descendantId], backref=backref('_ascendant', uselist=False) ) class BlockGroup(Base): "Abstract class" type = Column(String) __mapper_args__ = { 'polymorphic_identity': 'blockgroup', 'polymorphic_on': type } # one-to-many children = relationship('Block', cascade='all, delete-orphan', backref=backref('group', uselist=False), foreign_keys=[Block.groupId], order_by='Block.position' ) configure_mappers() Notice the configure_mappers() call at the end. That one does not work. If I try to access the Block.group relation, I get an AttributeError exception raised: AttributeError: 'Block' object has no attribute 'group' According to this SO question, configure_mappers() should resolve this. Somehow, configure_mappers() doesn't do its job. Something goes wrong.
has comment: http://stackoverflow.com/comment/80675765
downvote count: 0
has title: SQLAlchemy backref not working despite configure_mappers
has comment: http://stackoverflow.com/comment/88000422
has comment: http://stackoverflow.com/comment/80677483
favorite count: 0
has comment: http://stackoverflow.com/comment/80675797
has comment: http://stackoverflow.com/comment/80675746

http://stackoverflow.com/comment/80578504
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46792743
has text: I edited my answer to better answer the question. I saved the HTML given as a file on my computer and opened it with scrapy shell. I was able to get the outputs desired.

http://stackoverflow.com/comment/80726939
comment on: http://stackoverflow.com/q/46889844
has text: This seem to be timing issue. You can try to implement [Implicit or Explicit wait](http://selenium-python.readthedocs.io/waits.html)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46894059
has answer: http://stackoverflow.com/a/46894143
linked to: http://stackoverflow.com/q/21226808
has body: my English is not very good,so if I couldn't explain the question clearly,please forgive me. I downloaded the Geany directly and used it without any setting(because there are always something wrong and I can't solve the problem. I input code in geany，then copy and paste the in the python. then……
duplicate of: http://stackoverflow.com/q/21226808
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/80735248
has answer: http://stackoverflow.com/a/46894121
type: Question
tagged with: syntax-error
answer count: 2
upvote count: 0
score: -2
has title: How to solve the error on this code?SyntaxError
favorite count: 0

http://stackoverflow.com/q/46808810
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: anaconda
has title: Issues with pip install after installing Tensorflow
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/46499808
has body: I have Anaconda 5.0, Windows 10. I have installed Tensorflow with pip install tensorflow in the Anaconda Prompt. Installation was successful. The test suggested on the website worked as expected. But now I cannot install any other package with pip install. For instance when I run: pip install memory-profiler I get: Exception: Traceback (most recent call last): File "C:\Python\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Python\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "C:\Python\Anaconda3\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "C:\Python\Anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Python\Anaconda3\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file require_hashes File "C:\Python\Anaconda3\lib\site-packages\pip\req\req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 568, in _get_pages page = self._get_page(location) File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 811, in get_page inst = cls(resp.content, resp.url, resp.headers) File "C:\Python\Anaconda3\lib\site-packages\pip\index.py", line 731, in __init__ namespaceHTMLElements=False, TypeError: parse() got an unexpected keyword argument 'transport_encoding' How can I remedy this? The prob…
score: 0
has answer: http://stackoverflow.com/a/46810508
answer count: 1
has comment: http://stackoverflow.com/comment/80565774

http://stackoverflow.com/q/46883799
has comment: http://stackoverflow.com/comment/80717472
linked to: http://stackoverflow.com/q/9957195
score: 0
tagged with: qtreewidget
has comment: http://stackoverflow.com/comment/80717401
tagged with: pyqt
has body: so I'm building program with 2 classes but when I call function from one class in another class it gives me this error: QPixmap: It is not safe to use pixmaps outside the GUI thread QPixmap: It is not safe to use pixmaps outside the GUI thread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread QObject::startTimer: QTimer can only be used with threads started with QThread I'm not using QTimer nor QPixmap, here is part of the code: class Connect(QMainWindow): def __init__(self): # ... def connect(self): ip = self.iip.text() po = self.ipo.text() start_new_thread(self.client, (ip, int(po))) def client(self, i, p): s = socket(AF_INET, SOCK_STREAM) s.connect((i, p)) data = s.recv(1024) Audo().addNewRoom(data) class Audo(QMainWindow): def __init__(self): # ... def addNewRoom(self, room_name): self.rooms[room_name.lower()] = QTreeWidgetItem(self.roomsw, [room_name])
has comment: http://stackoverflow.com/comment/80717753
tagged with: qpixmap
answer count: 0
has comment: http://stackoverflow.com/comment/80717292
tagged with: qtimer
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80717901
type: Question
has title: PyQt QTimer and QPixmap error without using them

http://stackoverflow.com/comment/80597017
type: Comment
has text: This is exactly what I want ! Thank you very much !
type: AnswerComment
comment on: http://stackoverflow.com/a/46815851
score: 0

http://stackoverflow.com/a/46751833
has comment: http://stackoverflow.com/comment/80449545
has comment: http://stackoverflow.com/comment/80449633
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80449520
has comment: http://stackoverflow.com/comment/80450104
has body: Sum didn't work because while returning the series since there are only numbers it converted to respective float dtype format. It will be object only if it is mixed datatype when applying standard functions. For example when you do df = pd.DataFrame({ 'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7], 'col_3': [14, 15, 16, 'b'] }) df.astype(str).sum(1) Output: 0 0414 1 1515 2 2616 3 37b dtype: object One alternative for doing sum is with cumsum so dtype will be preserved i.e s = df.astype(str).cumsum(1).iloc[:,-1] Output: 0 0414 1 1515 2 2616 3 3719 Name: col_3, dtype: object Hope it helps
score: 2
has comment: http://stackoverflow.com/comment/80450136
accepted answer of: http://stackoverflow.com/q/46751465
upvote count: 2
has comment: http://stackoverflow.com/comment/80449626
answers question: http://stackoverflow.com/q/46751465
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80449534
has comment: http://stackoverflow.com/comment/80450193
has comment: http://stackoverflow.com/comment/80450159
has comment: http://stackoverflow.com/comment/80450142
has comment: http://stackoverflow.com/comment/80449548

http://stackoverflow.com/q/46858172
favorite count: 0
upvote count: 3
score: 0
tagged with: apache-spark
tagged with: python
has title: Pyspark using customized function
type: AnsweredQuestion
downvote count: 3
type: Question
has body: I am a programmer in Scala Spark, but I need to do something in Python with PySpark in a project. I want to know how to use a customized row => row map transformation in PySpark. For example: I have a dataframe mydf: id x1, x2 1 5 3 2 4 6 3 9 10 I want to transform this dataframe into another dataframe, with the map operation on each row. So I designed a the map function, which take a row as input, and generate a new row as output. So it is a Row => Row map: def mySum (row): id = row.id result = row.x1 + row.x2 return Row(id, result) Then I want to use someway in python, which is similar I do in Scala mynewdf = mydf.map( x=&gt; mySum(x)) So the expected result looks like: id result 1 8 2 10 3 19 In reality, the custom function is very complicated, so I need a separated function to describe it. How can I do this in Python with PySpark. Thanks,
tagged with: pyspark
has answer: http://stackoverflow.com/a/46858262
accepted answer: http://stackoverflow.com/a/46858262
answer count: 1

http://stackoverflow.com/q/46901521
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80750787
type: Question
has comment: http://stackoverflow.com/comment/80750541
has answer: http://stackoverflow.com/a/46902157
answer count: 1
has body: A row in my csv file: console_ip,spsstatus,spsversion 172.19.126.182,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)^M,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83) I am getting: {'console_ip': '172.19.126.182', 'spsversion': None, 'spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)'} {'console_ip': '', 'spsversion': None, 'spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)'} Expected just one element in a dictionary: {'console_ip': '172.19.126.182', 'spsversion': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)','spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)'} My code: f = 'consolespsdata/hostIpmi_bom52' with open(f, 'rU') as csv_file: csv_reader = csv.DictReader(csv_file,delimiter=&quot;,&quot;) for line in csv_reader: if line['console_ip'] is not None: print line Im wondering what might be causing this issue.
tagged with: python-2.7
score: 0
has title: Python csv.DictReader does not split at comma's
has comment: http://stackoverflow.com/comment/80751221

http://stackoverflow.com/q/46902154
answer count: 1
type: UnansweredQuestion
downvote count: 0
score: 1
has title: pip install .\scipy-0.16.1-win32-superpack-python3.4.exe
type: Question
has body: I issue a command to install scipy see below PS C:\Users\yosief\Downloads&gt; pip install .\scipy-0.16.1-win32-superpack-python3.4.exe and I get an error-traceback Invalid requirement: '.\scipy-0.16.1-win32-superpack-python3.4.exe' It looks like a path. Does it exist? My ENV variable is set so I can issue pip install from C:\Users\yosief\Downloads&gt; even though my python path is: C:\Users\yosief\AppData\Local\Programs\Python\Python36-32 Thanks
tagged with: python
has answer: http://stackoverflow.com/a/47860991
favorite count: 0
tagged with: python-3.x
tagged with: pip
upvote count: 1

http://stackoverflow.com/comment/80529508
comment on: http://stackoverflow.com/q/46791139
score: 0
type: Comment
type: QuestionComment
has text: Can anyone optimize my entire code if I send you?

http://stackoverflow.com/q/46756606
tagged with: machine-learning
score: 13
has answer: http://stackoverflow.com/a/56999837
accepted answer: http://stackoverflow.com/a/46759065
type: AnsweredQuestion
has body: The sklearn DecisionTreeClassifier has a attribute called "splitter" , it is set to "best" by default, what does setting it to "best" or "random" do? I couldn't find enough information from the official documentation.
has answer: http://stackoverflow.com/a/66604945
has answer: http://stackoverflow.com/a/74498753
type: Question
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: What does "splitter" attribute in sklearn's DecisionTreeClassifier do?
has answer: http://stackoverflow.com/a/48555365
has answer: http://stackoverflow.com/a/46759065
answer count: 5
tagged with: python
upvote count: 13
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/56999837

http://stackoverflow.com/q/46788179
has answer: http://stackoverflow.com/a/46788336
downvote count: 0
has body: I have a data frame that look like this: Customer_ID Category Products 1 Veg A 2 Veg B 3 Fruit A 3 Fruit B 3 Veg B 1 Fruit A 3 Veg C 1 Fruit C I want to find out the for each customer ID for each category which products were bought, and create a column for each product accordingly. The output would look like this: Customer_ID Category Pro_1 Pro_2 Pro_3 1 Veg A NA NA 1 Fruit A NA C 2 Veg NA B NA 3 Veg NA B C 3 Fruit A B NA
has title: Converting long table to wide and creating columns according to the rows
type: Question
has answer: http://stackoverflow.com/a/46788434
has answer: http://stackoverflow.com/a/46788403
upvote count: 2
tagged with: python-2.7
answer count: 3
tagged with: pandas
favorite count: 0
tagged with: pivot-table
tagged with: python
possible better answer: http://stackoverflow.com/a/46788403
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46788434

http://stackoverflow.com/q/46886245
has body: I would redirect the user to "admin" page if he is superuser, else to normal "profile" but it didn't work urls.py url(r'^user/login/', LoginUserView.as_view(), name='login'), url(r'^user/profile/', UpdateUserView.as_view(), name='profile'), url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'), views.py class LoginUserView(auth_views.LoginView): template_name = "Login/login.html" #TODO def dispatch(self, request, *args, **kwargs): if self.request.user.is_superuser: self.redirect_field_name = reverse_lazy("admin") else: self.redirect_field_name = reverse_lazy("profile") return super(LoginUserView, self).dispatch(request, *args, **kwargs)
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46886929
has answer: http://stackoverflow.com/a/46886370
has title: redirect_field_name DJANGO didn't work
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46886929
possible better answer: http://stackoverflow.com/a/46886370
type: Question

http://stackoverflow.com/comment/80607237
type: Comment
has text: Did you create a get-function for self.logger? That might be a reason you cannot set it (without using a set-funtion that is).
type: QuestionComment
comment on: http://stackoverflow.com/q/46829930
score: 0

http://stackoverflow.com/q/46767614
has answer: http://stackoverflow.com/a/46776340
upvote count: 2
has body: I am trying to export data from a python pandas data frame to an existing MS Access table, I would like to replace the MS access table with data that has been updated (in python) I have tried to use pandas.to_sql, but I get an error message. I find this strange this using pandas.read_sql works seamlessly? Here is my code: import pyodbc import pandas as pd conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=H:\Work\IndexTrader\Data\database\IndexData.accdb;' ) cnxn = pyodbc.connect(conn_str) SQL = 'SELECT * FROM Index_data; Reading data from MS Access is fine, see below dfins = pd.read_sql(SQL, cnxn) However when I try to write back and replace the table in MS excess it doesn't work? dfins.to_sql('Index_data', cnxn, if_exists='replace') cnxn.close() The error I get is: DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Microsoft Access Driver] The Microsoft Access database engine cannot find the input table or query 'sqlite_master'. Make sure it exists and that its name is spelled correctly. (-1305) (SQLExecDirectW)") If there is an alternative way instead of pandas.to_sql, that would help as well, I just need to know how to export my data.
has answer: http://stackoverflow.com/a/66502259
type: Question
possible better answer: http://stackoverflow.com/a/46776340
accepted answer: http://stackoverflow.com/a/46770412
has comment: http://stackoverflow.com/comment/80480926
answer count: 3
tagged with: pandas
downvote count: 0
tagged with: ms-access
favorite count: 0
has comment: http://stackoverflow.com/comment/80481404
has title: Exporting or writing data from python pandas data frame to MS Access table
has answer: http://stackoverflow.com/a/46770412
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/46751996
tagged with: function
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
score: 2
has body: 'I have an excel file which contains many columns with strings, but i want to import certain columns of this excel file containing 'NGUYEN'. I want to generate a string from columns in my excel which had 'NGUYEN' in them. import pandas as pd data = pd.read_excel("my_excel.xlsx", parse_cols='NGUYEN' in col for cols in my_excel.xlsx, skiprows=[0]) data = data.to_string() print(data) SyntaxError: invalid syntax my_excel.xlsx Function output should be data = 'NGUYEN VIETNAM HANOIR HAIR PANTS BIKES CYCLING ORANGE GIRL TABLE DARLYN NGUYEN OMG LOL'
has comment: http://stackoverflow.com/comment/80470074
upvote count: 2
type: UnansweredQuestion
tagged with: excel
tagged with: import-from-excel
type: Question
has answer: http://stackoverflow.com/a/64163439
has title: Selecting and importing only certain columns from excel for importing

http://stackoverflow.com/q/46831006
has title: How to efficiently save ongoing results while using df.apply()
answer count: 1
has answer: http://stackoverflow.com/a/46831715
score: 0
tagged with: pandas
type: UnansweredQuestion
tagged with: python
has body: Gurus, I am trying to use a function Process_Data() to process data from a dataframe 'df' as follows: def Process_Data(row): ... return(row) def main(): ... df= df.apply(Process_Data, axis=1) I would like to save some intermediate results to a file while processing each row in the dataframe 'df', what would be the best practice? Thx.
tagged with: output
type: Question

http://stackoverflow.com/comment/81494918
type: Comment
comment on: http://stackoverflow.com/a/46854486
score: 0
type: AnswerComment
has text: There are two calls related to flicking, QGraphicsView::setCacheMode(QGraphicsView::CacheBackground); QGraphicsView::setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);

http://stackoverflow.com/q/46751154
favorite count: 0
tagged with: go
accepted answer: http://stackoverflow.com/a/46762795
tagged with: python
upvote count: 4
tagged with: spi
has body: I have a simple Python code that does initalize MFRC522 device properly: import spidev mode_reset = 0x0F def spi_transfer(data): r = spi.xfer2(data) return r def dev_write(address, value): r = spi_transfer([(address &lt;&lt; 1) &amp; 0x7E, value]) print("&gt;&gt;",[(address &lt;&lt; 1) &amp; 0x7E, value], r) return r def reset(): dev_write(0x01, mode_reset) spi = spidev.SpiDev() spi.open(0, 0) spi.max_speed_hz = 1000000 print(spi.mode, spi.bits_per_word, spi.lsbfirst) reset() that works perfectly fine - it returns the command code back 15, but the same initialization routine implemented in Go doesn't really work: package main import ( "fmt" "golang.org/x/exp/io/spi" "log" ) func main() { spiDev, err := spi.Open(&amp;spi.Devfs{ Dev: "/dev/spidev0.0", Mode: spi.Mode(spi.Mode0), MaxSpeed: int64(1000000), }) spiDev.SetMode(spi.Mode0) spiDev.SetBitOrder(spi.MSBFirst) spiDev.SetBitsPerWord(8) if err != nil { log.Fatal(err) } writeSpiData := func(dataIn []byte) (out []byte, err error) { out = make([]byte, len(dataIn)) err = spiDev.Tx(dataIn, out) return } devWrite := func(address int, data byte) (err error) { newData := [2]byte{(byte(address) &lt;&lt; 1) &amp; 0x7E, data} readBuf, err := writeSpiData(newData[0:]) fmt.Println("&gt;&gt;", newData, readBuf) return } if err != nil { log.Fatal(err) } devWrite(0x01, 0x0F) fmt.Println("Done") } This one returns [0 0] which is wrong. Does anyone know what might be wrong there?
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46762795
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/80455231
score: 4
has title: Golang and SPI - trying to init RF522 drive
has comment: http://stackoverflow.com/comment/80459463
answer count: 1

http://stackoverflow.com/q/46816619
upvote count: 1
has comment: http://stackoverflow.com/comment/80580736
tagged with: scipy
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80580616
has body: I am trying to build an efficient frontier as in the Markowitz problem. I have written the code below, but I get the error "ValueError: Objective function must return a scalar". I have tested 'fun' with some values, for example, I input to the console: W = np.ones([n])/n # start optimization with equal weights cov_matrix = returns.cov() fun = 0.5*np.dot(np.dot(W, cov_matrix), W) # variance of the portfolio fun The output is 0.00015337622774133828, which is a scalar. I don't know what might be wrong. Any help is appreciated. Code: from scipy.optimize import minimize import pandas as pd import numpy as np from openpyxl import load_workbook wb = load_workbook('path/Assets_3.xlsx') # in this workbook there is data for returns. # The next lines clean unnecessary first column and first row. ws = wb.active df = pd.DataFrame(ws.values) df1 = df.drop(0,axis=1) df1 = df1.drop(0) df1 = df1.astype(float) rf = 0.05 r_bar = 0.05 returns = df1.copy() def efficient_frontier(rf, r_bar, returns): n = len(returns.transpose()) W = np.ones([n])/n # start optimization with equal weights exp_ret = returns.mean() cov_matrix = returns.cov() fun = 0.5*np.dot(np.dot(W, cov_matrix), W) # variance of the portfolio cons = ({'type': 'eq', 'fun': lambda W: sum(W) - 1. }, {'type': 'ineq', 'fun': lambda W: np.dot(exp_ret,W) - r_bar }) bnds = [(0.,1.) for i in range(n)] # weights between 0..1. res = minimize(fun, W, (returns, cov_matrix, rf), method='SLSQP', bounds = bnds, constraints = cons) return res x= efficient_frontier(rf,r_bar,returns) x Some Data 1 2 3 1 0.060206 0.005781 0.001117 2 0.006463 -0.007390 0.001133 3 -0.003211 -0.015730 0.001167 4 0.044227 -0.006250 0.001225 5 -0.040571 -0.006910 0.001292 6 -0.007900 -0.006160 0.001208 7 0.068702 0.013836 0.001300 8 0.039286 0.009854 0.001350 9 0.012457 -0.007950 0.001358 10 -0.013758 0.001021 0.001283 11 -0.002616 -0.013600 0.001300 12 0.059004 -0.006090 0.001442 13 0.015566 0.002818 0.001308 14 -0.036454 0.001395 0.001283 15 0.058899 0.011072 0.…
has comment: http://stackoverflow.com/comment/80581439
has title: Optimization using scipy
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80580733
has comment: http://stackoverflow.com/comment/80581299
favorite count: 0
has comment: http://stackoverflow.com/comment/80580758
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80580639
has comment: http://stackoverflow.com/comment/80580675
tagged with: python
has comment: http://stackoverflow.com/comment/80581389
has answer: http://stackoverflow.com/a/46817222
has comment: http://stackoverflow.com/comment/80580989
has comment: http://stackoverflow.com/comment/80580557

http://stackoverflow.com/comment/80750719
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46899727
has text: what do you mean? inside the var `queryset` you can add whatever you want, for example `other_model.objects.filter(model=model.objects.get(pk=1))`

http://stackoverflow.com/a/46806558
has body: So, what you need is to cconvert a column with a list of values into multiple rows. One solution is to create a new dataframe and do a left join: df = pd.DataFrame({'A':['a','b'],'B':['x','y'], 'C':[['a1', 'a2'],['b1', 'b2', 'b3']]}) df # A B C # 0 a x a1, a2 # 1 b y b1, b2, b3 dfr=df['C'].apply(lambda k: pd.Series(k)).stack().reset_index(level=1, drop=True).to_frame('C') dfr # C # 0 a1 # 0 a2 # 1 b1 # 1 b2 # 1 b3 df'A','B'.join(dfr, how='left') # A B C # 0 a x a1 # 0 a x a2 # 1 b y b1 # 1 b y b2 # 1 b y b3 Finally, use reset_index() df'A','B'.join(dfr, how='left').reset_index(drop=1) # A B C # 0 a x a1 # 1 a x a2 # 2 b y b1 # 3 b y b2 # 4 b y b3 Credit: https://stackoverflow.com/a/39955283/2314737
answers question: http://stackoverflow.com/q/46805907
score: 0
has comment: http://stackoverflow.com/comment/80560830
type: Answer

http://stackoverflow.com/q/46768859
answer count: 1
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/9397944
favorite count: 0
has answer: http://stackoverflow.com/a/46770057
duplicate of: http://stackoverflow.com/q/9397944
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80494355
accepted answer: http://stackoverflow.com/a/46770057
tagged with: plot
type: Question
has body: I want to use the same colormap/color cycle/palette to every plot in a Jupyter notebook. With the seaborn package, I can use: seaborn.set_palette('Set1') Is there a way to do the same using only matplotlib, without using seaborn? I know how to define the colormap to each plot separately and I am aware of the predefined style (e.g, ggplot), but I can't find a way to define only the colormap to all the plots at once. My intention is simplify the code for my students, thus using the intricate code behind set_palette() is not an option. Edit: as the accepted answer shows, I was confusing colormap with color cycle.
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80485763
has title: How to change the default colors for multiple plots in matplotlib?
duplicate of: http://stackoverflow.com/q/33185037

parameters
tags question: http://stackoverflow.com/q/46764475
tags question: http://stackoverflow.com/q/46900923
type: Tag
tags question: http://stackoverflow.com/q/46867715
tag name: parameters
tags question: http://stackoverflow.com/q/46837384

recursion
type: Tag
tags question: http://stackoverflow.com/q/46835995
tags question: http://stackoverflow.com/q/46835876
tags question: http://stackoverflow.com/q/46864921
tags question: http://stackoverflow.com/q/46762971
tags question: http://stackoverflow.com/q/46814083
tag name: recursion
tags question: http://stackoverflow.com/q/46903638
tags question: http://stackoverflow.com/q/46870304
tags question: http://stackoverflow.com/q/46900269
tags question: http://stackoverflow.com/q/46887816
tags question: http://stackoverflow.com/q/46837378
tags question: http://stackoverflow.com/q/46855686
tags question: http://stackoverflow.com/q/46776769
tags question: http://stackoverflow.com/q/46862834
tags question: http://stackoverflow.com/q/46902467
tags question: http://stackoverflow.com/q/46758244
tags question: http://stackoverflow.com/q/46902481
tags question: http://stackoverflow.com/q/46874238
tags question: http://stackoverflow.com/q/46762063
tags question: http://stackoverflow.com/q/46777429

http://stackoverflow.com/a/46837764
accepted answer of: http://stackoverflow.com/q/46836518
answers question: http://stackoverflow.com/q/46836518
has body: Using networkx: import networkx edges = [[1, 2], [2, 3], [4, 5], [6, 7], [7, 8], [9, 4], [8, 5]] graph = networkx.Graph(edges) print(list(networkx.connected_components(graph))) Output: [set([1, 2, 3]), set([4, 5, 6, 7, 8, 9])]
upvote count: 2
has comment: http://stackoverflow.com/comment/80629448
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/46880143
type: AnsweredQuestion
has body: I have a dictionary that i'd like to filter with another dictionary ('filter options' shown about halfway down this post) with multiple items. I can figure something out for a single item but not the entire dictionary...I've looked about for a while but the other answers are for filter with just one entry (nicely solved with dictionary comprehension) this is what i have done so far for single item dictionary filter i.e. filter_options = { 'Attack': 25} for kfo, vfo in filter_options.iteritems(): for kp, vp in pokers.iteritems(): if vp[kfo] &gt;= vfo: print pokedex[kp] It works but I can't figure it out to filter for multiple items this is the much-truncated version of the dictionary pokedex = {1: {'Attack': 49.0, 'Defense': 49.0, 'HP': 45.0, 'Name': 'Bulbasaur', 'PokedexNumber': 1.0, 'SpecialAttack': 65.0, 'SpecialDefense': 65.0, 'Speed': 45.0, 'Total': 318.0, 'Type': 'GrassPoison'}, 2: {'Attack': 62.0, 'Defense': 63.0, 'HP': 60.0, 'Name': 'Ivysaur', 'PokedexNumber': 2.0, 'SpecialAttack': 80.0, 'SpecialDefense': 80.0, 'Speed': 60.0, 'Total': 405.0, 'Type': 'GrassPoison'}, 3: {'Attack': 82.0, 'Defense': 83.0, 'HP': 80.0, 'Name': 'Venusaur', 'PokedexNumber': 3.0, 'SpecialAttack': 100.0, 'SpecialDefense': 100.0, 'Speed': 80.0, 'Total': 525.0, 'Type': 'GrassPoison'}} # Only filter based on parameters passed filter_options = { 'Attack': 25, 'Defense': 30, 'Type': 'Electric' } i.e Return records with attack >= 25, defense >= 30, and type == "Electric" Also anticipate that other paramters can also be passed such as "SpecialAttack", "Speed", etc. Example output: [{'Attack': 30.0, 'Defense': 50.0, 'HP': 40.0, 'Name': 'Voltorb', 'SpecialAttack': 55.0, 'SpecialDefense': 55.0, 'Speed': 100.0, 'Total': 330.0, 'Type': 'Electric'}, {'Attack': 30.0, 'Defense': 33.0, 'HP': 32.0, 'Name': 'Pikachu', 'SpecialAttack': 55.0, 'SpecialDefense': 55.0, 'Speed': 100.0, 'Total': 330.0, 'Type': 'Electric'}, ... etc ] i'll prolly stick it into a function along the lines of def filtered_pokedex(p…
has answer: http://stackoverflow.com/a/46880475
has comment: http://stackoverflow.com/comment/80708584
has answer: http://stackoverflow.com/a/46880197
type: Question
score: 0
answer count: 3
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/46880276
has answer: http://stackoverflow.com/a/46880276
has comment: http://stackoverflow.com/comment/80707620
has comment: http://stackoverflow.com/comment/80707532
has title: Filtering a dictionary with another dictionary containing multiple items
accepted answer: http://stackoverflow.com/a/46880197

http://stackoverflow.com/q/46901361
has title: Professor asked to write this program in python:
tagged with: loops
has comment: http://stackoverflow.com/comment/80749693
has body: Professor asked to write this program in python: Problem Write a program to prompt for the number of triangles and the height of each triangle, then print out all the specified triangles. The triangles should have the following format: How many triangles: 2 The height of the triangle: 3 1 3 5 7 9 11 The height of the triangle: 4 1 3 5 7 9 11 13 15 17 19 Process finished with exit code 0 How many triangles: 3 The height of the triangle: 1 1 The height of the triangle: 3 1 3 5 7 9 11 The height of the triangle: 5 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 Process finished with exit code 0 I got this so far: number = eval(input("Enter height")) for i in range(1, number+1): for j in range(i, 10): print(j+i, end="\t") print("\n") print()
type: Question
score: 0
has answer: http://stackoverflow.com/a/46901694
answer count: 1
tagged with: nested
has comment: http://stackoverflow.com/comment/80749711
has comment: http://stackoverflow.com/comment/80749656
has comment: http://stackoverflow.com/comment/80749641
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/46801226
type: UnansweredQuestion
answer count: 4
has answer: http://stackoverflow.com/a/46802085
has body: Sorry, I couldn't think of a better way to phrase the title! Basically, I want an abstract base class, then a sub-class of that which doesn't implement the abstract method, then a sub-class of that, which does implement the method. It's probably easier with an example: import abc class A(abc.ABC): def __init__(self, some_var): self.some_var = some_var @abc.abstractmethod def some_method(self): pass class B(A): def some_b_method(self): print("Hello") class C(B): def some_method(self): self.some_b_method() print(self.some_var) c = C('world') c.some_method() This is how I would expect it to work, but for the B class above Pylint reports warning 0223. Pylint doesn't give me any problems if I modify the B class to include the following, but the duplication of code seems wrong: @abc.abstractmethod def some_method(self): pass Is there a "correct" way? I couldn't find the answer.
favorite count: 0
type: Question
tagged with: pylint
tagged with: python
has answer: http://stackoverflow.com/a/46801289
score: 4
has answer: http://stackoverflow.com/a/46801260
downvote count: 1
upvote count: 5
has title: "Passing" the implementation of an abstract method through to subclass further down in Python?
has answer: http://stackoverflow.com/a/46801930

http://stackoverflow.com/q/46835146
downvote count: 0
answer count: 4
favorite count: 0
has title: Django - get current user permissions in a view?
has answer: http://stackoverflow.com/a/56188665
tagged with: django
upvote count: 1
accepted answer: http://stackoverflow.com/a/46835218
tagged with: python
has answer: http://stackoverflow.com/a/53880185
type: AnsweredQuestion
has body: Im trying to get the current logged on users permissions My current attempt below returns an error from django.contrib.auth.models import Permission from django.contrib.auth.models import User permissions = Permission.objects.filter(user=User.id) Error int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' does anyone know how I can do this? is there a simpler way? Thanks
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/61436780
has answer: http://stackoverflow.com/a/61436780
has answer: http://stackoverflow.com/a/46835218

http://stackoverflow.com/a/46863718
upvote count: 1
has body: itemgetter(0) gets the item at 0th index. In your first case, you are sorting 0th indexes of v in reverse order. So basically what you are actually doing is sorting 0th indexes of ["t1", "t2"], ["t3", "t4"] and ["tdfgdf99","x99"] in reverse order. In your second case, you are sorting v which is list values - basically [["t1","t2"], ["t3, "t4"], ["tdfgdf99","x99"]] as is in reverse order. the purpose of lambda k: k is you are simply picking one element from this list and returning.
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46863568
answers question: http://stackoverflow.com/q/46863568
type: Answer

http://stackoverflow.com/comment/80760590
has text: Thank you for your excellent answer. Coming back to the unusually large number of data points, this error shows when exceuting with more 70000 points: `ValueError: Image size of 79105x2400 pixels is too large. It must be less than 2^16 in each direction.` What can be done about this (besides splitting the graph into multiple parts and rejoin with another program)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46849891
type: AnswerComment

http://stackoverflow.com/comment/80743775
has text: Thank you so much for your help. This works perfectly but I will need to compare the year as well as the month. I thought the year would be an integer but when brought in from datetime it is a string meaning I can't compare it an input. Should I add the month within that code? How would I change it to an integer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46897878
type: Comment

http://stackoverflow.com/q/46854517
tagged with: python
type: AnsweredQuestion
has title: Django: int() argument must be a string , a bytes-like object or a number, not 'Game'
type: Question
answer count: 2
has body: Here's my code, objects = sorted(Game.objects.filter(...), key=lambda x: random.random()) items = Game.objects.exclude(pk__in=objects) But, i'm getting this error, int() argument must be a string, a bytes-like object or a number, not 'Game' How can I fix this problem?
possible better answer: http://stackoverflow.com/a/46854578
score: 0
accepted answer: http://stackoverflow.com/a/46854602
has answer: http://stackoverflow.com/a/46854602
has answer: http://stackoverflow.com/a/46854578
tagged with: django

http://stackoverflow.com/a/46901126
has comment: http://stackoverflow.com/comment/80749198
answers question: http://stackoverflow.com/q/46900659
type: Answer
has comment: http://stackoverflow.com/comment/80749336
score: 1
upvote count: 1
has body: I think you can do this way .. df['C']=df.stack().groupby(level=0).apply(','.join) df Out[459]: A B C 0 a f a,f 1 b NaN b 2 NaN u u 3 c i c,i 4 NaN NaN NaN Add timing : small Data set: %timeit df.apply(lambda x: ', '.join(x.dropna()), 1).replace('', np.nan) 1000 loops, best of 3: 1.6 ms per loop %timeit df.stack().groupby(level=0).apply(','.join) 1000 loops, best of 3: 1.41 ms per loop Large data set (both slow) df=pd.concat([df]*1000,axis=1) df=pd.concat([df]*1000,axis=0) %timeit df.apply(lambda x: ', '.join(x.dropna()), 1).replace('', np.nan) 1 loop, best of 3: 2.1 s per loop %timeit df.stack().groupby(level=0).apply(','.join) 1 loop, best of 3: 1.23 s per loop
has comment: http://stackoverflow.com/comment/80749289
downvote count: 0

http://stackoverflow.com/a/46786807
has comment: http://stackoverflow.com/comment/80558039
type: AcceptedAnswer
upvote count: 6
has comment: http://stackoverflow.com/comment/80612338
has comment: http://stackoverflow.com/comment/80519973
has comment: http://stackoverflow.com/comment/80520119
type: Answer
score: 6
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46786463
has comment: http://stackoverflow.com/comment/80560500
answers question: http://stackoverflow.com/q/46786463
has body: yes, you're missing something trivial. a = tf.constant(0.0) a is a python variable that holds a constant node of the computational graph. In the graph it has a name, let's call it constant:0. a = a + 1.0 a is a new python variable (the assignment is a destructive operation) that holds the add operation between the node constant:0 that is still defined in the graph and a new constant node, automatically create when using 1.0 (constant_1:0). Thus, in this line, you're overriding a python variable in order to make it holding an add node: you're not touching the values of the graph node constant:0. The constant, in fact, is defined in the graph that tensorflow describes and it can't be changed. What you can change, instead, is the python variable that points to a certain node in the graph. You can think about the python variables as pointers to the graph's nodes.

http://stackoverflow.com/comment/80613666
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46832711
has text: @mrCarnivore can you read traceback?
score: 0

http://stackoverflow.com/a/46755289
score: 0
has body: The issue is with the logic. ‘Yes’ != ‘No’, so one of the conditions will always be hit. I am not familiar with python syntax, logically what you need is: while not (input == ‘Yes’ or input == ‘No’) At this point, any single match would be good
type: Answer
answers question: http://stackoverflow.com/q/46755238

http://stackoverflow.com/a/50712203
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46770018
score: 2
has body: you can use the following code: r1.get_support(indices=True) print(u'有效特征为：%s' % ','.join(data.columns[rlr.get_support()])) I think the reason for the Indexerror is the version of numpy.you can look at the docs。 [https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#index-arrays][1] Boolean arrays must be of the same shape as the initial dimensions of the array being indexed.
upvote count: 2

http://stackoverflow.com/comment/80630312
comment on: http://stackoverflow.com/q/46840920
score: 0
type: Comment
type: QuestionComment
has text: Sounds like a deploy-time thing, not an execution-time thing. So, lambda would not be a good choice for this.

http://stackoverflow.com/q/46869500
has comment: http://stackoverflow.com/comment/80686254
type: Question
score: 0
has title: __iadd__ magic function issues
has comment: http://stackoverflow.com/comment/80686277
tagged with: python
tagged with: dictionary
answer count: 0
type: UnansweredQuestion
has body: The following is some code from a class called Container, which is intended to be a versitile data value storage with extra capabilities that the built in types dont't have. the __iadd__ function, for whatever reason, makes self equal to None. However, the __add__ function seems to be working perfectly fine, and the other argument is not affected. This problem is baffling me and any help is appreciated. class Container(): def __init__(self,list0,list1): self.list0,self.list1=list0,list1 self.pairs=zip(list0,list1) self.items=dict(self.pairs) ... def __add__(self,other): dictionary=self.items other = other if type(other)==dict else other.items for k in other.keys(): dictionary[k]=other[k] return dictionary ... def __iadd__(self,other): self.items=self+other # &gt;&gt;&gt; c2 = Container([11,12,13],['k','l','m']) # &gt;&gt;&gt; print container + c2 # {0: 'j', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 11: 'k', 12: 'l', 13: 'm'} # # Note: at this time the container does not equal None. # # &gt;&gt;&gt; container+=c2 # &gt;&gt;&gt; print container # None
has comment: http://stackoverflow.com/comment/80686218

http://stackoverflow.com/q/46876826
has title: Django - Limit the number of objects in Django template
type: Question
score: 0
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/80700948
has answer: http://stackoverflow.com/a/46876896
accepted answer: http://stackoverflow.com/a/46876896
tagged with: python
has body: I used to code in C#. I want to use Python to do something like: int start_index = 4; List&lt;int&gt; list = { ... } for(int i = start_index;i &lt; 10;i++){ list[i].dosomething(); } This is how I tried in Django {% with 0 as starting_index %} {% for comment in comments %} &lt;!--set a variable to limit the amount of comment on a page--&gt; {% with forloop.counter as index %} {% if index &lt; 3 %} &lt;div class="comment_body"&gt; &lt;div class="content_block"&gt; &lt;p&gt;{{comments[index]}}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; {% endif %} {% endwith %} {% endfor %} {% endwith %} This code is obviously not working. Can anybody help me with this problem? Thanks in advance!
has comment: http://stackoverflow.com/comment/80700927
tagged with: django
has comment: http://stackoverflow.com/comment/80700652
type: AnsweredQuestion
tagged with: tags

http://stackoverflow.com/a/46846684
has comment: http://stackoverflow.com/comment/80650065
has body: First method is OK if you know what you are doing. More explanation: In both method, you need to make sure your two threads have access to a shared variable(lp_voltage or v_queue). What the real advantage v_queue has is consistence. If you don't care about consistence, you can just simply use a variable. To implement this more pythonic, you can wrap your whole project into an object. For example: class VoltageTask: def __init__(self): self.lp_voltage = 0 self.thread = Thread(target=self.update_voltage) def update_voltage(self): self.lp_voltage = your_function_to_get_voltage() def main_thread(self): ... def start(self): self.thread.start() self.main_thread() if __name__ == "__main__": task = VoltageTask() task.start()
upvote count: 3
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/46846475
downvote count: 0
answers question: http://stackoverflow.com/q/46846475
type: AcceptedAnswer

http://stackoverflow.com/a/46863737
has comment: http://stackoverflow.com/comment/80675042
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80676400
has comment: http://stackoverflow.com/comment/80676411
has comment: http://stackoverflow.com/comment/80676589
answers question: http://stackoverflow.com/q/46863047
has comment: http://stackoverflow.com/comment/80691483
score: 0
has comment: http://stackoverflow.com/comment/80674991
has comment: http://stackoverflow.com/comment/80690810
type: Answer
has body: Corner detectors often cannot be relied on. The show extra corners and miss the ones you expect. What's more, you have to identify an regroup them. You obtain interesting results by computing a saturation image (S in LSH). Then by binarization and blob analysis, you can easily find the areas.
accepted answer of: http://stackoverflow.com/q/46863047
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/80457430
comment on: http://stackoverflow.com/q/46755784
type: QuestionComment
has text: I see! Not filtering on the gender gives you two observations for each year: one for male, one for female. Hence the line plot oscillates heavily making it appear as shown above.
type: Comment
score: 1

http://stackoverflow.com/a/51217256
upvote count: 6
has body: I know that this question is a little old, but I thought I would share what I found when trying to use python/kubernetes attach/exec for several debugging cases (since this isn't documented anywhere I can find). As far as I can tell, it's all about making the keyword arguments match the actual container configuration as opposed to what you want the container to do. When creating pods using kubectl run, if you don't use -i --tty flags (indicating interactive/TTY allocation), and then attempt to set either the tty or stdin flags to True in your function, then you'll get a mysterious 500 error with no other debug info. If you need to use stdin and tty and you are using a configuration file (as opposed to run), then make sure you set the stdin and tty flags to true in spec.containers. While running resp.readline_stdout(), if you get a OverflowError: timestamp too large to convert to C _PyTime_t, set the keyword argument timeout=&lt;any integer&gt;. By default, the timeout variable defaults to None, which is an invalid value in that function. If you run the attach/exec command and get an APIException and a status code of 0, the error Reason: hostname 'X.X.X.X' doesn't match either of..., note that there appears to be an incompatibility with Python 2. Works in Python 3. Should be patched eventually. I can confirm 404 code is thrown via an ApiException when the pod doesn't exist. If you are getting a mysterious error saying upgrade request required, note that you need to use the kubernetes.stream.stream function to wrap the call to attach/exec. You can see this issue on GitHub and this example code to help you get past that part. Here's my example: resp = kubernetes.stream.stream(k8s.connect_get_namespaced_pod_attach, name='alpine-python-2', namespace="default", stderr=True, stdin=True, stdout=True, tty=True, _preload_content=False) Note that the _preload_content=False is essential in the attach command or else the call will block indefinitely. I know that was probably mor…
answers question: http://stackoverflow.com/q/46789946
downvote count: 0
score: 6
type: Answer

http://stackoverflow.com/comment/80605373
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46827321
has text: Bad practice. You're unnecessarily creating a list for your purposes, just so you can have an one-liner.

http://stackoverflow.com/comment/80553512
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/46800562
has text: [Port 25 is documented as being blocked from Lambda Functions](https://aws.amazon.com/lambda/faqs/#functions) and is probably the default port being used here, which is actually wrong but very commonly used anyway. Your mail server should accept mail on MSA port 587 (or another port).

http://stackoverflow.com/q/46829474
score: 0
has answer: http://stackoverflow.com/a/46829832
answer count: 1
tagged with: python
has body: I am trying to import feedparser in Python, and want to call FeedParserDict from the library feedparser, i.e., feedparser.FeedParserDict. But it leads to the following error: "AttributeError: module 'feedparser' has no attribute 'FeedParserDict'." Does it mean that "FeedParserDict" is not in the library feedparser (version 5.2.1). I find that "FeedParserDict" is present in previous version of feedparser (i.e., version 3.3). How can I cope with this error?
type: Question
type: AnsweredQuestion
tagged with: feedparser
accepted answer: http://stackoverflow.com/a/46829832
has title: AttributeError: module 'feedparser' has no attribute 'FeedParserDict'

http://stackoverflow.com/comment/80737227
has text: I'm not sure what you mean by HTML table tags. I can't see any HTML table tags in your expected output
type: Comment
comment on: http://stackoverflow.com/a/46894977
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80604498
comment on: http://stackoverflow.com/q/46828008
score: 0
type: Comment
type: QuestionComment
has text: @244boy you say "Off course" - but since you don't share the code we can't check you're not doing anything silly that could possibly cause a lot more work than required. In regards to caching, a search for "django caching" will produce a lot of results that you can then deem whether they're fit for your scenario as you haven't shared what that scenario is either...

http://stackoverflow.com/a/46856468
score: 1
has body: df[df.applymap(np.isreal).sum(1).gt(0)] Out[794]: A 2 {'a': 5, 'b': 6, 'c': 8} 5 {'d': 9, 'e': 10, 'f': 11}
has comment: http://stackoverflow.com/comment/80660760
has comment: http://stackoverflow.com/comment/80660611
answers question: http://stackoverflow.com/q/46856276
upvote count: 1
has comment: http://stackoverflow.com/comment/80660691
has comment: http://stackoverflow.com/comment/80660785
has comment: http://stackoverflow.com/comment/80660533
has comment: http://stackoverflow.com/comment/80660664
has comment: http://stackoverflow.com/comment/80660583
has comment: http://stackoverflow.com/comment/80662104
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80661204
has comment: http://stackoverflow.com/comment/80660700

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

http://stackoverflow.com/comment/80689127
comment on: http://stackoverflow.com/a/46870829
type: AnswerComment
has text: Also added a groupby approach for multiple maximas . Thank you sir
score: 0
type: Comment

http://stackoverflow.com/comment/80465984
has text: Don't vandalize your posts.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46759238
score: 0

http://stackoverflow.com/comment/80851786
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46866604
type: Comment
has text: it only shows the first "select one" in the menu and menu does not drop down, but when i inspect the element, it populates with all the option but does not appear.

apscheduler
tags question: http://stackoverflow.com/q/46848651
tag name: apscheduler
tags question: http://stackoverflow.com/q/46883868
tags question: http://stackoverflow.com/q/46807428
type: Tag

http://stackoverflow.com/q/46786358
has title: Elegant way of doing post-processing using Python
accepted answer: http://stackoverflow.com/a/46791885
score: 0
has comment: http://stackoverflow.com/comment/80519191
tagged with: overriding
tagged with: inheritance
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46791885
linked to: http://stackoverflow.com/q/4723717
has body: Considering the following example of post-processing using inheritance in python (from this website): import os class FileCat(object): def cat(self, filepath): f = file(filepath) lines = f.readlines() f.close() return lines class FileCatNoEmpty(FileCat): def cat(self, filepath): lines = super(FileCatNoEmpty, self).cat(filepath) nonempty_lines = [l for l in lines if l != '\n'] return nonempty_lines Basically, when we are post-processing, we don't really care about the original invocation, we just want to work with the data returned by the function. So ideally, in my opinion, there should be no need for us to have redeclare the original function signature, just to be able to forward it to the original function. If FileCat class had 100 different functions (cat1,cat2,cat3,...) that returned the same type of data and we wanted to use a post-processed NoEmpty version, then we would have to define the same 100 functions signatures in FileCatNoEmpty just to forward the calls. So the question is: Is there a more elegant way of solving this problem? That is, something like the FileCatNoEmpty class that would automatically make available all methods from FileCat but that still allows us to process the returned value? Something like class FileCatNoEmpty(FileCat): # Any method with whatever arguments def f(self,args): lines = super(FileCatNoEmpty, self).f(args) nonempty_lines = [l for l in lines if l != '\n'] return nonempty_lines Or maybe even another solution that does not uses inheritance. Thanks!
type: Question
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/11349183

http://stackoverflow.com/q/46788035
tagged with: performance
score: 1
has comment: http://stackoverflow.com/comment/80533293
has comment: http://stackoverflow.com/comment/81532586
downvote count: 0
has body: I am helping to develop a fairly complex web application with Django. However some pages are taking 10+ seconds to render. I can't seem to get to the bottom of why this is so slow. The Django Debug Toolbar shows that the bottleneck is clearly CPU, rather than the database or anything else, but it doesn't go into any further detail (as far as I can see). I have tried running a profiler on the system, but can't make head or tail of what is going on from this either. It only shows deep internals as taking up the vast majority of the time, especially &lt;method 'poll' of 'select.poll' objects&gt;, and other such functions as builtins.hasattr, getmodule, ismodule, etc. I've also tried stepping through the code manually, or pausing execution at random points to try to catch what's going on. I can see that it takes quite a long time to get through a ton of import statements, but then it spends a huge amount of time inside render() functions, taking especially long loading a large number of model fields--something in the order of 100 fields. None of what is happening looks wrong to me, except for the insane amount of time everything takes to run. It's as though Python is just taking forever to load and parse each .py file before doing any processing. However, this is all running on a brand new Digital Ocean server with an SSD, with Gunicorn, PostgreSQL and Nginx. Does anyone have any hints how I can get to the bottom of this?
favorite count: 0
has comment: http://stackoverflow.com/comment/81533086
tagged with: python
has title: Extremely high CPU usage in Django
answer count: 0
has comment: http://stackoverflow.com/comment/80816454
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
tagged with: debugging

http://stackoverflow.com/q/46895696
has answer: http://stackoverflow.com/a/46895786
tagged with: python
score: 22
has title: Prevent duplicates from itertools.permutations
accepted answer: http://stackoverflow.com/a/46895786
has body: I want to get all the unique permutations for a 4 character string using 2 A and 2 B from itertools import permutations perm = permutations('AABB', 4) for i in list(perm): print(i) This gets me ('A', 'A', 'B', 'B') ('A', 'A', 'B', 'B') ('A', 'B', 'A', 'B') ('A', 'B', 'B', 'A') ... As you can see I get duplicates. I guess this is because it treats the A in the 1st place and 2nd place are different values, but to me AABB is simply 1 unique result. I can workaround this results by throwing all of them into a set to get rid of the dups, but I think I'm just using the permutation function wrong. How do I use permutation function to get all the unique permutations with using 2 A's and 2 B's without getting the dups?
answer count: 5
upvote count: 22
has answer: http://stackoverflow.com/a/46895896
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46895801
favorite count: 0
possible better answer: http://stackoverflow.com/a/72969842
has answer: http://stackoverflow.com/a/46895814
has answer: http://stackoverflow.com/a/72969842
type: Question

http://stackoverflow.com/a/46749043
has comment: http://stackoverflow.com/comment/80444410
has comment: http://stackoverflow.com/comment/80444309
has comment: http://stackoverflow.com/comment/80444225
score: -2
type: AcceptedAnswer
downvote count: 2
answers question: http://stackoverflow.com/q/46748976
type: Answer
has comment: http://stackoverflow.com/comment/80444350
accepted answer of: http://stackoverflow.com/q/46748976
upvote count: 0
has body: Question and my answer changed. Here is the last suggestion: string = "wordetcetcetcetcetcetcetcword" import re find = "word" p = re.compile(find) matches = [m.start() for m in p.finditer(string)] print(matches) Returns: [0, 25]

http://stackoverflow.com/q/46863394
has comment: http://stackoverflow.com/comment/80674286
tagged with: function
has comment: http://stackoverflow.com/comment/80674371
has comment: http://stackoverflow.com/comment/80674663
has comment: http://stackoverflow.com/comment/80674548
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80674424
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80674268
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46863436
tagged with: python
has body: In the following function ,clc, whenever I fail to pass the third argument 'z', I want the fuction to automatically perform addition. (i.e) If I pass only two arguments (150,200), I want to get the same result as I do when I pass (150,200,'a'). Unfortunately I am getting a traceback that 'UnboundLocalError: local variable 'r' referenced before assignment'. Can anyone please explain why I get this error? Thanks. def clc(x,y,z=None): if (z=='a') or (z is None): r=x+y elif z=='s': r=x-y elif z=='m': r=x*y elif z=='d': r=x/y elif z=='mod': r=x%y elif z=='ex': r=x**y return r while True: a=int(input('Enter a number:\t ')) b=int(input('Enter a number:\t ')) op=input('enter the operation:\t') answer=clc(a,b,op) print('the answer is',answer) query=input('If you want to continue, please press Enter\t') if len(query)&gt;0: break Edit: Thanks to PM2Ring for his explanation which cleared my error! This is his reply : 'If you just hit Enter at the 'enter the operation' prompt then op gets assigned the empty string '', it's not None. And then when you call clc(a,b,op) none of your if tests are True, and so r never gets assigned a value. The if statement I posted earlier handles that empty string case.'
has comment: http://stackoverflow.com/comment/80674603
has comment: http://stackoverflow.com/comment/80674498
type: Question
has comment: http://stackoverflow.com/comment/80674744
has title: When setting default arguments to a function in Python using None, why I am getting 'UnboundLocalError'?
has answer: http://stackoverflow.com/a/46863477

http://stackoverflow.com/a/46881259
has body: I'm not sure if I understand your question, but if you need the positions where the gradient is zero, you can write something like this: from numpy import gradient g = gradient(f) zeros = [ i for i,x in enumerate(g) if x.any() == 0 ] print(zeros)
upvote count: 0
has comment: http://stackoverflow.com/comment/80713190
has comment: http://stackoverflow.com/comment/80709819
has comment: http://stackoverflow.com/comment/80709997
has comment: http://stackoverflow.com/comment/80713068
score: -1
accepted answer of: http://stackoverflow.com/q/46881107
answers question: http://stackoverflow.com/q/46881107
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/a/46891078
has comment: http://stackoverflow.com/comment/80731506
accepted answer of: http://stackoverflow.com/q/46890972
has body: Use a temporary varaible to store the value using .copy(), because you are changing the values while assigning them on chain i.e. Unless you use copy the data will be changed directly. a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B']) b, c = a.iloc[0], a.iloc[1] temp = a.iloc[0].copy() a.iloc[0] = c a.iloc[1] = temp Or you can directly use copy like a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B']) b, c = a.iloc[0].copy(), a.iloc[1].copy() a.iloc[0],a.iloc[1] = c,b
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80731316
type: Answer
score: 21
upvote count: 21
answers question: http://stackoverflow.com/q/46890972

http://stackoverflow.com/comment/80707401
comment on: http://stackoverflow.com/a/46880087
score: 0
type: AnswerComment
has text: sorry and last part of the question - is how to interpret the results of the optimizer
type: Comment

http://stackoverflow.com/q/46765617
answer count: 1
tagged with: flask
has title: Call a python script with flask: what is the best way?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46771185
upvote count: 1
downvote count: 1
tagged with: plot
type: Question
tagged with: matplotlib
has body: I am fairly new to flask and therefore I have a question regarding the logic behind my code and if my thought process makes sense. I have an old python script, that takes a lot of data, processes it and then produces a plot with matplotlib. This works fine. Now I want to build a web application, where a user selects specific input parameters, clicks the submit button, my server checks (with the help of sqlite) if there already exists a plot/the data to make the plot with those parameters, if yes then make it downloadable by the user. If this plot/the data does not exist, my flask application calls my python script and the new plot/data for it will get created, uploaded to sqlite and then the user can download it from the web application. As you can see in my code so far the python script is an external one and my plan is to not include it in my views from my flask app, does this make sense? Should I call an external script here or just copy the code directly to my views? (I wanted to avoid it so far since it's a pretty big script) My logic so far looks like this: # this part works well so far, I get the user input here and redirect it to the specific page @app.route('/plot', methods = ['GET','POST']) def get_plot(): if request.method == 'POST': input1 = request.form['input1'] input2 = request.form['input2'] input3 = request.form['input3'] return redirect('plot/{}/{}/{}/'.format(input1, input2, input3)) else: return render_template('plot.html') # here it get's a bit tricky for me @app.route('/plot/&lt;input1&gt;/&lt;input2&gt;/&lt;input3&gt;/') def create_plot(input1='1', input2='2', input3='3'): try: db = get_db(DB_PLOT) cur = db.execute('SELECT * FROM {} WHERE param1 = {} AND param2={}'.format(input1, input2, input3)) # get all the data from the table except: return "Plot not found !" # CALL THE EXTERNAL PYTHON SCRIPT HERE? cur = db.execute('SELECT * FROM {} WHERE param1 = {} AND param2={}'.format(input1, input2, input3)) # python script should have updated the dat…
score: 0

http://stackoverflow.com/a/46844535
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46818117
answers question: http://stackoverflow.com/q/46818117
type: Answer
score: 1
has body: I found the solution. Firstly, include pubsub from wx.lib.pubsub import pub Then, I neet to set the subscribe, right after the creating of ListCtrl self.list_ctrl = wx.ListCtrl(panel, size=(680, 340), style=wx.LC_REPORT | wx.BORDER_SUNKEN ) self.list_ctrl.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.DoubleClick) pub.subscribe(self.UpdateListView, 'UpdateListview') also, I need to make the function inside same class of ListCtrl creation. def UpdateListView(self): self.list_ctrl.DeleteAllItems() #Do something else Then, from any other class you just send a message to update the list. pub.sendMessage('UpdateListview')
upvote count: 1

http://stackoverflow.com/comment/80497987
has text: But here you fetch all records, and you are only printing the first one?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46776234
type: Comment

http://stackoverflow.com/comment/80520797
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46785814
has text: my current code `def update(self, instance, validated_data): instance = super().update(instance, validated_data) routes = validated_data.get('routes') print("GGGGG", validated_data) if routes: for route_info in routes: Route.objects.filter(id=route_info['id']).update(**route_info) return instance `

http://stackoverflow.com/a/49893339
has comment: http://stackoverflow.com/comment/104718413
has comment: http://stackoverflow.com/comment/89814937
has comment: http://stackoverflow.com/comment/98926802
has comment: http://stackoverflow.com/comment/90727510
has comment: http://stackoverflow.com/comment/101967403
has comment: http://stackoverflow.com/comment/98753978
score: 308
has comment: http://stackoverflow.com/comment/102276081
has comment: http://stackoverflow.com/comment/95504520
has comment: http://stackoverflow.com/comment/113527065
has comment: http://stackoverflow.com/comment/98639045
has comment: http://stackoverflow.com/comment/135759127
has comment: http://stackoverflow.com/comment/98205842
accepted answer of: http://stackoverflow.com/q/46902357
upvote count: 310
has comment: http://stackoverflow.com/comment/98891467
has comment: http://stackoverflow.com/comment/113856621
has comment: http://stackoverflow.com/comment/124303933
has comment: http://stackoverflow.com/comment/96379987
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98789028
answers question: http://stackoverflow.com/q/46902357
has comment: http://stackoverflow.com/comment/125677100
has body: pip install pymysql Then, edit the __init__.py file in your project origin dir(the same as settings.py) add: import pymysql pymysql.install_as_MySQLdb()
downvote count: 2
has comment: http://stackoverflow.com/comment/89841220
type: Answer
has comment: http://stackoverflow.com/comment/98250573

http://stackoverflow.com/q/46773165
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46776679
tagged with: screenshot
tagged with: pyqt5
upvote count: 1
accepted answer: http://stackoverflow.com/a/46776679
type: Question
has body: So the idea is that I should be able to fire up the script, select a portion of the screen, then hit enter (or otherwise trigger it) to save the selection. I've got a good bit of the code from other posts and things, but now I'm stuck. I can select any portion of the screen and resize as needed, but I can't seem to get it to recognize the "enter" key. Right now the "keyPressEvent" function is just supposed to print a message so I know it worked, but I got nothing. Any ideas? import sys from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtCore import Qt, QPoint, QRect, QSize from PyQt5.QtGui import QScreen from PyQt5.QtWidgets import QApplication, QLabel, QRubberBand class MyLabel(QtWidgets.QLabel): def __init__(self, parent=None): QtWidgets.QLabel.__init__(self, parent) self.selection = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self) def keyPressEvent(self, qKeyEvent): print(qKeyEvent.key()) if qKeyEvent.key() == QtCore.Qt.Key_Return: print('Enter pressed') else: super().keyPressEvent(qKeyEvent) def mousePressEvent(self, event): ''' Mouse is pressed. If selection is visible either set dragging mode (if close to border) or hide selection. If selection is not visible make it visible and start at this point. ''' if event.button() == QtCore.Qt.LeftButton: position = QtCore.QPoint(event.pos()) if self.selection.isVisible(): # visible selection if (self.upper_left - position).manhattanLength() &lt; 20: # close to upper left corner, drag it self.mode = "drag_upper_left" elif (self.lower_right - position).manhattanLength() &lt; 20: # close to lower right corner, drag it self.mode = "drag_lower_right" else: # clicked somewhere else, hide selection self.selection.hide() else: # no visible selection, start new selection self.upper_left = position self.lower_right = position self.mode = "drag_lower_right" self.selection.show() def mouseMoveEvent(self, event): ''' Mouse moved. If selection is visible, drag it according to drag mode. ''' if self.selection.isVisibl…
answer count: 1
downvote count: 0
score: 1
tagged with: key
favorite count: 0
has title: PyQt5 Grab and save section of screen
tagged with: python

http://stackoverflow.com/a/46898960
score: 0
has body: Yes it is possible to put another dataframe (or any type of object) in a pandas cell. In[2]: df1 = pd.DataFrame({'a':range(2)}) df1 Out[2]: a 0 0 1 1 In[3]: df2 = pd.DataFrame({'x':range(3), 'y':range(3)}) df2 Out[3]: x y 0 0 0 1 1 1 2 2 2 In[4]: df1['b'] = [df2, {'cat':'meow', 'otter':'clap'}] df1 Out[4]: a b 0 0 x y 0 0 0 1 1 1 2 2 2 1 1 {u'otter': u'clap', u'cat': u'meow'} In[5]: df1.get_value(0, 'b') Out[5]: x y 0 0 0 1 1 1 2 2 2 As you see it's not very readable to print a dataframe contaning another dataframe. If you want it to look as your example you should go with multiindex as Wen suggested.
answers question: http://stackoverflow.com/q/46893448
type: Answer

http://stackoverflow.com/q/46863134
type: UnansweredQuestion
tagged with: audio
has body: I'm writing a chat-like app. I want to send data which I got from microphone to another app through UDP and I managed it, but I don't know how to play received audio without saving it to file. Does someone know how to play raw audio? Thanks in advance, Adam
has title: Python - play audio without saving it
type: Question
duplicate of: http://stackoverflow.com/q/43737015
has comment: http://stackoverflow.com/comment/80673904
tagged with: pyaudio
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/43737015
has comment: http://stackoverflow.com/comment/80674443
linked to: http://stackoverflow.com/q/45842385
answer count: 0
has comment: http://stackoverflow.com/comment/80674549

http://stackoverflow.com/q/46843897
tagged with: pygame
score: 14
downvote count: 3
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/75440127
has title: How to draw a circle in PyGame?
has answer: http://stackoverflow.com/a/58263732
has answer: http://stackoverflow.com/a/46843934
tagged with: draw
favorite count: 0
has answer: http://stackoverflow.com/a/67986949
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/65050164
has body: Hi I am having a problem with drawing a circle ERROR: module object has no attribute 'circle'. what am I doing wrong? And also how can I put numbers in circles? For example: (first click is circle with 0 second is circle with 1 and so on) import pygame WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) TEXTCOLOR = ( 0, 0, 0) (width, height) = (200, 300) running = True def main(): global running, screen pygame.init() screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("TUFF") screen.fill(background_color) pygame.display.update() while running: ev = pygame.event.get() for event in ev: if event.type == pygame.MOUSEBUTTONUP: drawCircle() pygame.display.update() if event.type == pygame.QUIT: running = False def getPos(): pos = pygame.mouse.get_pos() return (pos) def drawCircle(): pos=getPos() pygame.draw.circl(screen, BLUE, pos, 20) if __name__ == '__main__': main()
tagged with: python

http://stackoverflow.com/comment/80463420
score: 0
type: Comment
has text: My bad, that is just a typo in my main post. Corrected it.
type: AnswerComment
comment on: http://stackoverflow.com/a/46759001

http://stackoverflow.com/comment/80666016
score: 0
type: Comment
has text: In your code, `reverse` ends up the same as `converter`. I would use `converter=dict(zip(alpha,key))` and `reverse=dict(zip(key,alpha))` (or `reverse={b:a for a, b in converter.items()}`).
type: AnswerComment
comment on: http://stackoverflow.com/a/46859089

http://stackoverflow.com/q/46838428
has comment: http://stackoverflow.com/comment/80674131
has comment: http://stackoverflow.com/comment/80627657
score: 0
tagged with: odoo-10
has body: i have a problem when i've tried to show the average of a field in the tree view. percentage = fields.Float(string='Porcentaje', compute='fill_percentage', store=True,default=False) @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): res = super(Project_Task_Extension, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) if 'percentage' in fields: for line in res: if '__domain' in line: value = 0.0 aux = 0 lines = self.search(line['__domain']) for x in lines: value += x.percentage aux += 1 total = value/aux line['percentage'] = total return res ----in the xml---- &lt;field name="percentage" avg="Average"/&gt; with this code works perfectly but when I tried to filter for example by 'project', the final average is not correct, any suggestions? In this image the average is correct but with this filter the total average is wrong in second the image, the total should be (85.71 + 100 +0)/3=61.90...
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/80784595
has comment: http://stackoverflow.com/comment/80659712
has title: Calculate the average when i filter by groups

line-profiler
tags question: http://stackoverflow.com/q/46893266
type: Tag
tag name: line-profiler

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/46888448
type: Tag
tags question: http://stackoverflow.com/q/46878759
tags question: http://stackoverflow.com/q/46820189
tags question: http://stackoverflow.com/q/46752103

http://stackoverflow.com/comment/80461087
score: 0
has text: A better method: `s = str(n)`, `return s[:len(s)//2] == s[:(len(s) - 1)//2:-1]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46757581

http://stackoverflow.com/comment/80751616
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46884043
has text: try to make a new project then make new app with django, then you can copy your code to it, instead of coping all project.

http://stackoverflow.com/q/46864194
has title: Issue reading an excel sheet in python 3 using XLRD
has answer: http://stackoverflow.com/a/46864195
tagged with: python
upvote count: 1
answer count: 1
type: UnansweredQuestion
has body: I have an issue reading an excel sheet in python 3. I am using the python library "xlrd". And all data is in "text" data type in the excel sheet. Issue: It reads few cell values in a different way than what actually is there in the cell. For example: These are few rows from the excel file named "All_TPN_SearchResults.xlsx" which I am trying to read: 42398 010277 RES,1.15K,MF,RN55D,1% HEAVY &amp; HIGHWAY|GENERAL INSTALL PARTS 2D 42399 010284 TUBING,SHRINKABLE BL CORP,MANUFACTURING|MISCELLANEOUS 42400 010284 TUBING,SHRINKABLE BL CORP,MANUFACTURING|MISCELLANEOUS Where 42398, 42399, 42400 are the row numbers from excel file and rest are actual data. Here is the image of that data sample: https://i.sstatic.net/hB7ER.png The code which I am running is:` import xlrd file_location = "All_TPN_SearchResults.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) print(sheet.cell(42399,0).value) The output of the code: 10284 The expected output of the code: 010284 Can somebody shed some light on what the problem is? Note: It's my first time at Stack exchange and English is not my native language. So, I may not have put my problem in a perfect way, but, I have tried my best to be as descriptive as possible. Thanks in advance!
has comment: http://stackoverflow.com/comment/80675701
has comment: http://stackoverflow.com/comment/80675700
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/80746346
has text: @RobertTownley your code works but now I have the problem that profile model won't generate id auto increment on save (if I add the record directly on the database everything works). I'm using aview that saves profile and user at the same time, maybe I should post another question.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46898601

http://stackoverflow.com/q/46778562
tagged with: python
has title: Exponential moving averages implemented in TensorFlow's Estimator/Experiment APIs?
score: 1
has comment: http://stackoverflow.com/comment/81363537
tagged with: tensorflow
has body: With the new Estimator/Experiments API combination, I struggle to find information concerning implementing exponential moving averages of variables in these models. I cannot seem to find anywhere in the source code to either the estimator or experiments base classes that should specify whether or not the GraphKeys.VARIABLES collection is gathered during the evaluation phase (which I guess should be the requirement for implementing ema, right?). Has anyone experimented with this further?
type: Question
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80788725
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/80682666
score: 0
type: Comment
has text: The template is just a simple HTML page with a form that does the post action. The form has a username and password field and a button.
type: QuestionComment
comment on: http://stackoverflow.com/q/46867659

http://stackoverflow.com/a/46870349
score: 0
type: Answer
has body: Let's say the existing dictionary is X and the list is Y, for i in Y: if i[0] in Y: X[i[0]].sumofdata+=sum(split(i[2])) else: sum_of_data=sum(split(i[2])) X[i[0]]=Person(i[0], i[1],sum_of_data)
answers question: http://stackoverflow.com/q/46870263

http://stackoverflow.com/a/46849373
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: One simple way is to convert the names in both dataframes into a common format so they can be matched.* Let's assume that in df1 names are in the L. Messi format and in df2 names are in the lionel messi format. What would a common format look like? You have several choices, but one option would be all lowercase, with just the first initial followed by a period: l. messi. df1 = pd.DataFrame({'names': ['L. Messi'], 'x': [1]}) df2 = pd.DataFrame({'names': ['lionel messi'], 'y': [2]}) df1.names = df1.names.str.lower() df2.names = df2.names.apply(lambda n: n[0] + '.' + n[n.find(' '):]) df = df1.merge(df2, left_on='names', right_on='names') *Note: This approach is totally dependent on the names being "matchable" in this way. There are plenty of cases that could cause this simple approach to fail. If a team has two members, Abby Wambach and Aaron Wambach, they'll both look like a. wambach. If one dataframe tries to differentiate them by using other initials in their name, like m.a. wambach and a.k. wambach, the naive matching will fail. How you handle this depends on the size your data - maybe you can try match most players this way, and see who gets dropped, and write custom code for them.
answers question: http://stackoverflow.com/q/46848924

http://stackoverflow.com/comment/80669385
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46860908
score: 0
has text: the result can be `'Hello how are you now are you doing now'`. Although a string like this won't come most likely!

http://stackoverflow.com/comment/80470920
score: 0
type: AnswerComment
has text: I can add every other characters except --( ' ). like if the input is `Ravi's` it will show error. How can I fix it? Thanks.
type: Comment
comment on: http://stackoverflow.com/a/46757763

http://stackoverflow.com/a/46925532
type: Answer
upvote count: 6
downvote count: 1
score: 5
answers question: http://stackoverflow.com/q/46796011
has body: A small modification in setup.py specifically applicable for test should do the job import sys import pkg_resources from setuptools import setup, find_packages from setuptools.dist import Distribution install_requires = [ 'redis~=2.8.0', 'example_submodule', ] tests_require = [ 'pytest', ] original_function = None if sys.argv[1] == "test": working_set = pkg_resources.WorkingSet() new_reqs = set() for req in install_requires: try: sets = working_set.resolve(pkg_resources.parse_requirements(req)) except Exception as ex: new_reqs.add(req) install_requires = new_reqs setup( name='example_module', version='0.1.0', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, setup_requires=['pytest-runner'], extras_require={ 'testing': tests_require, }, dependency_links=[ 'git+ssh://git@github.com/vartec/example_repo_setuptools_issue_submodule.git#egg=example_submodule-0.1.0', ] ) See if this is indeed what you were looking for, if not then provide your feedback. Edit-1 If you really don't care about the install_requires in case of test then you can just do if sys.argv[1] == "test": install_requires = []

http://stackoverflow.com/q/46823526
has comment: http://stackoverflow.com/comment/80605960
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/80629796
score: 1
tagged with: image
type: Question
downvote count: 0
tagged with: python
favorite count: 0
answer count: 0
has title: Nan error in custom inception v3 sigmoid cross entropy
type: UnansweredQuestion
has body: I am currently implementing inception v3 for my system. Input will be a batch of images, and output labels of the images. Basically, the model will have one inception module, 2 fully connected layers. Afterwards, the loss is calculated using multi-label sigmoid cross entropy function. Finally because I wanted to train the items on a small set number of pregiven labels, I will multiply the losses with "filter weights", so 90% of the 750 labels will have losses 0, others will have normal losses. def build_inputs(self): """Input prefetching, preprocessing and batching. Outputs: self.images self.tag_captions self.highscore_captions (training and eval only) self.input_mask (training and eval only) """ if self.mode == "inference": # In inference mode, images and inputs are fed via placeholders. image_feed = tf.placeholder(dtype=tf.string, shape=[], name="image_feed") tag_feed = tf.placeholder(dtype=tf.int64, shape=[None], # batch_size name="tag_feed") # Process image and insert batch dimensions. images = tf.expand_dims(self.process_image(image_feed), 0) tag_filters = input_ops.convert_one_vector( tag_feed, self.num_outputs, name="pred_tag_filter_convert_one_hot_vector") # No target sequences or input mask in inference mode. highscore_caption_one_vectors = None else: # Prefetch serialized SequenceExample protos. input_queue = input_ops.prefetch_input_data( self.reader, self.config.input_file_pattern, is_training=self.is_training(), batch_size=self.config.batch_size, values_per_shard=self.config.values_per_input_shard, input_queue_capacity_factor=self.config.input_queue_capacity_factor, num_reader_threads=self.config.num_input_reader_threads) # Image processing and random distortion. Split across multiple threads # with each thread applying a slightly different distortion. assert self.config.num_preprocess_threads % 2 == 0 images_and_captions = [] for thread_id in range(self.config.num_preprocess_threads): serialized_sequence_example = input_queue.dequeue() encoded_image, t…
upvote count: 1
tagged with: machine-learning
tagged with: multilabel-classification

http://stackoverflow.com/comment/80695053
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46873692
has text: Rephrased the question with an example,

tkinter
tags question: http://stackoverflow.com/q/46784260
tags question: http://stackoverflow.com/q/46852845
tags question: http://stackoverflow.com/q/46810931
tags question: http://stackoverflow.com/q/46789053
tags question: http://stackoverflow.com/q/46788776
tags question: http://stackoverflow.com/q/46795018
tags question: http://stackoverflow.com/q/46787429
tags question: http://stackoverflow.com/q/46877571
tags question: http://stackoverflow.com/q/46885016
tags question: http://stackoverflow.com/q/46861236
tags question: http://stackoverflow.com/q/46788852
tags question: http://stackoverflow.com/q/46756163
tags question: http://stackoverflow.com/q/46841438
tags question: http://stackoverflow.com/q/46880678
tags question: http://stackoverflow.com/q/46824604
tags question: http://stackoverflow.com/q/46905542
tags question: http://stackoverflow.com/q/46828579
tags question: http://stackoverflow.com/q/46905049
tags question: http://stackoverflow.com/q/46837373
tags question: http://stackoverflow.com/q/46903529
tags question: http://stackoverflow.com/q/46753024
tag name: tkinter
tags question: http://stackoverflow.com/q/46824725
tags question: http://stackoverflow.com/q/46771673
tags question: http://stackoverflow.com/q/46831855
tags question: http://stackoverflow.com/q/46788495
tags question: http://stackoverflow.com/q/46873773
tags question: http://stackoverflow.com/q/46758698
tags question: http://stackoverflow.com/q/46835490
tags question: http://stackoverflow.com/q/46762655
tags question: http://stackoverflow.com/q/46881316
tags question: http://stackoverflow.com/q/46797770
tags question: http://stackoverflow.com/q/46859814
tags question: http://stackoverflow.com/q/46775342
tags question: http://stackoverflow.com/q/46838196
tags question: http://stackoverflow.com/q/46844090
tags question: http://stackoverflow.com/q/46864525
tags question: http://stackoverflow.com/q/46827196
tags question: http://stackoverflow.com/q/46815433
tags question: http://stackoverflow.com/q/46759090
tags question: http://stackoverflow.com/q/46775912
tags question: http://stackoverflow.com/q/46833607
tags question: http://stackoverflow.com/q/46817290
tags question: http://stackoverflow.com/q/46868526
tags question: http://stackoverflow.com/q/46810011
tags question: http://stackoverflow.com/q/46761013
tags question: http://stackoverflow.com/q/46877986
tags question: http://stackoverflow.com/q/46865046
tags question: http://stackoverflow.com/q/46806464
tags question: http://stackoverflow.com/q/46847870
tags question: http://stackoverflow.com/q/46869971
tags question: http://stackoverflow.com/q/46901324
tags question: http://stackoverflow.com/q/46807489
tags question: http://stackoverflow.com/q/46894762
tags question: http://stackoverflow.com/q/46843814
tags question: http://stackoverflow.com/q/46762645
tags question: http://stackoverflow.com/q/46837752
tags question: http://stackoverflow.com/q/46799450
tags question: http://stackoverflow.com/q/46754615
tags question: http://stackoverflow.com/q/46810693
tags question: http://stackoverflow.com/q/46835474
tags question: http://stackoverflow.com/q/46815337
tags question: http://stackoverflow.com/q/46866677
tags question: http://stackoverflow.com/q/46870447
tags question: http://stackoverflow.com/q/46779121
tags question: http://stackoverflow.com/q/46778491
tags question: http://stackoverflow.com/q/46773499
tags question: http://stackoverflow.com/q/46866387
tags question: http://stackoverflow.com/q/46804669
tags question: http://stackoverflow.com/q/46820061
tags question: http://stackoverflow.com/q/46891555
tags question: http://stackoverflow.com/q/46897671
tags question: http://stackoverflow.com/q/46898992
tags question: http://stackoverflow.com/q/46864799
tags question: http://stackoverflow.com/q/46762061
tags question: http://stackoverflow.com/q/46904839
tags question: http://stackoverflow.com/q/46880566
tags question: http://stackoverflow.com/q/46829450
tags question: http://stackoverflow.com/q/46809771
tags question: http://stackoverflow.com/q/46791895

http://stackoverflow.com/a/46919466
answers question: http://stackoverflow.com/q/46899930
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80811859
score: 2
has comment: http://stackoverflow.com/comment/80816998
upvote count: 2
has body: You can use pydub to slice middle 8 seconds very easily. Details on pydub are here And you can install as pip install pydub I had a wav file of 348 sec duration whose middle 8 seconds are sliced. &gt;&gt;&gt; song.duration_seconds 348.05551020408166 You can also use different file formats such as wav, mp3, m4a, ogg etc. for import (convert to data-segments) and export. Source Code from pydub import AudioSegment from pydub.playback import play song = AudioSegment.from_wav("music.wav") #slice middle eight seconds of audio midpoint = song.duration_seconds // 2 left_four_seconds = (midpoint - 4) * 1000 #pydub workds in milliseconds right_four_seconds = (midpoint + 4) * 1000 #pydub workds in milliseconds eight_sec_slice = song[left_four_seconds:right_four_seconds ] #Play slice play(eight_sec_slice ) #or save to file eight_sec_slice.export("eight_sec_slice.wav", format="wav") As you can see length of middle 8 seconds slice is exactly as desired. &gt;&gt;&gt; eight_sec_slice.duration_seconds 8.0

http://stackoverflow.com/q/46756467
score: 1
accepted answer: http://stackoverflow.com/a/46756490
upvote count: 1
duplicate of: http://stackoverflow.com/q/1535327
type: Question
has title: Control of string rendered when an object is printed?
has body: In some classes, doing str(class) will give you a string, such as 'something'. However, whenever I make a class, it only ever gives &lt;__main__.Test object at 0x0000026FB34D70B8&gt;. How do I make it return a string, such as '0', or even '100'?
tagged with: class
duplicate of: http://stackoverflow.com/q/3691101
answer count: 1
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/46756490
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/46870070
has body: I am trying to draw a narrow filled arc in python--the height is small and the width is very wide. I want it to startX at 250, startY at 550, i want the width to be 245, the height to be 15... and then I am stuck. I have tried a few different things for the start/angle but it doesn't look right: 0/90. I just want it to be a straight horizontal line with a small arc attached to make a semi-circle. Here is an example of what I tried: addArcFilled(pic, 250, 550,245,15, 0, 90, blue)
answer count: 1
tagged with: drawing
favorite count: 0
has title: Drawing a narrow filled arc in python
has comment: http://stackoverflow.com/comment/80694917
tagged with: shapes
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80687683
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46876309
tagged with: jython
score: -1
tagged with: jes
has answer: http://stackoverflow.com/a/46876309

http://stackoverflow.com/comment/80569404
has text: you able to show me how? honestly im struggling on it
type: AnswerComment
comment on: http://stackoverflow.com/a/46811195
score: 0
type: Comment

http://stackoverflow.com/comment/80655060
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the response.
comment on: http://stackoverflow.com/a/46851134

http://stackoverflow.com/a/56410147
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46777919
type: Answer
has body: I had the same issue except I got it on unpiclikg an instane of _gdi.Colour class. Following advice from Unpickling python objects with a changed module path I was saved with: import wx as _wx from wx import _core sys.modules['wx._gdi'] = _core This is a hack of course and you should be better off with a try-except as in (untested) try: from wxPython._gdi import wxBitmapFromImage except ImportError: from wx import BitmapFromImage as wxBitmapFromImage
upvote count: 1

http://stackoverflow.com/comment/118117374
comment on: http://stackoverflow.com/a/46905953
has text: @Patrick like most answers here, this shows how to do the thing that was asked. It can be worked into comprehensive code by the reader. A trivial if statement can check to see if `parsed.password` and `parsed.username` exists and adjust behaviour accordingly.
type: Comment
score: 3
type: AnswerComment

http://stackoverflow.com/q/46903491
has title: Unable to rewrite a CSS to XPATH with multiple classes and skipping elements
has body: I am trying to rewrite a css to XPATH. The css is shortened to: div:nth-child(1) &gt; .lay-selection-button span.bet-button-price I am trying to write an xpath equivalent. //div[1]/button[starts-with(@class=’lay-selection-button span.bet-button-price’)]//span[@class=’bet-button-price’] Any idea why it is not working. It is from this site or an image is here The full css is: #main-wrapper &gt; div &gt; div.scrollable-panes-height-taker &gt; div &gt; div.page-content.nested-scrollable-pane-parent &gt; div &gt; div &gt; div &gt; div.content-page-center-column.coupon-center-column &gt; div &gt; div:nth-child(1) &gt; main &gt; ng-include:nth-child(3) &gt; section.coupon-card.coupon-card-first &gt; div.card-content &gt; bf-coupon-table &gt; div &gt; table &gt; tbody &gt; tr:nth-child(1) &gt; td.coupon-runners &gt; div:nth-child(1) &gt; button.bf-bet-button.lay-button.lay-selection-button &gt; div &gt; span.bet-button-price Shortened to: div:nth-child(1) &gt; button.bf-bet-button.lay-button.lay-selection-button &gt; div &gt; span.bet-button-price And finally what I have at the top: div:nth-child(1) &gt; .lay-selection-button span.bet-button-price
has comment: http://stackoverflow.com/comment/80755277
has comment: http://stackoverflow.com/comment/80755106
tagged with: python
tagged with: css
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80754990
has comment: http://stackoverflow.com/comment/80755431
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/80754643
type: Question
has comment: http://stackoverflow.com/comment/80755362
has answer: http://stackoverflow.com/a/46904434
has comment: http://stackoverflow.com/comment/80754991
accepted answer: http://stackoverflow.com/a/46904434
has comment: http://stackoverflow.com/comment/80755274
has comment: http://stackoverflow.com/comment/80754319
tagged with: jquery
possible better answer: http://stackoverflow.com/a/46904653
has answer: http://stackoverflow.com/a/46904653
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/80755029
has comment: http://stackoverflow.com/comment/80755194
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/80754847

http://stackoverflow.com/comment/80650594
type: QuestionComment
comment on: http://stackoverflow.com/q/46850111
score: 0
has text: @sascha I have linked the csv file to the question so that you can take a look at the entire dataset.
type: Comment

http://stackoverflow.com/q/46817583
answer count: 2
has title: Pycharm debuger disconects
downvote count: 1
has answer: http://stackoverflow.com/a/46818317
tagged with: python-itertools
has answer: http://stackoverflow.com/a/46976373
has comment: http://stackoverflow.com/comment/80583366
possible better answer: http://stackoverflow.com/a/46818317
has body: Hi I have list of four directions and method like directions = ["NORTH", "EAST", "SOUTH", "WEST"] def rotate_left(self): cycled = cycle(self.directions) current = dropwhile(lambda x: x != self.direction, cycled) self.direction = next(current) but somehow after this method my program stops without any exception any idea why? Thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80582572
upvote count: 0
has comment: http://stackoverflow.com/comment/80582700
has comment: http://stackoverflow.com/comment/80582778
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46976373
has comment: http://stackoverflow.com/comment/80582781
tagged with: python
score: -1
tagged with: pycharm
has comment: http://stackoverflow.com/comment/80582756

http://stackoverflow.com/q/46852741
has comment: http://stackoverflow.com/comment/80653446
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80653548
tagged with: python
possible better answer: http://stackoverflow.com/a/46853288
has answer: http://stackoverflow.com/a/46853288
has answer: http://stackoverflow.com/a/46853081
type: AnsweredQuestion
has body: I have the follwoing problem. I have a 3D array like matrix = np.zeros((30,30,100)) where every entry is a coordinate and gets a value. So matrix [0][0][0] is the coordinate x=0,y0,z=0 and has a value of 0. Now i want to store all the values in a csv like this where the first 3 rows are the coordinates and the 4th the corresponding value: Is there a fast way with numpy to do this?
accepted answer: http://stackoverflow.com/a/46853081
type: Question
upvote count: 9
linked to: http://stackoverflow.com/q/46134827
has comment: http://stackoverflow.com/comment/80653230
has comment: http://stackoverflow.com/comment/80653324
score: 9
tagged with: numpy
answer count: 2
tagged with: arrays
downvote count: 0
has title: Python: Storing values in a 3D array to csv
favorite count: 0

http://stackoverflow.com/comment/80632355
comment on: http://stackoverflow.com/q/46842320
score: 1
type: Comment
type: QuestionComment
has text: Have you seen `df.resample`?

http://stackoverflow.com/a/46912490
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46758210
accepted answer of: http://stackoverflow.com/q/46758210
upvote count: 1
score: 1
has body: Use os.system('command &amp; pause') '&amp;' Allows you to string multiple commands within the same window which will execute one after the other. 'Pause' Asks for user input to exit from the terminal.
type: AcceptedAnswer

http://stackoverflow.com/comment/80497662
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46775010
has text: this is still setting every year entry in the result to 0, even if there should be a value there.
type: Comment

http://stackoverflow.com/q/46787093
type: Question
answer count: 2
tagged with: python
has title: Python module import not working
possible better answer: http://stackoverflow.com/a/46787153
accepted answer: http://stackoverflow.com/a/46787154
has answer: http://stackoverflow.com/a/46787153
upvote count: 1
tagged with: python-import
tagged with: getcwd
has body: I am getting an error with the following code: from os import getcwd os.getcwd() Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; os.getcwd() NameError: name 'os' is not defined Anyone know why importing this way is not working?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46787154
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/46841878
tagged with: bash
has body: I have an application that runs multiple Python scripts in order. I can run them in docker-compose as follow: command: &gt; bash -c "python -m module_a &amp;&amp; python -m module_b &amp;&amp; python -m module_c" Now I'm, scheduling the job in Nomad, and added the below command under configuration for Docker driver: command = "/bin/bash" args = ["-c", "python -m module_a", "&amp;&amp;"," "python -m module_b", "&amp;&amp;", "python -m module_c"] But Nomad seems to escape &amp;&amp;, and just runs the first module, and issue exit code 0. Is there any way to run the multiline command similar to docker-compose?
has title: Multiple bash command in Nomad
tagged with: python
has comment: http://stackoverflow.com/comment/95162552
has comment: http://stackoverflow.com/comment/80632361
type: UnansweredQuestion
tagged with: nomad
score: 2
downvote count: 0
type: Question
upvote count: 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46842361

http://stackoverflow.com/comment/80634081
score: 1
comment on: http://stackoverflow.com/a/46843210
type: AnswerComment
has text: Actually, in this case, it doesn't get there for that you need `infer_datetime_format and format is None`. In OP's case it goes to `tslib.array_to_datetime` I guess.
type: Comment

http://stackoverflow.com/a/47648795
has body: I hit this too, reading the thread https://github.com/tensorflow/tensorflow/issues/11621 I think your program is perfectly correct and it's the warning that's wrong :). It was added long before the Datasets API existed, and was well intentioned. (AFAICT the predict() API relies on your input terminating with a tf.errors.OutOfRangeError and before Datasets existed only QueueRunner-based pipelines would terminate that way, so it probably was an error if no queue runners existed.) @xiejw Should we remove this warning, or is there a more cunning way to detect the error condition? Hopefully they will remove the error when it's unnecessary.
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46857382
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46857382
type: Answer
downvote count: 0
score: 3

http://stackoverflow.com/comment/80607735
type: Comment
type: QuestionComment
score: 0
has text: Have you tried: if not all(variable) ?
comment on: http://stackoverflow.com/q/46830120

http://stackoverflow.com/comment/80585805
type: Comment
type: QuestionComment
has text: cake_colour is a list of strings
score: 0
comment on: http://stackoverflow.com/q/46818539

http://stackoverflow.com/a/46846372
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46846305
answers question: http://stackoverflow.com/q/46846305
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80641499
has comment: http://stackoverflow.com/comment/80676236
has body: X_train looks like a list of numpy arrays and tensorflow expects a numpy array, you can simply convert it to a numpy array by: X_train = np.array(X_train) or using numpy.asarray function, which does the exact same thing as above: X_train = np.asarray(X_train) Bear in mind, all your images should have the same dimensions for conversion to work.
type: AcceptedAnswer

http://stackoverflow.com/q/46751618
accepted answer: http://stackoverflow.com/a/46751654
has answer: http://stackoverflow.com/a/46751684
favorite count: 0
has body: I was looking at an INI configuration file implementation here that used this code: # Load the configuration file with open("config.ini") as f: sample_config = f.read() config = ConfigParser.RawConfigParser(allow_no_value=True) config.readfp(io.BytesIO(sample_config)) I want to output something if the configuration file can not be found, but the Python documentation doesn't say anything about an else condition, so I was thinking of using an if...else block here instead: # Load the configuration file if f = open("config.ini"): sample_config = f.read() config = ConfigParser.RawConfigParser(allow_no_value=True) config.readfp(io.BytesIO(sample_config)) else print "Could not open config file" What kind of differences would I see with an if...else block in place of a with block?
tagged with: python
tagged with: with-statement
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46751684
type: Question
has title: What is the difference between with and if in Python2?
tagged with: if-statement
tagged with: python-2.7
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46751654

http://stackoverflow.com/comment/80590495
type: QuestionComment
comment on: http://stackoverflow.com/q/46814197
score: 0
has text: Sorry about typo. It should be this: os.popen('aws s3 cp c:\1.txt s3://bucket') Thank you all for comment. I will try. But anyone know why it doesn't work with apache?
type: Comment

numpy
tags question: http://stackoverflow.com/q/46820146
tags question: http://stackoverflow.com/q/46879273
tags question: http://stackoverflow.com/q/46839075
tags question: http://stackoverflow.com/q/46801175
tags question: http://stackoverflow.com/q/46754677
tags question: http://stackoverflow.com/q/46857052
tags question: http://stackoverflow.com/q/46833593
tags question: http://stackoverflow.com/q/46859304
tags question: http://stackoverflow.com/q/46791372
tags question: http://stackoverflow.com/q/46861741
tags question: http://stackoverflow.com/q/46890371
tags question: http://stackoverflow.com/q/46774106
tags question: http://stackoverflow.com/q/46877236
tags question: http://stackoverflow.com/q/46869116
tags question: http://stackoverflow.com/q/46859839
tags question: http://stackoverflow.com/q/46861241
tags question: http://stackoverflow.com/q/46807443
tags question: http://stackoverflow.com/q/46862148
tags question: http://stackoverflow.com/q/46749573
tags question: http://stackoverflow.com/q/46860970
tags question: http://stackoverflow.com/q/46858945
tags question: http://stackoverflow.com/q/46904999
tags question: http://stackoverflow.com/q/46803155
tags question: http://stackoverflow.com/q/46905380
tags question: http://stackoverflow.com/q/46832108
tags question: http://stackoverflow.com/q/46880944
tags question: http://stackoverflow.com/q/46853354
tags question: http://stackoverflow.com/q/46880748
tags question: http://stackoverflow.com/q/46806935
tags question: http://stackoverflow.com/q/46873354
tags question: http://stackoverflow.com/q/46877710
tags question: http://stackoverflow.com/q/46802409
tags question: http://stackoverflow.com/q/46774792
tags question: http://stackoverflow.com/q/46885031
tags question: http://stackoverflow.com/q/46802122
tags question: http://stackoverflow.com/q/46841269
tags question: http://stackoverflow.com/q/46808533
tags question: http://stackoverflow.com/q/46761745
tags question: http://stackoverflow.com/q/46807403
tags question: http://stackoverflow.com/q/46786847
tags question: http://stackoverflow.com/q/46852741
tags question: http://stackoverflow.com/q/46799741
tags question: http://stackoverflow.com/q/46786311
tags question: http://stackoverflow.com/q/46848095
tags question: http://stackoverflow.com/q/46840637
tags question: http://stackoverflow.com/q/46814724
tags question: http://stackoverflow.com/q/46837983
tags question: http://stackoverflow.com/q/46791664
tags question: http://stackoverflow.com/q/46842173
tags question: http://stackoverflow.com/q/46888976
tags question: http://stackoverflow.com/q/46750017
tags question: http://stackoverflow.com/q/46814037
tags question: http://stackoverflow.com/q/46750647
tags question: http://stackoverflow.com/q/46809027
tags question: http://stackoverflow.com/q/46875194
tags question: http://stackoverflow.com/q/46810714
tags question: http://stackoverflow.com/q/46868855
tags question: http://stackoverflow.com/q/46781282
tags question: http://stackoverflow.com/q/46792252
tags question: http://stackoverflow.com/q/46815698
tags question: http://stackoverflow.com/q/46759801
tags question: http://stackoverflow.com/q/46879936
tags question: http://stackoverflow.com/q/46824478
tags question: http://stackoverflow.com/q/46900957
tags question: http://stackoverflow.com/q/46866295
tags question: http://stackoverflow.com/q/46853819
tags question: http://stackoverflow.com/q/46761892
tags question: http://stackoverflow.com/q/46881360
tags question: http://stackoverflow.com/q/46795836
tags question: http://stackoverflow.com/q/46870621
tags question: http://stackoverflow.com/q/46810539
tags question: http://stackoverflow.com/q/46846193
tags question: http://stackoverflow.com/q/46754144
tags question: http://stackoverflow.com/q/46880930
tags question: http://stackoverflow.com/q/46905471
tags question: http://stackoverflow.com/q/46764246
tags question: http://stackoverflow.com/q/46883245
tags question: http://stackoverflow.com/q/46891502
tags question: http://stackoverflow.com/q/46889408
tags question: http://stackoverflow.com/q/46811709

http://stackoverflow.com/a/46832547
answers question: http://stackoverflow.com/q/46832263
score: 0
has body: If you really want to put the values into a dictionary then, before with open('my.txt') as file:, put country = dict() and inside the loop you can use as if (region != ""): output.append([current_state, region]) if current_state in country: country[current_state].append(region) else: country[current_state] = [] country[current_state].append(region) region = '' For your question the region = '' will solve the issue but to put in dictionary the above code will help, this will make a list for a particular key. Happy coding!
type: Answer

http://stackoverflow.com/comment/80545281
score: 0
type: Comment
has text: Thanks for the heads up. I will be using scrollbars in the very near future
comment on: http://stackoverflow.com/a/46798512
type: AnswerComment

http://stackoverflow.com/comment/80626104
type: Comment
has text: Good. You're on the right track. You should now be seeing other bugs :)
type: AnswerComment
comment on: http://stackoverflow.com/a/46838871
score: 0

http://stackoverflow.com/comment/80446529
type: Comment
type: QuestionComment
has text: `from vpython import *` is *terrible, terrible* practice.
comment on: http://stackoverflow.com/q/46750280
score: 0

http://stackoverflow.com/q/46788125
has body: I have problem getting the static files with nginx. This is the settings of my file in /etc/nginx/sites-available/app location /static/ { alias /home/username/projects/website/static/; } And on my server I checked that my files acctually exist in this directory /home/username/projects/website/static/ I see that files are being called in the wepage from http://xxx.xxx.xx.xx/static/app/images/image.png This file exist on server in directory /home/username/projects/website/static/app/images/image.png My settings file have defines STATIC_ROOT like this STATIC_ROOT = '/home/username/projects/website/static' STATIC_URL = '/static/' I'm really confused. Reading and searching for typos or mismatches. I really need a new set of eyes and pointers.
has comment: http://stackoverflow.com/comment/80522558
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80522517
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80524235
has comment: http://stackoverflow.com/comment/80522475
has comment: http://stackoverflow.com/comment/80533350
type: Question
has comment: http://stackoverflow.com/comment/80522554
has title: Static files not showing with nginx on django server
tagged with: nginx
score: 0
has comment: http://stackoverflow.com/comment/80545776
has comment: http://stackoverflow.com/comment/80528956
answer count: 1
has answer: http://stackoverflow.com/a/52991226
has comment: http://stackoverflow.com/comment/80522594

http://stackoverflow.com/q/46833533
score: 0
tagged with: for-loop
tagged with: genfromtxt
answer count: 1
has answer: http://stackoverflow.com/a/46833740
has title: How to import and write text in a for cycle
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46833740
tagged with: loops
has body: I have the following code: dat11=np.genfromtxt('errors11.txt') dat12=np.genfromtxt('errors12.txt') dat13=np.genfromtxt('errors13.txt') dat22=np.genfromtxt('errors22.txt') dat23=np.genfromtxt('errors23.txt') dat33=np.genfromtxt('errors33.txt') zip(dat11,dat12,dat13,dat22,dat23,dat33) import csv with open('Allerrors.txt', "w+") as output: writer = csv.writer(output, delimiter='\t') writer.writerows(zip(dat11,dat12,dat13,dat22,dat23,dat33)) quit Where each of the 'errorsxy.txt' files consists in a column of numbers. With this program I created the 'Allerrors.txt' file, were all those columns are one next to the others. I need to do this same thing with a for cycle (or any other kind of loop) because I'll actually have much more files and I can't do it by hand. But I don't know how to write these various datxy with a cycle. I tried (for the first part of the code) with: for x in range(1,Nbin+1): for y in range(1,Nbin+1): 'dat'+str(x)+str(y)=np.genfromtxt('errors'+str(x)+str(y)+'.txt') But of course I get the following error: SyntaxError: can't assign to operator I understand why I get this error, but I couldn't find any other way to write it. Also, I have no idea how to write the second part of the code. I'm using Python 2.7 Anyone can help me?
type: Question
tagged with: python-2.7

http://stackoverflow.com/comment/80701476
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46877206
type: Comment
has text: @StefanPochmann: It handles old-style classes, which the questioner may be using.

http://stackoverflow.com/comment/80549799
has text: I get the same error message in the same line. line 64, in <module> coord=tree.findall("XmlForm/[houseNum="+str(houseindex)+"]/"‌​‌​+columns[index]+"/‌​co‌​ord/") ...raise SyntaxError("invalid predicate") SyntaxError: invalid predicate –
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46801323
type: Comment

http://stackoverflow.com/a/46786288
score: 1
downvote count: 0
type: Answer
has body: import glob if not glob.glob("*.txt"): print('No text files Found')
answers question: http://stackoverflow.com/q/46786151
upvote count: 1

global
type: Tag
tags question: http://stackoverflow.com/q/46897950
tag name: global
tags question: http://stackoverflow.com/q/46810559
tags question: http://stackoverflow.com/q/46846475

http://stackoverflow.com/comment/102901723
comment on: http://stackoverflow.com/q/46853692
score: 0
has text: If your only purpose of creating a custom User model is to use email in authentication, i'll suggest you should change the `AUTHENTICATION_BACKENDS` instead of using a custom user model. Please refer to this question if you want email login: https://stackoverflow.com/questions/37332190/django-login-with-email
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46869916
score: 2
accepted answer of: http://stackoverflow.com/q/46869895
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has body: Figured out the problem. The version of geckodriver I was using was not compatible with my version of Firefox (thanks Firefox auto-updates). Installed latest version of geckodriver (0.19) and it works fine now.
type: Answer
answers question: http://stackoverflow.com/q/46869895

http://stackoverflow.com/a/46855772
has body: I fixed this by changing to python 3.
score: 1
answers question: http://stackoverflow.com/q/46855313
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/46842547
has comment: http://stackoverflow.com/comment/95212919
has comment: http://stackoverflow.com/comment/83896399
has comment: http://stackoverflow.com/comment/80632930
has comment: http://stackoverflow.com/comment/99754477
type: Answer
has body: TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion. The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source. If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in: conda create --name tensorflow python=3.5 activate tensorflow pip install tensorflow-gpu Also one more alternative If you are using anaconda distribution, you can do the following to use python 3.5 on the new environnement "tensorflow": conda create --name tensorflow python=3.5 activate tensorflow conda install jupyter conda install scipy pip install tensorflow or pip install tensorflow-gpu It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.
score: 3
answers question: http://stackoverflow.com/q/46842398
upvote count: 3
has comment: http://stackoverflow.com/comment/80632893
has comment: http://stackoverflow.com/comment/85262453
downvote count: 0
has comment: http://stackoverflow.com/comment/99755038
has comment: http://stackoverflow.com/comment/99743265
has comment: http://stackoverflow.com/comment/99754144

http://stackoverflow.com/q/46891494
score: 3
has title: Error when connecting to Oracle from Python using cx_Oracle
upvote count: 3
type: Question
has body: Python 3.6.3 Oracle InstantClient Basic 12.2 cx_Oracle 6 Installed per instructions I'm attempting to connect to an Oracle db using python 3.6.3 and the above mentioned cx_oracle installation. It's definitely finding the client and the mentioned vc redistributable as far as I can tell, because I had different errors when I first tried to run it. Now I'm getting: cx_Oracle.DatabaseError: DPI-1050: Oracle Client library must be at version 11.2 or higher Now I'm not really an Oracle guy, so maybe I'm misreading or misunderstanding something. InstantClient 12.2 is the required client, correct? And according to the docs cx_oracle 6 is compatible with 11.2, 12.1 and 12.2, so where did I go wrong? edit: ORACLE_HOME was not set, so I added it, pointed at the InstantClient installation, but it made no difference. cx_oracle.clientversion() throws the same error as mentioned above. For clarity: This is Windows Server 2012 R2
has comment: http://stackoverflow.com/comment/80732385
has answer: http://stackoverflow.com/a/49367151
has comment: http://stackoverflow.com/comment/86677783
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86640189
has comment: http://stackoverflow.com/comment/80733068
type: UnansweredQuestion
tagged with: oracle-database
tagged with: python

http://stackoverflow.com/comment/80492295
type: Comment
has text: Thanks @PeterGibson! Break is what I was looking for, make sense. I wonder why my question was voted down, the thread they claimed answered my question doesn't answer my question...
comment on: http://stackoverflow.com/a/46761731
score: 0
type: AnswerComment

http://stackoverflow.com/a/46772536
accepted answer of: http://stackoverflow.com/q/46772462
has comment: http://stackoverflow.com/comment/80491694
has comment: http://stackoverflow.com/comment/80492871
has comment: http://stackoverflow.com/comment/80491625
has comment: http://stackoverflow.com/comment/80492862
has comment: http://stackoverflow.com/comment/80491736
has body: You can use a += (listnum[0]) as you can see in the following example: a = '' idx = 0 for i in y: listbyte = subprocess.check_output('python foo.py ' + path + str(y[idx]), shell=True).rstrip() idx += 1 listnum = listbyte.decode() a += (listnum[0]) u.append(listnum) And then a will be a string which contains "12345" &gt;&gt;&gt; print(a) 12345 In case you want a to be an integer at the end, and not a string, you can parse it using int(a)
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80490946
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46772462
score: 1
has comment: http://stackoverflow.com/comment/80491011

http://stackoverflow.com/comment/80498914
has text: How are you starting Jupyter? Is the path `C:\Users\PC\Documents` constant or does it differ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46775023

http://stackoverflow.com/q/46825656
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/46828631
has title: Python C++ API: How to retrieve lineno attribute of NameError
linked to: http://stackoverflow.com/q/16733425
has comment: http://stackoverflow.com/comment/80601710
has comment: http://stackoverflow.com/comment/80599139
tagged with: api
has comment: http://stackoverflow.com/comment/80600734
upvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/1796510
has comment: http://stackoverflow.com/comment/80601545
has comment: http://stackoverflow.com/comment/80604757
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80601460
has comment: http://stackoverflow.com/comment/80602866
has comment: http://stackoverflow.com/comment/80599431
score: -1
tagged with: c++
has comment: http://stackoverflow.com/comment/80602017
has comment: http://stackoverflow.com/comment/80600647
has comment: http://stackoverflow.com/comment/80600850
downvote count: 1
has comment: http://stackoverflow.com/comment/80601583
type: Question
has comment: http://stackoverflow.com/comment/80601537
has body: I am using the python API for C/C++ and I would like to retrieve the line number in case of a NameError. I followed the instructions found within the question bellow: How to retrieve filename and lineno attribute of SyntaxError and I wrote the following code: PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL; PyObject *comp = NULL, *eval = NULL; char code[] = {"A=undef_var"}; comp = Py_CompileString(code, "", Py_file_input); if (comp) { eval = PyEval_EvalCode(comp, PyEval_GetBuiltins(), NULL); } if (!comp || !eval) { PyErr_PrintEx(1); // inside this function the PyErr_Fetch(ptype, pvalue, ptraceback) is called // retrieve the information gained from PyErr_Fetch() called inside PyErr_PrintEx(1) pvalue = PySys_GetObject("last_value"); ptype = PySys_GetObject("last_type"); ptraceback = PySys_GetObject("last_traceback"); PyErr_NormalizeException(ptype, pvalue, ptraceback); PyObject* line_no = PyObject_GetAttrString(pvalue,"lineno"); if (line_no) { PyObject* line_no_str = PyObject_Str(line_no); PyObject* line_no_unicode = PyUnicode_AsEncodedString(line_no_str,"utf-8", "Error"); char *actual_line_no = PyBytes_AsString(line_no_unicode); } } The code above returns the correct line number, in case the python code contains a SyntaxError (e.g. for a simple python code like "A="), but in case of a NameError the line number is not set correctly to the pvalue object (e.g. for the python code: "A=undefined_var"). Any ideas how can I solve this problem?
has comment: http://stackoverflow.com/comment/80602667
linked to: http://stackoverflow.com/q/1418015

http://stackoverflow.com/q/46872011
has body: Given the following DataFrame: Category Area Country Code Function Last Name LanID Spend1 Spend2 Spend3 Spend4 Spend5 0 Bisc EE RU02,UA02 Mk Smith df3432 1.0 NaN NaN NaN NaN 1 Bisc EE RU02 Mk Bibs fdss34 1.0 NaN NaN NaN NaN 2 Bisc EE UA02,EURASIA Mk Crow fdsdr43 1.0 NaN NaN NaN NaN 3 Bisc WE FR31 Mk Ellis fdssdf3 1.0 NaN NaN NaN NaN 4 Bisc WE BE32,NL31 Mk Mower TOZ1720 1.0 NaN NaN NaN NaN 5 Bisc WE FR31,BE32,NL31 LKU Elan SKY8851 1.0 1.0 1.0 1.0 1.0 6 Bisc SE IT31 Mk Bobret 3dfsfg 1.0 NaN NaN NaN NaN 7 Bisc SE GR31 Mk Concept MOSGX009 1.0 NaN NaN NaN NaN 8 Bisc SE RU02,IT31,GR31,PT31,ES31 LKU Solar MSS5723 1.0 1.0 1.0 1.0 1.0 9 Bisc SE IT31,GR31,PT31,ES31 Mk Brix fdgd22 NaN 1.0 NaN NaN NaN 10 Choc CE RU02,CZ31,SK31,PL31,LT31 Fin Ocoser 43233d NaN 1.0 NaN NaN NaN 11 Choc CE DE31,AT31,HU31,CH31 Fin Smuth 4rewf NaN 1.0 NaN NaN NaN 12 Choc CE BG31,RO31,EMA Fin Momocs hgghg2 NaN 1.0 NaN NaN NaN 13 Choc WE FR31,BE32,NL31 Fin Bruntly ffdd32 NaN NaN NaN NaN 1.0 14 Choc WE FR31,BE32,NL31 Mk Ofer BROGX011 NaN 1.0 1.0 NaN NaN 15 Choc WE FR31,BE32,NL31 Mk Hem NZJ3189 NaN NaN NaN 1.0 1.0 16 G&amp;C NE UA02,SE31 Mk Cre ORY9499 1.0 NaN NaN NaN NaN 17 G&amp;C NE NO31 Mk Qlyo XVM7639 1.0 NaN NaN NaN NaN 18 G&amp;C NE GB31,NO31,SE31,IE31,FI31 Mk Omny LOX1512 NaN 1.0 1.0 NaN NaN I would like to get it exported into a nested Dict with the below structure: {RU02: {Bisc: {EE: {Mkt: {Spend1: {df3432: Smith} {fdss34: Bibs} {Bisc: {SE: {LKU: {Spend1: {MSS5723: Solar} {Spend2: {MSS5723: Solar} {Spend3: {MSS5723: Solar} {Spend4: {MSS5723: Solar} {Spend5: {MSS5723: Solar} {Choc: {CE: {Fin: {Spend2: {43233d: Ocoser} ..... {UA02: {Bisc: {EE: {Mkt: {Spend1: {df3432: Smith} {ffdsdr43: Crow} {G&amp;C: {NE: {Mkt: {Spend1: {ORY9499: Cre} ..... So essentially, in this Dict I'm trying to track for each CountryCode, what is the list of LastNames+LandIDs, per Spend category (Spend1,Spend2, etc.) and their attributes (Function, Category, Area). The DataFrame is not very large (less than 200rows), but it c…
type: Question
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/19798112
score: 1
has comment: http://stackoverflow.com/comment/80693999
has answer: http://stackoverflow.com/a/46875201
tagged with: pandas
has comment: http://stackoverflow.com/comment/80691309
tagged with: python
tagged with: dictionary
has title: reshaping pandas DataFrame for export in a nested dict
favorite count: 0
linked to: http://stackoverflow.com/q/27263805
upvote count: 1
accepted answer: http://stackoverflow.com/a/46875201
type: AnsweredQuestion
tagged with: dataframe

http://stackoverflow.com/comment/80567381
type: Comment
comment on: http://stackoverflow.com/q/46810058
has text: have a look at this answer https://stackoverflow.com/a/19138327/5476782 if you don't need join(), remove it from your code, it blocks the thread in execution
score: 0
type: QuestionComment

http://stackoverflow.com/a/46849617
has body: The problem is, I suppose, a typo in your Javascript code: var canvas = d3.select("body") .append("svg") .attr("width",500) .attr("width",300); As you can see, you didn't set the height property; instead you set twice the width property. Check this fiddle for the complete code.
has comment: http://stackoverflow.com/comment/80646728
score: 1
has comment: http://stackoverflow.com/comment/80646740
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46848562
answers question: http://stackoverflow.com/q/46848562
type: Answer
upvote count: 1

http://stackoverflow.com/comment/80686574
type: QuestionComment
comment on: http://stackoverflow.com/q/46869642
type: Comment
score: 0
has text: When you get it right it's fun - thanks!

http://stackoverflow.com/comment/80568377
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46806540
has text: Are you using ImageDataGenerator with augmentation? If so, random transformations will be applied to your validation set, so variance on accuracy is expected.

http://stackoverflow.com/q/46850902
upvote count: 7
linked to: http://stackoverflow.com/q/37161560
tagged with: python
has comment: http://stackoverflow.com/comment/80914127
has title: Failing to open an Excel file with Python
has comment: http://stackoverflow.com/comment/80652460
has answer: http://stackoverflow.com/a/46851404
has answer: http://stackoverflow.com/a/47000017
has answer: http://stackoverflow.com/a/46915624
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80649635
has answer: http://stackoverflow.com/a/46965133
possible better answer: http://stackoverflow.com/a/47000017
has comment: http://stackoverflow.com/comment/80650239
has answer: http://stackoverflow.com/a/46986940
accepted answer: http://stackoverflow.com/a/46986940
has comment: http://stackoverflow.com/comment/80652924
has comment: http://stackoverflow.com/comment/80652336
has comment: http://stackoverflow.com/comment/80914152
has comment: http://stackoverflow.com/comment/80651469
has answer: http://stackoverflow.com/a/46896278
type: Question
has body: I'm on a Debian GNU/Linux computer, working with Python 2.7.9. As a part of my job, I have been making python scripts that read inputs in various formats (e.g. Excel, Csv, Txt) and parse the information to more standarized files. It's not my first time opening or working with Excel files. There's a particular file which is giving me problems, I just can't open it. When I tried with xlrd (version 0.9.3), it gave me the following error: xlrd.open_workbook('sample.xls') XLRDError: Unsupported format, or corrupt file: BOF not workbook/worksheet: op=0x0009 vers=0x0002 strm=0x000a build=0 year=0 -> BIFF21 I tried to investigate the matter on my own, found a couple of answers in StackOverflow but I couldn't open it anyway. This particular answer I found may be the problem (the second explanation), but it doesn't include a workaround: https://stackoverflow.com/a/16518707/4345659 A tool that could conert the file to csv/txt would also solve the problem. I already tried with: xlrd openpyxl xlsx2csv (the shell tool) A sample file is available here: https://ufile.io/r4m6j As a side note, I can open it with LibreOffice Calc and MS Excel, so I could eventually change it to csv that way. The thing is, I need to do it all with a python script. Thanks in advance!
has comment: http://stackoverflow.com/comment/80652814
downvote count: 2
score: 5
has answer: http://stackoverflow.com/a/46910884
has answer: http://stackoverflow.com/a/46898608
has comment: http://stackoverflow.com/comment/80653012
favorite count: 0
has comment: http://stackoverflow.com/comment/80917480
has comment: http://stackoverflow.com/comment/80744622
tagged with: python-2.7
answer count: 9
has answer: http://stackoverflow.com/a/47003570
tagged with: xlrd
has comment: http://stackoverflow.com/comment/80746887
linked to: http://stackoverflow.com/q/16504975

http://stackoverflow.com/comment/80638987
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46844284
has text: Yes, that fixes the problem. I never inended to use the checkbox value explicitly and only relied on a callback, so I thought that creating one is not necessary. More fool me for not paying enough attention to the docs.

http://stackoverflow.com/comment/80575291
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46813921
has text: Possible duplicate of [make several operations in a dataframe at once](https://stackoverflow.com/questions/46812223/make-several-operations-in-a-dataframe-at-once)
type: Comment

http://stackoverflow.com/comment/80459444
type: Comment
type: QuestionComment
score: 1
has text: You forgot to indent the `print`.
comment on: http://stackoverflow.com/q/46757079

http://stackoverflow.com/comment/128020417
type: Comment
comment on: http://stackoverflow.com/a/72467833
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80667887
score: 2
comment on: http://stackoverflow.com/q/46860145
type: QuestionComment
has text: "leads to error messages" Did you feel like sharing them with us?
type: Comment

http://stackoverflow.com/a/46762499
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46762411
type: Answer
answers question: http://stackoverflow.com/q/46762411
downvote count: 0
score: 1
has body: Anaconda uses conda to manage virtual environments. You can simply create a new environment by conda create -n env_name [python=x[.x]]. And activate a environment by activate env_name, deactivate a environment by deactivate.
upvote count: 1

http://stackoverflow.com/a/46892576
type: Answer
answers question: http://stackoverflow.com/q/46892392
accepted answer of: http://stackoverflow.com/q/46892392
type: AcceptedAnswer
has body: Easily: df.groupby('user_id').agg({'product_id': ['count', pd.Series.nunique]}) Pandas has docs for helping with the translation from SQL to Pandas: https://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html
has comment: http://stackoverflow.com/comment/80751383
score: 0

http://stackoverflow.com/a/46841777
accepted answer of: http://stackoverflow.com/q/46841316
answers question: http://stackoverflow.com/q/46841316
has body: I would suggest a simplified "architecture". Your functions to get the user and computer choices should return values that can be compared. import random CHOICES = ('rock', 'paper', 'scissors') def get_user_choice(): choice = input('Rock, paper, or scissors? ') choice = choice.lower().strip() if choice not in CHOICES: print('Please select one of rock, paper, or scissors') choice = get_user_choice() return choice def get_computer_choice(): return random.choice(CHOICES) def play_round(): user_choice = get_user_choice() computer_choice = get_computer_choice() print('You selected', user_choice) print('Computer selected', computer_choice) # Compare choices here # Return value indicating win, loss, or draw def play(): wins = 0 losses = 0 draws = 0 result = play_round() # Update wins, losses, or draws according to the result # Prompt user to play again or quit return wins, losses, draws if __name__ == '__main__': wins, losses, draws = play() # Report wins, losses, and draws
score: 0
type: AcceptedAnswer
type: Answer

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

http://stackoverflow.com/q/46770574
has comment: http://stackoverflow.com/comment/80511085
tagged with: python
duplicate of: http://stackoverflow.com/q/34316346
tagged with: list
score: 0
has title: Python: System getting stuck during list generation via product function, without explicit parallel processing
has body: I'm using the list function with the product function to create a list whose elements are made of m digits (10) out of n types(0 to 7), which should yield all possible patterns. Using n=8, I first use smaller numbers for m to get the process going, it works fine till m=8. My program is as follows import time from itertools import product start_time = time.time() repeatnum=8 patternnum=8 list1=list(product(range(0,patternnum), repeat=repeatnum)) print(len(list1)) print("Time taken for list is --- %s seconds ---" % (time.time() - start_time)) At n=8(repeatnum), the time taken is about 3 seconds. As I use n=9, not only the python program (within IDLE/Spyder/Windows CLI), but the whole system starts behaving sluggishly, which has not happened before. (Usually only the python program takes time, but the other programs on the computer run normally.) I don't get any error messages till I stop the execution, neither does the processor heat up as one would expect. Just that the system shows choppy and time delayed behaviour for other functions As a result, I have to end the python program execution (which is also not straightforward) and the general usability of the system also improves. What could be causing this behaviour? Is there some auto-parallelization happening automatically? Or I am just running out of RAM memory? System Info: System Manufacturer HP System Model HP ProBook 640 G2 System Type x64-based PC Processor Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz, 2401 Mhz, 2 Core(s), 4 Logical Processor(s), 8 GB RAM
linked to: http://stackoverflow.com/q/45586863
has comment: http://stackoverflow.com/comment/80486962
type: UnansweredQuestion
tagged with: memory
answer count: 0
linked to: http://stackoverflow.com/q/34316346
type: Question

python-2.7
tags question: http://stackoverflow.com/q/46891862
tags question: http://stackoverflow.com/q/46818732
tags question: http://stackoverflow.com/q/46843833
tags question: http://stackoverflow.com/q/46751438
tags question: http://stackoverflow.com/q/46885741
tags question: http://stackoverflow.com/q/46877845
tags question: http://stackoverflow.com/q/46843740
tags question: http://stackoverflow.com/q/46769942
tags question: http://stackoverflow.com/q/46886704
tags question: http://stackoverflow.com/q/46886903
tags question: http://stackoverflow.com/q/46808404
tags question: http://stackoverflow.com/q/46762791
tags question: http://stackoverflow.com/q/46843183
tags question: http://stackoverflow.com/q/46834214
tags question: http://stackoverflow.com/q/46904444
tags question: http://stackoverflow.com/q/46778621
tags question: http://stackoverflow.com/q/46851216
tags question: http://stackoverflow.com/q/46874039
tags question: http://stackoverflow.com/q/46850850
tags question: http://stackoverflow.com/q/46866053
tags question: http://stackoverflow.com/q/46887098
tags question: http://stackoverflow.com/q/46856584
tags question: http://stackoverflow.com/q/46821912
tags question: http://stackoverflow.com/q/46762351
tags question: http://stackoverflow.com/q/46850902
tags question: http://stackoverflow.com/q/46819308
tags question: http://stackoverflow.com/q/46844569
tags question: http://stackoverflow.com/q/46878270
tags question: http://stackoverflow.com/q/46795816
tags question: http://stackoverflow.com/q/46802586
tags question: http://stackoverflow.com/q/46788179
tags question: http://stackoverflow.com/q/46887497
tags question: http://stackoverflow.com/q/46897717
tags question: http://stackoverflow.com/q/46854846
tags question: http://stackoverflow.com/q/46899021
tags question: http://stackoverflow.com/q/46805610
tags question: http://stackoverflow.com/q/46890703
tags question: http://stackoverflow.com/q/46797973
tags question: http://stackoverflow.com/q/46751618
tags question: http://stackoverflow.com/q/46792348
tags question: http://stackoverflow.com/q/46862074
tags question: http://stackoverflow.com/q/46824205
tags question: http://stackoverflow.com/q/46892078
tags question: http://stackoverflow.com/q/46853852
tags question: http://stackoverflow.com/q/46823571
tags question: http://stackoverflow.com/q/46800479
tags question: http://stackoverflow.com/q/46807876
tags question: http://stackoverflow.com/q/46901521
tags question: http://stackoverflow.com/q/46752888
tags question: http://stackoverflow.com/q/46808219
tags question: http://stackoverflow.com/q/46823861
tags question: http://stackoverflow.com/q/46824087
tags question: http://stackoverflow.com/q/46836330
tags question: http://stackoverflow.com/q/46894503
tags question: http://stackoverflow.com/q/46781050
tags question: http://stackoverflow.com/q/46896986
tags question: http://stackoverflow.com/q/46792252
tags question: http://stackoverflow.com/q/46857728
tags question: http://stackoverflow.com/q/46750552
tags question: http://stackoverflow.com/q/46788883
tags question: http://stackoverflow.com/q/46844281
tags question: http://stackoverflow.com/q/46849467
tags question: http://stackoverflow.com/q/46801867
tags question: http://stackoverflow.com/q/46795836
tags question: http://stackoverflow.com/q/46819982
tags question: http://stackoverflow.com/q/46751905
tags question: http://stackoverflow.com/q/46887870
tags question: http://stackoverflow.com/q/46849507
tags question: http://stackoverflow.com/q/46857851
tags question: http://stackoverflow.com/q/46840770
tags question: http://stackoverflow.com/q/46762881
tags question: http://stackoverflow.com/q/46829975
tags question: http://stackoverflow.com/q/46793486
tags question: http://stackoverflow.com/q/46891026
tags question: http://stackoverflow.com/q/46836287
tags question: http://stackoverflow.com/q/46886937
tags question: http://stackoverflow.com/q/46832451
tags question: http://stackoverflow.com/q/46838913
tags question: http://stackoverflow.com/q/46859006
tags question: http://stackoverflow.com/q/46780221

http://stackoverflow.com/q/46858016
has answer: http://stackoverflow.com/a/46863648
upvote count: 16
has title: Keras Custom loss function to pass arguments other than y_true and y_pred
linked to: http://stackoverflow.com/q/62393032
tagged with: keras
has body: I am writing a keras custom loss function where in I want to pass to this function the following: y_true, y_pred (these two will be passed automatically anyway), weights of a layer inside the model, and a constant. Something like below: def Custom_loss(y_true, y_pred, layer_weights, val = 0.01): loss = mse(y_true, y_pred) loss += K.sum(val, K.abs(K.sum(K.square(layer_weights), axis=1))) return loss But the above implementation gives me error. How can I achieve this in keras ?
favorite count: 0
linked to: http://stackoverflow.com/q/50706160
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54177997
downvote count: 0
has comment: http://stackoverflow.com/comment/117610672
score: 16
tagged with: tensorflow
type: Question
answer count: 2

http://stackoverflow.com/comment/80788143
type: Comment
comment on: http://stackoverflow.com/a/46919545
has text: Also tried tracing. Doesn't return a full log of the queries executed by `BatchStatement`
score: 0
type: AnswerComment

http://stackoverflow.com/a/46889102
accepted answer of: http://stackoverflow.com/q/46888107
score: 0
has body: I think you need to have the start_urls like below start_urls = [ 'https://www.dawnnews.tv', 'https://www.dawnnews.tv/latest-news', 'https://www.dawnnews.tv/news', 'https://www.dawnnews.tv/tech' ] You dont have the urls separated by commas in the code mentioned above so it is take only two urls the first one and the other three are appended and used as one url please put commas after each url as mentioned above Next story_body = response.css('div.story__content') means in the page given by the url there should be a div element with class=story__content which i think is missing in the mentioned urls.Just having a quick look at the html of https://www.dawnnews.tv it seems it has something like story__excerpt as div class not sure if this is what you require.Anyway you need to check the html of these pages and get the correct contents. What you can do to debug this is to use print statements and print out story_body,story_paragraphs_text and check whether you are getting any output for these.Hope this will be helpful for you to do the required debugging. 017-10-23 22:11:22 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.dawnnews.tv&gt; (referer: None) https://www.dawnnews.tv 2017-10-23 22:11:23 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.dawnnews.tv/news&gt; (referer: None) https://www.dawnnews.tv/news news.txt [] 2017-10-23 22:11:23 [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://www.dawnnews.tv/tech&gt; (referer: None) https://www.dawnnews.tv/tech tech.txt [&lt;Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' story__excerpt ')]" data='&lt;div class="story__excerpt "&gt;فیس '&gt;, &lt;Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' story__excerpt ')]" data='&lt;div class="story__excerpt "&gt;یوٹی'&gt;, &lt;Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' story_…
type: Answer
has comment: http://stackoverflow.com/comment/80743144
answers question: http://stackoverflow.com/q/46888107
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80735915
has comment: http://stackoverflow.com/comment/80733185

http://stackoverflow.com/q/46801543
has title: (Turtle/Python3) How to make a while loop that's independently working forever in turtle?
answer count: 1
has body: So what I want to do, is display: The distance of Alex from Alice is: (distance I calculated already) I need this to be displayed on top of the screen.. forever,refreshing, kind of like PING statistics in games shows on top there.. I assume it would be a while loop? I need the rest of the program running while this is constantly displaying and refreshing..
score: 0
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/80551146
tagged with: python-3.x
tagged with: turtle-graphics
tagged with: infinite
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/46804289

http://stackoverflow.com/a/46775464
score: 2
upvote count: 2
has body: I have found the solution here. I just had to use Context. So work code looks like this: Context = autoclass('android.content.Context') notification_service = PythonActivity.mActivity.getSystemService(Context.NOTIFICATION_SERVICE) I hope this helps those who encounter the same problem.
accepted answer of: http://stackoverflow.com/q/46760144
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46760144
downvote count: 0
type: Answer

http://stackoverflow.com/q/46751152
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/80448408
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46751316
has comment: http://stackoverflow.com/comment/80448324
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/46751316
has answer: http://stackoverflow.com/a/46751292
score: 0
has comment: http://stackoverflow.com/comment/80448300
accepted answer: http://stackoverflow.com/a/46751292
tagged with: python
tagged with: regex
tagged with: delimiter
favorite count: 0
has title: python multiline regex findall
has body: I'm trying to find multiple matches across multiple lines of text with a delimiter to stop the search using regex in python... my query works well for what I'm trying to accomplish if what I need is all on the same line: re.findall('([a-zA-Z]{3}\d-[aAeE][rRsS]\d.*), output) the problem is, sometimes the additional data I'm trying to capture doesn't fit on the same line and goes to the next... is there a way to set the pattern match to stop if it either finds the next match or hits a delimiter (= in this case)? Simplified example with two matches below, and I need the ability to capture both... Example Port Id Description 3/2/4 Part of aggregate interface lag-4. Next device in path sea1-as2 lag-4, sea1-as2 3/1/2.

http://stackoverflow.com/q/46899816
has body: So I am following a Django tutorial and I have reached the stage where I add my own URL patterns to the urls.py file. from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url((r'^webapp/', include('webapp.urls'))), url(r'^admin/', admin.site.urls), ] the problem is that when I run the server Django doesnt even search for the pattern. I'm not sure what I'm doing wrong here webapp.urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ]
has comment: http://stackoverflow.com/comment/80747280
has comment: http://stackoverflow.com/comment/80747298
has title: Django URL patterns not being read
has comment: http://stackoverflow.com/comment/80746785
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80747171
has answer: http://stackoverflow.com/a/46900775
tagged with: django
has comment: http://stackoverflow.com/comment/80746772
type: Question
has comment: http://stackoverflow.com/comment/80747226
has comment: http://stackoverflow.com/comment/80747937
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80747214
has comment: http://stackoverflow.com/comment/80746870
has answer: http://stackoverflow.com/a/46900910
has comment: http://stackoverflow.com/comment/80746826

http://stackoverflow.com/comment/80613082
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46832579
has text: When I do that, I get this output; 36.8 Int64Index([16978], dtype='int64')
type: Comment

http://stackoverflow.com/comment/80643771
score: 0
type: Comment
has text: thank you for your help but I still get errors using your method. >>> import requests as rq Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> import requests as rq ModuleNotFoundError: No module named 'requests' >>> response = rq.get("https://google.com", veryify=False) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> response = rq.get("https://google.com", veryify=False) NameError: name 'rq' is not defined
type: AnswerComment
comment on: http://stackoverflow.com/a/46848175

http://stackoverflow.com/a/68570234
has body: What you want to do can be achieved by updating your limits within on_ylims_change. However, we need to make sure not to end up with an infinite callback loop. One way to do this is to disconnect the callback while we are updating xlim and ylim, and then reconnecting it immediately afterward. import matplotlib.pyplot as plt # # Some toy data x_seq = [x / 100.0 for x in range(1, 100)] y_seq = [x**2 for x in x_seq] # # Scatter plot fig, ax = plt.subplots(1, 1) ax.scatter(x_seq, y_seq) # # Declare and register callbacks def on_lims_change(event_ax): cid_list = list(event_ax.callbacks.callbacks['ylim_changed'].keys()) for cid in cid_list: event_ax.callbacks.disconnect(cid) a = ax.get_xlim() span = a[1]-a[0] event_ax.set_xlim(-span/2, span/2) a = ax.get_ylim() span = a[1]-a[0] event_ax.set_ylim(-span/2, span/2) event_ax.callbacks.connect('ylim_changed', on_lims_change) ax.callbacks.connect('ylim_changed', on_lims_change) # # Show plt.show() Generally we only want to connect to the ylim_changed event since this will be called after xlim_changed for a standard zoom event. This way we have the final zoom results before starting to make changes.
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46855458
has comment: http://stackoverflow.com/comment/121182849

http://stackoverflow.com/a/46787309
type: Answer
has body: The numbers are being stored as strings which is causing your sort to see all the 1's as the first rather than their integer value
answers question: http://stackoverflow.com/q/46787230
score: 0

http://stackoverflow.com/q/46873667
upvote count: 1
answer count: 1
favorite count: 0
has title: Imbricated for selection in dict (Python)
has comment: http://stackoverflow.com/comment/80694502
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46873759
accepted answer: http://stackoverflow.com/a/46873759
tagged with: selection
type: Question
has body: Coming from MATLAB, I am really new to Python and i am still trying to understand its syntax. I succeeded in doing what I want but I am sure there is a proper way to do it in only one line... serialsToFind = ['43788273-1', '45788259-2', '87788202'] dataSelection = [] from numpy import linspace serials = linspace(0,len(data)-1,len(data), dtype='int') for serialToFind in serialsToFind: for serial in serials: if data[serial]['SerialNumber'][:8] == serialToFind[:8]: dataSelection.append(data[serial]) Thanks a lot, Max

http://stackoverflow.com/comment/80478598
comment on: http://stackoverflow.com/q/46765766
has text: How could I implement it with a join?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80588813
type: Comment
score: 1
has text: It's generally a good idea to have files open as little as possible, and to use the `with` syntax. You can pass the names of the files to the function, open them in the function, read them, and then immediately close them.
comment on: http://stackoverflow.com/q/46820292
type: QuestionComment

http://stackoverflow.com/q/46813827
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80615263
tagged with: bignum
has comment: http://stackoverflow.com/comment/80640975
has answer: http://stackoverflow.com/a/46824380
tagged with: python
accepted answer: http://stackoverflow.com/a/46824380
has title: swig c++ to python with openssl/bn.h
tagged with: c++
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80600514
type: Question
tagged with: swig
has comment: http://stackoverflow.com/comment/80591052
has comment: http://stackoverflow.com/comment/80591079
tagged with: openssl
upvote count: 3
has comment: http://stackoverflow.com/comment/80721398
linked to: http://stackoverflow.com/q/46846754
has body: I'm trying to create a *.so file for further use in Python using SWIG. In particular I'm using some libraries from openssl (such opensll/bn.h). But somehow it return error ImportError: [...]/auxchash.so: undefined symbol: BN_bn2hex. I have the file.cpp, auxchash.cpp: #include auxchash.h int keygen(int bits, char *p, char *q, char *g, char *hk, char *tk){ BN_CTX *ctx = BN_CTX_new(); BIGNUM *bn_p = BN_new(); BIGNUM *bn_q = BN_new(); BIGNUM *bn_g = BN_new(); BIGNUM *bn_hk = BN_new(); BIGNUM *bn_tk = BN_new(); BIGNUM *bn_two = BN_new(); BN_CTX_init(ctx); BN_dec2bn(&amp;bn_two, "2"); //initialize a BIGNUM with value 2 //on non-unix platform needs to initialize the PRNG with randomness //or BN_generate_prime_ex may fail //computing the safe prime p and q = (p-1)/2 BN_generate_prime_ex(bn_p, bits, 1, NULL, NULL, NULL); BN_sub(bn_q, bn_p, BN_value_one()); BN_div(bn_q, NULL, bn_q, bn_two, ctx); //finding the generator g (for the group QR_p) BN_rand_range(bn_g, bn_p); BN_mod_exp(bn_g, bn_g, bn_two, bn_p, ctx); //choosing the keys hk and tk BN_rand_range(bn_tk, bn_q); BN_mod_exp(bn_hk, bn_g, bn_tk, bn_p, ctx); //converting from BIGNUM to hex p = BN_bn2hex(bn_p); q = BN_bn2hex(bn_q); g = BN_bn2hex(bn_g); hk = BN_bn2hex(bn_hk); tk = BN_bn2hex(bn_tk); //freeing the resources BN_CTX_free(ctx); BN_free(bn_two); BN_free(bn_p); BN_free(bn_q); BN_free(bn_g); BN_free(bn_hk); BN_clear_free(bn_tk); return 0; } The file.h, auxchash.h: #include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; #include&lt;openssl/bn.h&gt; #include&lt;openssl/sha.h&gt; #include&lt;openssl/rand.h&gt; int keygen(int bits, char *p, char *q, char *g, char *hk, char *tk); The file.i for the swig module, auxchash.i: %module auxchash %{ #define SWIG_FILE_WITH_INIT #include "auxchash.h" #include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; #include&lt;openssl/bn.h&gt; #include&lt;openssl/sha.h&gt; #include&lt;openssl/rand.h&gt; %} %include "typemaps.i" %include "cstring.i" %cstrin…
downvote count: 1

http://stackoverflow.com/comment/80584599
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46818539
has text: you return "cakes" but I don't see it defined anywhere else before?
score: 1

http://stackoverflow.com/a/46757729
has comment: http://stackoverflow.com/comment/80461182
has comment: http://stackoverflow.com/comment/80481251
downvote count: 0
has comment: http://stackoverflow.com/comment/80461267
answers question: http://stackoverflow.com/q/46757318
type: Answer
has comment: http://stackoverflow.com/comment/80477855
upvote count: 3
has body: You mentioned trying rolling. What exactly went wrong with that? This works for me: my_res = tabla['2015_Avion'].rolling(100).corr(tabla['2015_Hotel']) my_res will have NaN values until its 100th value, so my_res[99] should be the correlation between the row 0 and row 99 elements of both columns, as would be returned by pandas corr function applied only to the subset. my_res[100] is the correlation between the row 1 and row 100 elements.
has comment: http://stackoverflow.com/comment/80478804
score: 3
has comment: http://stackoverflow.com/comment/80460884
has comment: http://stackoverflow.com/comment/80461515

http://stackoverflow.com/comment/80706735
type: AnswerComment
comment on: http://stackoverflow.com/a/46797009
has text: Added the line that you need in Python 3, just for the future reference.
type: Comment
score: 0

http://stackoverflow.com/comment/80645419
comment on: http://stackoverflow.com/a/46834476
score: 0
type: AnswerComment
type: Comment
has text: Then your problem is more related to Hive and the way it handles UDFs. I do not have much experience with Hive but I would try to add the script (with the shebang) with something like `ADD FILE hdfs:///tmp/my_script.py; USE tmp;` and then either: * call it using something like `... USING 'my_script.py' ...`, or * call it specifying the full path to Python `... USING '/opt/python2.7/bin/python my_script.py' ...`

http://stackoverflow.com/q/46905380
has answer: http://stackoverflow.com/a/46905833
downvote count: 0
favorite count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80757541
type: AnsweredQuestion
upvote count: 1
has title: Converting dictionary key datatype
type: Question
has body: I've seen some questions asked but they change both value and keys. I have the glove embedding dictionary that's in public access. It has words as the keys and 300 values for each key. The keys are str datatype and the values are float. I need to change the keys to 'numpy.unicode_' data type. But just the keys. How do I go about doing that? My current dictionary looks like this: 'king' : [0.0033901, -0.34614, 0.28144, ...] These float values are to be unchanged, it is a 300 dimensional embedding. I just need to change the datatype of the key, 'king' in the example I've given to numpy unicode I tried this from another solution I found: unidict = {key.decode('utf8') for key in embedding_dict()} But it gives the error "TypeError: 'dict' object is not callable"
has answer: http://stackoverflow.com/a/46905897
score: 1
has comment: http://stackoverflow.com/comment/80757816
accepted answer: http://stackoverflow.com/a/46905897
tagged with: numpy
has comment: http://stackoverflow.com/comment/80757556
possible better answer: http://stackoverflow.com/a/46905833
answer count: 2

http://stackoverflow.com/a/46809372
downvote count: 0
answers question: http://stackoverflow.com/q/46805811
has body: First of all, you need to have multiple drilldown series for each series (e.g. three for the 'Passed', three for the 'Failed', three for the 'Not run'). Secondly, the only way to drilldown to more than one series is to add them on drilldown event with a function called addSingleSeriesAsDrilldown. When desired series are added all you need to do is to apply them with applyDrilldown function. Take a look at the example below and in case of any question, feel free to ask. API Reference: https://api.highcharts.com/highcharts/chart.events.drilldown Example: https://jsfiddle.net/7a6gh7vz/
has comment: http://stackoverflow.com/comment/80601238
accepted answer of: http://stackoverflow.com/q/46805811
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/80463617
score: 0
type: Comment
type: QuestionComment
has text: If regex is not the only criterion to get the desired output then you can serve the purpose very easily.
comment on: http://stackoverflow.com/q/46758807

http://stackoverflow.com/q/46755141
favorite count: 0
tagged with: qtreewidget
has answer: http://stackoverflow.com/a/46756148
accepted answer: http://stackoverflow.com/a/46756148
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I have two QTreeWidget's in a form, one without children, the other with children as depicted in the screenshot below. I want that the right tree be expanded if it is collapsed (and collapsed if it is expanded), each time an item in the left tree is selected. I tried to achieve this with the code below, where I connect a handle function to the itemSelectionChanged event of the left list. The problem is that the .collapse() and .expand() methods require a QIndexModel parameter (inherited from QTreeView), but QTreeWidget use a predefined model which I don't know how to access. Can anyone out there give me hand? import sys from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.tree1 = QtGui.QTreeWidget(self) self.tree2 = QtGui.QTreeWidget(self) layout = QtGui.QHBoxLayout(self) self.tree1.header().hide() self.tree2.header().hide() self.tree1.itemSelectionChanged.connect(self.handleSelected) for text in 'A B C D'.split(): item = QtGui.QTreeWidgetItem(self.tree1, [text]) for text in '1 2 3 4'.split(): item = QtGui.QTreeWidgetItem(self.tree2, [text]) for text in 'red blue green'.split(): child = QtGui.QTreeWidgetItem(item, [text]) layout.addWidget(self.tree1) layout.addWidget(self.tree2) def handleSelected(self): if self.tree2.isExpanded(): self.tree2.collapse() else: self.tree2.expand() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
type: Question
score: 1
tagged with: pyqt4
has title: python - Synchronizing two QTreeWidgets
tagged with: pyqt
upvote count: 1
answer count: 1

http://stackoverflow.com/q/46838196
answer count: 1
tagged with: button
has body: I have two python scripts mainapp.py, and calculations.py mainapp.py from tkinter import * import calculations root = Tk() mainapp = Frame(root) mainapp.grid() label1 = Label(mainapp, text="Value A") label1.grid(row=0, column=0) value_a = IntVar() entry1 = Entry(mainapp, textvariable=value_a) entry1.grid(row=0, column=1) label2 = Label(mainapp, text="Value B") label2.grid(row=1, column=0) value_b = IntVar() entry2 = Entry(mainapp, textvariable=value_b) entry2.grid(row=1, column=1) button = Button(mainapp, text="Calculate", command=calculations.addvalues(a=value_a.get(), b=value_b.get())) button.grid(row=2, columnspan=2) label3 = Label(mainapp, text="A+B") label3.grid(row=3, column=0) value_c = IntVar() entry3 = Entry(mainapp, textvariable=value_c) entry3.grid(row=3, column=1) root.mainloop() calculations.py def addvalues(a, b): return a + b I would like to pass the Button command calculation to entry3 field. How to do that? Thank you for the help in advance.
favorite count: 0
tagged with: python
tagged with: command
type: AnsweredQuestion
has title: How to pass calculation form Button command to Entry field?
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/46838719
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46838719
has comment: http://stackoverflow.com/comment/80624781
downvote count: 0

http://stackoverflow.com/a/46901541
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46900020
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80773122
has body: Looking for Packages when you do a conda create .. or conda install ... , or even a conda search, it will only present you results consistent with your OS and in some cases, base python version. What's really available You can go directly to Anaconda.org and search for you package. This will surface builds on channels other than the "official" anaconda distribution packages. When looking here, however, you must manually look through the files available as some may not be built for your os. view the results of conda info to see your current channels. It looks like the channel "conda-forge" may have what you are craving. conda create -n tamtams_project ipython cgal --channel conda-forge I prefer knowing where packages are coming from when I stray from the default channels. you can always see that info by adding to your .condarc file with the command: conda config --set show_channel_urls True The above create would then show that nearly all of the packages would be conda-forge packages since the command line channel becomes the preferred channel. So, a minor preference might be to use: conda create -n tamtams_project ipython cgal -c defaults -c conda-forge Then you see most packages being default packages and two coming from conda-forge.
has comment: http://stackoverflow.com/comment/80775320

http://stackoverflow.com/comment/80653803
comment on: http://stackoverflow.com/q/46852584
score: 0
type: Comment
type: QuestionComment
has text: The person that gave a negative vote could please provide the answer ?

http://stackoverflow.com/comment/89986195
score: 1
has text: @user3698694 if you found an accurate fix, please add it as an answer or remove the question if you don't think it is helpful
type: AnswerComment
comment on: http://stackoverflow.com/a/46854110
type: Comment

http://stackoverflow.com/comment/80586460
score: 0
type: Comment
has text: Thanks wpercy, was knocking my head against a wall then!
type: AnswerComment
comment on: http://stackoverflow.com/a/46819438

http://stackoverflow.com/comment/80671651
has text: I take it you're using recursion here because it's part of an assignment because it's a lot simpler not doing so :)
score: 0
comment on: http://stackoverflow.com/q/46862045
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46785210
upvote count: 2
has comment: http://stackoverflow.com/comment/80518024
has comment: http://stackoverflow.com/comment/80517826
answers question: http://stackoverflow.com/q/46784727
has comment: http://stackoverflow.com/comment/80519015
downvote count: 0
has body: Python solution. from __future__ import print_function with open('file.csv') as f: print(*next(f).split()) # header lastid = None lineno = 0 for line in f: id_, tagno, nth = line.split() if lastid != id_: lineno = 0 if lineno % int(nth) == 0: print(id_, tagno, nth) lastid = id_ lineno += 1
type: Answer
has comment: http://stackoverflow.com/comment/80518594
score: 2
has comment: http://stackoverflow.com/comment/80518273

http://stackoverflow.com/comment/80632917
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46842418
type: Comment
has text: @maynull glad can help

http://stackoverflow.com/q/46876351
tagged with: optimization
has answer: http://stackoverflow.com/a/46878050
score: 0
answer count: 1
has title: Scipy Optimisation with Quadrature
has comment: http://stackoverflow.com/comment/80700460
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80700846
tagged with: python
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/80699842
has body: I'm trying to solve an optimisation, but instead of a function, I am optimising over the parameters of a functional. Here is an example def Q(a,b,c): d = integrate.quad(lambda x: (a*x**2+b*x+c), 0, 1) return d def u(a,b,c): e = a+b+c return e cons = ({'type': 'eq', 'fun' : lambda u: np.array([u - 1]),}), f = lambda x: Q(x[0],x[1],x[2]) res = minimize(Q, args=(3,), method='SLSQP', constraints=cons) I want to minimize the functional Integral Q, given the constraint on the parameters. Ideally I could make the constraint an integral as well. I've not included this here because I want to start off simple. The error I get is TypeError Traceback (most recent call last) &lt;ipython-input-158-cdbd019dd886&gt; in &lt;module&gt;() 8 'fun' : lambda u: np.array([u - 1]),}), 9 f = lambda x: Q(x[0],x[1],x[2]) ---&gt; 10 res = minimize(Q, args=(3,), method='SLSQP', constraints=cons) TypeError: minimize() takes at least 2 arguments (4 given) It should be stated that I'm not bothered about what kind of code or edits I use to get this to work! just want it to work.

http://stackoverflow.com/a/59539120
has body: Assuming that type(api) == 'testlink.testlinkapigeneric.TestlinkAPIClient' api.getLastExecutionResult(testplanID, testcaseID, [buildid = build_number])[0] Build number is optional. You can use this to generate Python TestLink API documentation and explore other TestLink methods/APIs. for m in testlink.testlinkargs._apiMethodsArgs.keys(): print(tls.whatArgs(m), '\n')
answers question: http://stackoverflow.com/q/46901923
score: 0
type: Answer

http://stackoverflow.com/q/46772176
linked to: http://stackoverflow.com/q/37731368
has answer: http://stackoverflow.com/a/46772745
has answer: http://stackoverflow.com/a/46772342
linked to: http://stackoverflow.com/q/9733638
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/46772821
tagged with: curl
has comment: http://stackoverflow.com/comment/80490016
has comment: http://stackoverflow.com/comment/80490239
upvote count: 0
has body: I am using anki-connect to communicate with Anki, a spaced repetition software. In readme.md, it uses following command to get deck name. curl localhost:8765 -X POST -d "{\"action\": \"deckNames\", \"version\": 5}" It works right in my Windows system. How can I use python instead of cURL? I've tried this but get no luck. import requests r = requests.post("http://127.0.0.1:8765", data={'action': 'guiAddCards', 'version': 5}) print(r.text)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80490004
has comment: http://stackoverflow.com/comment/80489999
has title: How can I post http request instead of using cURL?
score: -1
type: Question
has comment: http://stackoverflow.com/comment/80489979
favorite count: 0

http://stackoverflow.com/q/46905399
has title: Call python function from robot framework
tagged with: robotframework
type: UnansweredQuestion
has body: I'm trying to figure out what am I doing wrong, I want to get the result of a specific python function. This is my Resources.robot file: *** Settings *** Library resources_func.py *** Keywords *** Test Time ${time_delta}= get time period ${Time} ${Time} is defined but isn't relevant to my question and this is my python script: import re from dateutil.parser import parse class TimeTests(object): def get_time_period(timestamp): timestamps = re.findall(r'[0-9][0-9]:[0-9][0-9]', timestamp) a = parse(timestamp[0]) b = parse(timestamp[1]) res = (b - a) res = res.seconds / 60 return res This is the error I'm getting: No keyword with name 'get time period' found. Any ideas?
tagged with: python
type: Question
tagged with: selenium2library
score: 0
has comment: http://stackoverflow.com/comment/80759500
has answer: http://stackoverflow.com/a/46906566
answer count: 1
has comment: http://stackoverflow.com/comment/80758585

http://stackoverflow.com/a/46760689
type: Answer
answers question: http://stackoverflow.com/q/46760671
score: 0
type: AcceptedAnswer
has body: You don't import TfawItem anywhere in massEffect.py. Add for example from ..items import TfawItem to the top of massEffect.py.
accepted answer of: http://stackoverflow.com/q/46760671

http://stackoverflow.com/comment/80563843
has text: It will help if you also share the relevant code snippets from your DAG. This can happen if you miss to assign task to the DAG while defining them.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46807838

http://stackoverflow.com/a/46839318
has comment: http://stackoverflow.com/comment/80626625
has comment: http://stackoverflow.com/comment/80626556
score: 1
upvote count: 1
has body: I will make a simple example, but basically you need a class that will contain each region function as a method and then call those functions with getattr() wich allows you to call a method of a class by its name as string. class Region(object): def foo_US(self): print('US method') def foo_GB(self): print('GB method') # so on... my_region = 'foo_US' my_region_function = getattr(Region, my_region) my_region_function() # &gt;&gt;&gt; US method
downvote count: 0
answers question: http://stackoverflow.com/q/46839087
has comment: http://stackoverflow.com/comment/80627142
type: Answer

http://stackoverflow.com/comment/80739915
type: QuestionComment
score: 2
has text: Convert this to use sets instead of lists. Then apply set intersection, and return the length of the result. Can you supply a self-contained example for us to experiment?
comment on: http://stackoverflow.com/q/46896347
type: Comment

http://stackoverflow.com/comment/80636369
score: 0
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157123/discussion-between-rajkris-and-christian).
comment on: http://stackoverflow.com/a/46843735
type: AnswerComment

http://stackoverflow.com/comment/93507650
score: 0
type: AnswerComment
has text: The program needs to read these environment variable to determine which model to use and what image size to use.
type: Comment
comment on: http://stackoverflow.com/a/46880437

http://stackoverflow.com/q/46805610
upvote count: 1
has title: What's the parse function to this Json?
accepted answer: http://stackoverflow.com/a/46806130
type: Question
has body: "results": [ { "result_index": 0, "results": [ { "final": true, "alternatives": [ { "transcript": "THE TEXT ", "confidence": 0.2958 } ] } ] } ], "status": "completed" I want the value of transcript in this Json, basically i want :THE TEXT The parse i tried and didn't work : def parse(obj): text=[] if 'results' in obj: results = obj['results'] for result in results: if 'results' in results: results = results['results'] if 'alternatives' in result: alternatives = result['alternatives'] assert len(alternatives) == 1 alternative = alternatives[0] text.append(alternative['transcript']) return ' '.join(text).lstrip().rstrip() What would the correct parse function to use be
tagged with: http://stackoverflow.com/tag/json
score: -1
tagged with: python-2.7
answer count: 1
favorite count: 0
tagged with: parsing
has answer: http://stackoverflow.com/a/46806130
has comment: http://stackoverflow.com/comment/80559089
tagged with: python
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/a/46864391
answers question: http://stackoverflow.com/q/46864338
type: Answer
has comment: http://stackoverflow.com/comment/80676212
has comment: http://stackoverflow.com/comment/80676261
has comment: http://stackoverflow.com/comment/80676468
has comment: http://stackoverflow.com/comment/80676303
has body: If you are trying to remove the first 4 letters from the file, you can use regular expressions: import re characters = re.findall("[\w\W]", open('file.txt').read()) final_data = ''.join(characters[4:])
has comment: http://stackoverflow.com/comment/80676358
score: 0
has comment: http://stackoverflow.com/comment/80676314

http://stackoverflow.com/comment/80735179
type: AnswerComment
score: 0
has text: how do your items look when logged?
type: Comment
comment on: http://stackoverflow.com/a/46893575

flask-mongoengine
tags question: http://stackoverflow.com/q/46766174
type: Tag
tag name: flask-mongoengine

http://stackoverflow.com/comment/80747877
type: Comment
comment on: http://stackoverflow.com/a/46900348
has text: I'm being forced to code because I don't want to copy and paste 500 items into an excel sheet one-by-one.
score: 0
type: AnswerComment

http://stackoverflow.com/q/46857851
type: Question
tagged with: python-2.7
has body: I have a simple scenario where I am changing the delimiter in a CSV from ; (semicolon) to , (comma). Below is the code Code: import csv semicolonin = csv.reader(r"C:\pyscripts\1.csv", delimiter=';') commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',') for row in semicolonin: commaout.writerow(row) But I receive an error. Am I missing something? TypeError: argument 1 must have a "write" method while executing line commaout = csv.writer(r"C:\pyscripts\1.csv", delimiter=',').
answer count: 2
has answer: http://stackoverflow.com/a/57709827
has title: Converting delimiter from semicolon to comma in a CSV?
favorite count: 0
has comment: http://stackoverflow.com/comment/80670500
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
upvote count: 4
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80663344
has answer: http://stackoverflow.com/a/46857992
score: 4

http://stackoverflow.com/q/46868031
downvote count: 0
has comment: http://stackoverflow.com/comment/80691864
has body: I am developing an event driven system which has two processes: the event driven algorithm with Queue() the data handler. The data handler is a separate class that launches a secondary process which is a self-contained websocket (MySocket) that updates the data within itself. The data handler has two methods: one to fetch and modify the data from the socket and one to put the data into a queue that is used by the main event driven process. In a nutshell the script does the following: Update data -> data_handler.update_market() -> put data into queue Confirm signal Execute Repeat Here is the data handler code snippet: import multiprocessing as mp class SocketDataHandler(DataHandler): def __init__(self, events, client, markets_list): """ Initialises data handler. Parameters: events - The Event Queue. markets_list - A list of symbol strings. """ self.events = events self.client = client self.markets_list = markets_list self.market_orders = [] self.socket = None self.proc = None self.start_w_proc() def start_w_proc(self): market_list = self.markets_list[0] self.socket = MySocket(self.markets_list[0]) self.proc = mp.Process(target=self.socket.run()) self.proc.start() def get_market_orders(self): market_orders = self.socket.get_order_book() #...Rearrange the data return market_orders def update_market(self): self.market_orders = self.get_market_orders() self.events.put(MarketEvent()) The code so far seems to work i.e I am able to access the MySocket class from the main process without using multiprocessing.Manager or Value but I believe there could be a more efficient and proper way to accomplish that.
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Access class methods from another process
score: 2
has comment: http://stackoverflow.com/comment/80683399
answer count: 0
upvote count: 2
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/80691855
has comment: http://stackoverflow.com/comment/80687012

http://stackoverflow.com/a/46824417
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/46824333
has body: The problem is not in how to use assert but what you are trying to assert. Your union function prints a "result" but actually returns None (because you don't have any return statement). So you are actually asserting None == ({-3, 1, 2, 4, 'bob', 'jill'}, 6) which is False, use return total instead of (or in addition to if you really want to) print(total).
score: -1

http://stackoverflow.com/q/46854766
has answer: http://stackoverflow.com/a/47312020
has title: Is Luigi suited for building a pipeline around lots of small files (100k+)
has body: My first gut reaction is that Luigi isn't suited for this sort of thing, but I would like the "pipeline" functionality and everything keeps pointing me back to Luigi/Airflow. I can't use Airflow as it is a Windows environment. My use-case: So currently from my “source” folder we have 20 or so machines that produce XML data. Over time, some process puts these files into a folder continually on each machine (its log data). On any given day these machines could have 0 files in the folder or it could have 100k+ files (each machine). Eventually someone will go delete all of the files. One part of this process is to to watch all of these directories on all of these machines, and copy the files down to an archive folder if they are new. My current process makes a listing of all the files on each machine every 5 minutes, grabs a listing of the files and loops over the source checking if the file is available at the destination. Copies if it doesn't exist at destination, skips if it does. It seems that Luigi wants to work with only "a" (singular) file in its output and/or target. The issue is, I could have 1 new file, or several thousand files that shows up. This same exact issue happens through the entire process. As the next step in my pipeline is to add the files and its metadata information (size, filename, directory location) to a db record. At that point another process reads all of the metadata record rows and puts them into a content extracted table of the XML log data. Is Luigi even suited for something like this? Luigi seems to want to deal with one thing, do some work on it, and then emit that information out to another single file.
type: Question
answer count: 1
score: 0
tagged with: luigi
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/46862297
has comment: http://stackoverflow.com/comment/80687039
has comment: http://stackoverflow.com/comment/80687315
type: Answer
accepted answer of: http://stackoverflow.com/q/46860838
has comment: http://stackoverflow.com/comment/80694490
answers question: http://stackoverflow.com/q/46860838
upvote count: 1
has body: Try this. It will give you the items you probably look for. Selenium with BeautifulSoup is easy to handle. I've written it that way. Here it is. from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Chrome() driver.get("https://twitter.com/24x7chess") soup = BeautifulSoup(driver.page_source,"lxml") driver.quit() for title in soup.select("#page-container"): name = title.select(".ProfileHeaderCard-nameLink")[0].text.strip() location = title.select(".ProfileHeaderCard-locationText")[0].text.strip() tweets = title.select(".ProfileNav-value")[0].text.strip() following = title.select(".ProfileNav-value")[1].text.strip() followers = title.select(".ProfileNav-value")[2].text.strip() likes = title.select(".ProfileNav-value")[3].text.strip() print(name,location,tweets,following,followers,likes) Output: akul chhillar New Delhi, India 214 44 17 5
has comment: http://stackoverflow.com/comment/80678255
has comment: http://stackoverflow.com/comment/80677845
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80694441

http://stackoverflow.com/q/46876976
has body: class A: pass class B(A): pass How can I check that var is instance of B, not A, without referencing A. I have around 50 classes that subclass some class. I want to check whether instance is a child. Something like not isinstance(var, A). Is there any way?
has title: Python determine if isintance without checking superclass
has comment: http://stackoverflow.com/comment/80701553
has answer: http://stackoverflow.com/a/46877185
score: 5
has comment: http://stackoverflow.com/comment/80701112
has comment: http://stackoverflow.com/comment/80701363
has answer: http://stackoverflow.com/a/46883383
has answer: http://stackoverflow.com/a/46877108
favorite count: 0
has answer: http://stackoverflow.com/a/46877208
upvote count: 8
answer count: 5
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46877206
downvote count: 3
linked to: http://stackoverflow.com/q/16688655
possible better answer: http://stackoverflow.com/a/46877108
has comment: http://stackoverflow.com/comment/80701672
type: Question
has comment: http://stackoverflow.com/comment/80701419
accepted answer: http://stackoverflow.com/a/46883383

http://stackoverflow.com/comment/80500313
has text: Thank you @user2357112 ! k-d tree is very nice in my situation !
score: 0
comment on: http://stackoverflow.com/q/46775913
type: Comment
type: QuestionComment

pool
tags question: http://stackoverflow.com/q/46833131
tag name: pool
type: Tag
tags question: http://stackoverflow.com/q/46827515

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

http://stackoverflow.com/comment/80614664
type: QuestionComment
comment on: http://stackoverflow.com/q/46833398
has text: @Divakar: It throws a `TypeError` for non-integer values
score: 0
type: Comment

http://stackoverflow.com/a/46817959
accepted answer of: http://stackoverflow.com/q/46799638
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: I'm from Upwork. I guess this is what you want results[3].xpath("//td[contains(@class,'actual')]")
answers question: http://stackoverflow.com/q/46799638
type: Answer

http://stackoverflow.com/comment/80585217
comment on: http://stackoverflow.com/q/46818102
has text: Why do you add the same button several times to the layout? `layout.addWidget(btn_close, 0, 1) layout.addWidget(btn_close, 1, 1) layout.addWidget(btn_close, 2, 0) layout.addWidget(btn_close, 2, 2)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46903999
type: Answer
has body: So,it seems the culprit was something else in my case,i didn't add a proper variable to ALLOWED_HOSTS,adding the heroku app fixed it
score: 0
answers question: http://stackoverflow.com/q/46902711

http://stackoverflow.com/a/46891423
has body: In Pseudo code? I'd try and read up a bit on Python, its really not hard to understand what is going on. Basically: import imports various python modules needed in this code. def restart_program(): defines a function which you can run later in the code with restart_program() While True: means do something forever, or until break .lower() is the lowercase version of the string If you're using this code as a basis, it is not particularly pythonic, it uses a style like an old linear basic program, with an overuse of While True loops. There is definitely much shorter and more readable ways of writing the same program.
has comment: http://stackoverflow.com/comment/80734961
downvote count: 0
answers question: http://stackoverflow.com/q/46890334
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/46859816
has body: I was able to get it working with the code below. import re def editcam(filetext, filename, x, y, z): print 'opening file' filetext=re.sub(r'location &lt;(\d+),(\d+),(\d+)&gt;', 'location &lt;%d,%d,%d&gt;'% (x,y,z), filetext) fout=open(filename, 'w') print 'file opened' fout.write(filetext) fout.close() return def main(): editcam(__file__,'tmp.pov',0,0,12) return main()
score: 0
answers question: http://stackoverflow.com/q/46859728
type: Answer

http://stackoverflow.com/comment/80684995
comment on: http://stackoverflow.com/q/46868725
score: 0
has text: you have to add the exact content of the text file and the output of your script when you execute it.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46814474
has body: As mentioned in the comments of your question, you do not want to use mutable default values. A common idiom in this case is something like so: def my_function(arg1="my_string", arg2=None, arg3=None, arg4=True): if arg2 is None: arg2 = [] if arg3 is None: arg3 = {} Note that arg1 and arg4 were not changed. This is because they are IMMUTABLE, and thus can be used properly as default arguments. Obviously, one issue with this approach is that the user of your function does not easily know what type is expected for arg2 and arg3 so you will want to make sure and include a docstring that explains the expected types.
upvote count: 4
answers question: http://stackoverflow.com/q/46813910
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/80596140
has comment: http://stackoverflow.com/comment/80582096
type: Answer

http://stackoverflow.com/comment/80634582
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46843016
has text: @XeroSmith I've made the changes. Thanks for the correction

http://stackoverflow.com/a/46802884
accepted answer of: http://stackoverflow.com/q/46786469
answers question: http://stackoverflow.com/q/46786469
score: 0
type: AcceptedAnswer
has body: Let's go through your code in file_main.py execfile("file_execed.py", globals(), exec_results) This line creates two functions named foo, bar and put them into the dict exec_results. When these functions are created, their global state (result of globals()) is what we put on the second parameter of execfile command, in this case it's the global state of file_main.py (remember that when a function is defined in a module, it's set into the locals() of that module, not globals()) # Attach objects created by exec to module_to_add_to for k, v in exec_results.iteritems(): setattr(module_to_add_to, k, v) The two functions foo, bar above are added to the module module_to_add_to. module_to_add_to.call() The function bar above is called, when it's called, as what stated above, its global state is the global state of file_main.py, so let's check what we have in the global state of file_main.py by adding this line above module_to_add_to.call(): print(globals().keys()) And we get: ['exec_results', '__builtins__', '__file__', 'module_to_add_to', '__package__', 'v', '__name__', '__doc__', 'k'] There's no foo or bar here, so that's why you got the NameError exception. You can try modifying your code as below and it will work: # Attach objects created by exec to module_to_add_to for k, v in exec_results.iteritems(): setattr(module_to_add_to, k, v) globals()[k] = v Hope this helps.
type: Answer

http://stackoverflow.com/comment/80494753
comment on: http://stackoverflow.com/a/46770057
type: AnswerComment
score: 0
type: Comment
has text: I am looking for the same behavior of `set_palette( )`. If I redefine the colormap, with something like `plt.rcParams["image.cmap"] = "Accent"`, when I call `plt.scatter(x[:,0],x[:,1])` (without the color argument) it would use the first color on the colormap. But maybe I'm wrongly expecting a colormap to function as palette.

http://stackoverflow.com/comment/80691302
type: QuestionComment
type: Comment
score: 0
has text: Have you tried something ? If so, please show us the code.
comment on: http://stackoverflow.com/q/46872021

http://stackoverflow.com/a/46830119
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46828031
answers question: http://stackoverflow.com/q/46828031
upvote count: 2
type: AcceptedAnswer
has body: Using the x_vars and y_vars arguments of pairplot you can select which columns to correlate. import matplotlib.pyplot as plt import seaborn as sns iris = sns.load_dataset("iris") g = sns.pairplot(iris, x_vars=["sepal_width","petal_length","petal_width"], y_vars=["sepal_length"]) plt.show()
has comment: http://stackoverflow.com/comment/80618669
type: Answer
score: 2

http://stackoverflow.com/q/46806918
tagged with: yaml
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to make a custom YAML dumper/loader for some configuration objects. For simplicity, assuming we want to dump a object of class Hero to a hero.yml file. The example which works with default dumper/loader class Hero: yaml_tag = '!Hero' def __init__(self, name, age): self.name = name self.age = age Then add the default loader/dumper by ruamel.yaml yaml.register_class(Hero) And try dump and load: h = Hero('Saber', 15) with open('config.yml', 'w') as fout: yaml.dump(h, fout) with open('config.yml') as fin: yaml.load(fin) It works perfectly! But failed with custom to_yaml and from_yaml methods However, when I need a more flexible behavior, thus a custom from_yaml and to_yaml method is necessary, there is problem. The implementation of Hero is changed to: class Hero: yaml_tag = '!Hero' def __init__(self, name, age): self.name = name self.age = age @classmethod def to_yaml(cls, representer, data): return representer.represent_mapping(cls.yaml_tag, {'name': data.name, 'age': data.age}) @classmethod def from_yaml(cls, constructor, node): print(node) # for debug value = constructor.construct_mapping(node) return cls(**value) The dumper works just as desired. But the load failed to load the YAML file. An Exception is thrown: 243 def check_mapping_key(self, node, key_node, mapping, key, value): 244 # type: (Any, Any, Any, Any, Any) -&gt; None --&gt; 245 if key in mapping: 246 if not self.allow_duplicate_keys: 247 args = [ TypeError: argument of type 'NoneType' is not iterable By the print(node) line marked with for debug, the node loaded is: MappingNode(tag='!Hero', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='name'), ScalarNode(tag='tag:yaml.org,2002:str', value='Saber')), (ScalarNode(tag='tag:yaml.org,2002:str', value='age'), ScalarNode(tag='tag:yaml.org,2002:int', value='15'))]) Reason of not using default dumper/loader This sample is a minimal case to show the problem, in real case, I'm trying to dump only part of the object, like class A: yaml_tag = '!A…
type: UnansweredQuestion
tagged with: python
upvote count: 3
type: Question
tagged with: ruamel.yaml
score: 3
has answer: http://stackoverflow.com/a/51827378
has title: How to create a custom yaml mapping dumper for ruamel.yaml?

http://stackoverflow.com/q/46788182
has body: I'm trying to pass the session object from one file to another in order to use the same session object across all the different things I need to do (list/create VMs etc.) So far I've tried using Pickle (which hasn't worked as there is a lock instance on the object). I'm now trying to use Cherrypy to enable me to store the object as a cookie (which I'm already doing for name and fedid). But I'm getting an error which says the session object isn't JSON serializable. How do I get past this error and is this the right way to go about passing session objects? If it's not the correct solution, how do I pass session objects (the documentation isn't exactly helpful)? import cherrypy import ldap import xmlrpclib import xml.etree.ElementTree as ET from keystoneauth1 import loading from keystoneauth1 import session as session import novaclient.client as client import json import pickle NOVA_VERSION="2.1" KEYSTONE_URL = cherrypy.request.config.get("keystone") OPENSTACK_HOST = cherrypy.request.config.get("openstack_host") OPENSTACK_DEFAULT_DOMAIN = cherrypy.request.config.get("openstack_default_domain") loader = loading.get_plugin_loader('password') auth = loader.load_from_options(auth_url=KEYSTONE_URL, username=data.get("username"), password=data.get("password").replace(" ","%20"),user_domain_name=OPENSTACK_DEFAULT_DOMAIN) sess = session.Session(auth=auth) nova = client.Client(NOVA_VERSION,session=sess) data = { 'name' : name, 'fedid' : data.get("username"), 'sessionTest' : json.dumps(sess), 'expires' : EXPIRE } Error: File "/usr/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 656, in respond response.body = self.handler() File "/usr/lib/python2.7/site-packages/cherrypy/lib/encoding.py", line 188, in __call__ self.body = self.oldhandler(*args, **kwargs) File "/usr/lib/python2.7/site-packages/cherrypy/lib/jsontools.py", line 61, in json_handler value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) File "/usr/lib/python2.7/site-packages/cherrypy/_cpdispa…
tagged with: cherrypy
tagged with: openstack
type: Question
has comment: http://stackoverflow.com/comment/80523636
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80522707
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/46788765
has comment: http://stackoverflow.com/comment/80523207
has title: Passing Session Object Using OpenStack - KeyStone
answer count: 1
has answer: http://stackoverflow.com/a/46788765
tagged with: keystone
score: 0
tagged with: python

http://stackoverflow.com/a/57360758
score: 3
answers question: http://stackoverflow.com/q/46751336
has body: The problem is in the import. I've had same issue when I used: from graphene import ObjectType I've found how to import it properly in next example from docs. Here it is: from graphene_django.types import DjangoObjectType
upvote count: 3
type: Answer
downvote count: 0

http://stackoverflow.com/comment/80701003
comment on: http://stackoverflow.com/a/46876967
score: 0
type: Comment
has text: But dude the whole stuff is written in a file how do you store it in 's' ??
type: AnswerComment

http://stackoverflow.com/q/46861946
has comment: http://stackoverflow.com/comment/80671835
has answer: http://stackoverflow.com/a/46862594
has comment: http://stackoverflow.com/comment/80671649
type: Question
has title: How to fix, limit_choices_to cannot be a ForeignKey in Django?
has comment: http://stackoverflow.com/comment/80671938
score: 3
has comment: http://stackoverflow.com/comment/80671553
linked to: http://stackoverflow.com/q/583327
has comment: http://stackoverflow.com/comment/80671945
upvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80671950
has body: I've a snip of code like following: models.py class Notebook(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) name= models.CharField(max_length=50) class Note(models.Model): create_user = models.ForeignKey(User, on_delete = models.CASCADE) text=models.CharField(max_length=500) notebook=models.ForeignKey(Notebook, on_delete = models.CASCADE, limit_choices_to = {'owner' : create_user}) But I'm getting an error that limit_users_to cannot be a Foreign Key. I want to users to select only notebooks they have created while writing a note, but now users can select other's notebook while limit_choices_to is not set. And notebook must be ForeignKey. What can i do?
has comment: http://stackoverflow.com/comment/80671764
accepted answer: http://stackoverflow.com/a/46862594
linked to: http://stackoverflow.com/q/28038599
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/46794333
has title: Python Fruit Machine - Looping back to input
has body: I need to make a fruit machine in Python. The fruits/items spinning are Cherry, Lemon, Bell, Star and Skull. The Success criteria is • • If two symbols are rolled the user wins 50p. • If two skulls are rolled user loses £1, if three skulls are rolled loses all money. • If you get 3 of the same you get £1, if 3 bells rolled £5. • Starts with £1, each go costs 20p. How do I loop it back to the question "Roll" or "Quit" and how do I make it so that is a user enters something other than roll or quit it says "Oops try again"? - Please explain any changes to the code as I just know the basics.
tagged with: python
answer count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/46794602
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/46794602
score: 0

http://stackoverflow.com/comment/80689331
has text: @DamirShakenov try with some other text viewer such as sublime.
comment on: http://stackoverflow.com/a/46870985
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46836301
has title: KeyError When I want try to plot
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80620683
favorite count: 0
has body: I get an error whenever I try to perform actions on U objects. I always get a KeyError. I have tried many times to plot U (last statement.) import pandas as pd users =pd.read_csv('./users.csv',sep=',',parse_dates=[30]) users.head() users.columns.get_loc("WhenCreated") users['Month'] = users['WhenCreated'].dt.month users.head() UsersCreatedin2017=users['WhenCreated'] &gt; '2017-01-01' users2017=users[UsersCreatedin2017].copy() users2017'Month','UserPrincipalName'.groupby('Month').count() u=users2017'Month','UserPrincipalName'.groupby('Month').count().copy() u.plot(kind='line', x='Month', y='UserPrincipalName') where I go the following error KeyError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2392 try: -&gt; 2393 return self._engine.get_loc(key) 2394 except KeyError: pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)() KeyError: 'Month' During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) &lt;ipython-input-7-841cfe522e84&gt; in &lt;module&gt;() 13 #u.sort_values(by='Month', ascending=True) 14 #u.plot.line('Month','UserPrincipalName') ---&gt; 15 u.plot(kind='line', x='Month', y='UserPrincipalName') 16 17 C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py 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) 2618 fon…
has answer: http://stackoverflow.com/a/46837897
tagged with: python
tagged with: plot
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/80623025
has comment: http://stackoverflow.com/comment/80623289
type: Question
has comment: http://stackoverflow.com/comment/80623161
accepted answer: http://stackoverflow.com/a/46837897
has comment: http://stackoverflow.com/comment/80623104
tagged with: data-science

http://stackoverflow.com/q/46874324
has body: I have the following data: Id | PrimaryName | SecondaryName | Value ---+-------------+---------------+------- 0 | PN0 | SN0 | 3 1 | PN0 | SN1 | 5 2 | PN0 | SN2 | 6 3 | PN1 | SN3 | 5 4 | PN1 | SN4 | 6 5 | PN1 | SN5 | 7 6 | PN2 | SN6 | 1 7 | PN2 | SN7 | 2 8 | PN2 | SN8 | 3 Actually, it is something like a key-value pair, with SecondaryName as key and Value as, hm, value, with additional column PrimaryName. My task is, by looking at only the two entries with the biggest value for each PrimaryName, to determine the two biggest PrimaryNames. For example, for PN0 two biggest values are 5 and 6, for PN1 are 6 and 7, for PN2 are 2 and 3. That means that the biggest PrimaryNames are PN0 with the score of 11, and PN1 with the score of 13. The desirable result is just an ordered list of PrimaryNames => ['PN1', 'PN0'] As someone who's rather proficient with C#, that looked like a quite easy task, solvable with the following query: var result = table.GroupBy(r =&gt; r.PrimaryName) .Select(g =&gt; new { PrimaryName = g.Key, Value = g.OrderByDescending(e =&gt; e.Value).Take(2).Sum(e =&gt; e.Value) }) .OrderByDescending(e =&gt; e.Value) .Take(2) .Select(e =&gt; e.PrimaryName) .ToList(); Yet now I have to repeat it in Python, specifically pandas. So far I conjured only the following part of a query: df.groupby('PrimaryName')'PrimaryName', 'Value' I suspect that to perform calculations like I did in this C# line g.OrderByDescending(e =&gt; e.Value).Take(2).Sum(e =&gt; e.Value) I will have to define a new dataframe with a temporary column, but I am not sure how exactly. Can anybody please help me with that? There is actually a bit more to the question. This task is the part of a course on pandas, and, judging by the fact that groupby is the next weeks topic, I might be on the wrong path, or at least I might be missing out something easy and obvious.
has answer: http://stackoverflow.com/a/46874575
upvote count: 2
has comment: http://stackoverflow.com/comment/80695629
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/46874403
accepted answer: http://stackoverflow.com/a/46874403
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Query to Pandas dataframe
type: Question
tagged with: c#
answer count: 2
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/46874575

http://stackoverflow.com/a/46832388
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46832263
answers question: http://stackoverflow.com/q/46832263
has comment: http://stackoverflow.com/comment/80665893
type: Answer
score: 0
has body: you are not reset the region, so it store previous result. if (region != ""): output.append([current_state, region]) change to if (region != ""): output.append([current_state, region]) region = ''

http://stackoverflow.com/q/46792634
possible better answer: http://stackoverflow.com/a/46793450
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80532698
has body: Working with the following python pandas dataframe "df": Customer_ID | Transaction_ID | Item_ID ABC 2017-04-12-333 X8973 ABC 2017-04-12-333 X2468 ABC 2017-05-22-658 X2906 ABC 2017-05-22-757 X8790 ABC 2017-07-13-864 X8790 BCD 2017-08-11-879 X2346 BCD 2017-08-11-879 X2468 I want to count the transactions to have in a column denoted, when it's the client's 1st transaction, 2nd transaction and so forth by date. (If there are two transactions on the same day, I am counting them both as the same count, since I don't have the time, so I don't know which one came first - basically treating them as one transaction). #get the date out of the Transaction_ID string df['date'] = pd.to_datetime(df.Transaction_ID.str[:10]) #calculate the transaction number df['trans_nr'] = df.groupby(['Customer_ID',"Transaction_ID", df['date'].dt.year]).cumcount()+1 Unfortunately, this is my output with the code above: Customer_ID | Transaction_ID | Item_ID | date | trans_nr ABC 2017-04-12-333 X8973 2017-04-12 1 ABC 2017-04-12-333 X2468 2017-04-12 2 ABC 2017-05-22-658 X2906 2017-05-22 1 ABC 2017-05-22-757 X8790 2017-05-22 1 ABC 2017-07-13-864 X8790 2017-07-13 1 BCD 2017-08-11-879 X2346 2017-08-11 1 BCD 2017-08-11-879 X2468 2017-08-11 2 Which is incorrect, this is the correct output I am looking for: Customer_ID | Transaction_ID | Item_ID | date | trans_nr ABC 2017-04-12-333 X8973 2017-04-12 1 ABC 2017-04-12-333 X2468 2017-04-12 1 ABC 2017-05-22-658 X2906 2017-05-22 2 ABC 2017-05-22-757 X8790 2017-05-22 2 ABC 2017-07-13-864 X8790 2017-07-13 3 BCD 2017-08-11-879 X2346 2017-08-11 1 BCD 2017-08-11-879 X2468 2017-08-11 1 Maybe the logic should be based only on Customer_ID and date (without Transaction_ID)? I tried this df['trans_nr'] = df.groupby(['Customer_ID','date').cumcount()+1 But it also counts incorrectly.
has answer: http://stackoverflow.com/a/46793308
has title: Python Pandas incorrect date count
has comment: http://stackoverflow.com/comment/80532238
tagged with: date
has answer: http://stackoverflow.com/a/46793323
has comment: http://stackoverflow.com/comment/80532361
has comment: http://stackoverflow.com/comment/80532437
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46793323
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80532397
tagged with: count
has answer: http://stackoverflow.com/a/46793450
tagged with: python
has comment: http://stackoverflow.com/comment/80532653
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/46860410
tagged with: image
type: Question
has comment: http://stackoverflow.com/comment/80668455
has title: Python - Method to convert random points to line?
has comment: http://stackoverflow.com/comment/80668950
has comment: http://stackoverflow.com/comment/80668563
answer count: 1
has body: When I have some points its position is random as drawn below. I want to dynamically draw lines with some restrictions. 1) No points in selected region. 2) The triangles are at acute angle. 3) Points are in X/Y (2D) plane. So points are processed &amp; divided therefore... Can I find advice about any appropriate math solutions or even libraries?
has comment: http://stackoverflow.com/comment/80669212
favorite count: 0
has answer: http://stackoverflow.com/a/46860754
has comment: http://stackoverflow.com/comment/80668649
has comment: http://stackoverflow.com/comment/80668792
tagged with: python
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80669537
downvote count: 3
score: -1
has comment: http://stackoverflow.com/comment/80669220

http://stackoverflow.com/a/52499699
has comment: http://stackoverflow.com/comment/91943195
answers question: http://stackoverflow.com/q/46749659
score: 4
has comment: http://stackoverflow.com/comment/95003152
has comment: http://stackoverflow.com/comment/94982847
type: Answer
upvote count: 4
has body: If you want to stop a spider from a pipeline, you can call the close_spider() function of the engine. class MongoDBPipeline(object): def process_item(self, item, spider): spider.crawler.engine.close_spider(self, reason='finished')
downvote count: 0

http://stackoverflow.com/comment/80707492
type: QuestionComment
comment on: http://stackoverflow.com/q/46878153
has text: if the data points are unformly spaced along one axis then there are digital signal processing/filter options for upsampling or sample rate conversion
score: 0
type: Comment

http://stackoverflow.com/comment/80611301
comment on: http://stackoverflow.com/q/46783887
has text: do you got any updates on this? I did a small demo app on my machine and couldn't reproduce this one :(
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46832727
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47012058
score: 1
has body: I'm trying to feed Pandas some data via a SQL query then save the pivoted results onto a .csv file. So far I have been successful. import cx_Oracle import pandas as pd query = """ SELECT dt, --Workstack, GM, COUNT(JOB_NUMBER) FROM MY_TABLE GROUP BY dt, --Workstack, GM """ connection = cx_Oracle.connect("&lt;My_Username&gt;", "&lt;My Password&gt;", "&lt;Database String&gt;") df = pd.read_sql_query(query, connection) piv = df.pivot(index='GM', columns='DT', values='COUNT') print (piv.head()) piv.to_csv('''Workstack.csv''') Now I wish to include the field "Workstack" used within the query variable and I also want to use pandas to filter on different strings with the field Workstack then paste them as different csv files or on the same Excel file. However, when I include Workstack within the query python gives me this error... ValueError: Index contains duplicate entries, cannot reshape Any ideas how I solve this? Eventually I want to use a python Excel module to paste pivot tables like the one above onto different cells and sheets. Thanks :)
upvote count: 1
tagged with: excel
type: Question
has title: Filtering Pandas PivotTable
has comment: http://stackoverflow.com/comment/80613140
answer count: 2
has answer: http://stackoverflow.com/a/46832870
accepted answer: http://stackoverflow.com/a/46832870
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47012058
downvote count: 0
favorite count: 0
tagged with: pivot-table

http://stackoverflow.com/comment/80673125
type: QuestionComment
comment on: http://stackoverflow.com/q/46862849
has text: my expected out put are Even numbers: ~56 Odd numbers:~3~8.9~7.7~5
score: 0
type: Comment

http://stackoverflow.com/comment/80504457
type: Comment
type: QuestionComment
has text: Thanks Man but still not working in fact I have the whole code like this :
comment on: http://stackoverflow.com/q/46779060
score: 0

http://stackoverflow.com/comment/80639537
comment on: http://stackoverflow.com/a/46845801
score: 0
type: AnswerComment
has text: @PM2Ring I guess that could be solved by using `collections.OrderedDict`
type: Comment

http://stackoverflow.com/comment/80699467
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46874463
has text: @MaxU Cheers, I couldn't have gotten this far without your support. B)
type: AnswerComment

http://stackoverflow.com/comment/80676556
has text: This doesn't work. It finds the smallest non-empty overlap, rather than the largest. For example, for overlap('Where did', 'did you go?') it gives 'Where didid you go?', rather than the desired 'Where did you go?'. It needs to start with the longest possible overlap, not the smallest.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46861094

http://stackoverflow.com/q/46796467
has answer: http://stackoverflow.com/a/46796651
upvote count: 1
has body: import random avchars = ['a','b','c','d','e','f','g'] ra = random.randint(8,24) rb = random.randint(1,7) for i in range(ra): file = open("pass","w") ac = avchars(rb) print(ac) file.write(ac) file.close() print("Done") I want to generate 8-24 characters from the list above. However, I receive the error: TypeError: 'list' object is not callable
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46796892
has title: Cant call on list object when generating from a list
score: -1
has comment: http://stackoverflow.com/comment/80539994
has comment: http://stackoverflow.com/comment/80539680
has comment: http://stackoverflow.com/comment/80539828
tagged with: random
answer count: 2
has comment: http://stackoverflow.com/comment/80539645
has comment: http://stackoverflow.com/comment/80540007
favorite count: 0
has comment: http://stackoverflow.com/comment/80539987
possible better answer: http://stackoverflow.com/a/46796892
accepted answer: http://stackoverflow.com/a/46796651
has comment: http://stackoverflow.com/comment/80539718
tagged with: python
tagged with: python-3.x
downvote count: 2

http://stackoverflow.com/q/46876459
tagged with: python
has comment: http://stackoverflow.com/comment/80699940
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46941820
type: Question
score: 0
tagged with: atom-editor
has title: Python/atom: Is there an installable package that will enable the 'raw_input()' function?
accepted answer: http://stackoverflow.com/a/46941820
answer count: 1
has comment: http://stackoverflow.com/comment/80699838
has comment: http://stackoverflow.com/comment/80709137
has body: Just looking for a package that allows the programmer to enter information after declaring a 'raw_input' function in a python program. Already have the code-running package installed for my project but am looking to expand my code. Please comment if such a package even exists! Any help is greatly appreciated.

http://stackoverflow.com/comment/80745257
has text: You need to post the code that you are having an issue with if you want a reasonable answer
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46898992
type: QuestionComment

http://stackoverflow.com/comment/81118355
has text: Well if you look at [this](http://api.mongodb.com/python/current/faq.html#id21) they indicate that this is the preferred method, as in this case each process would a function call. I guess it would also be possible to create _n_ mongo instances which are then reused.
type: AnswerComment
comment on: http://stackoverflow.com/a/46805479
score: 0
type: Comment

http://stackoverflow.com/comment/80551964
type: QuestionComment
type: Comment
has text: Using the output file, I'd like too be able to create a list of dictionaries, with each dictionary containing the 'screen_name' who sent the tweet as a key, and the 'followers_count' for each screen name as the value. But I don't know how to do that. And before that, I don't know if I am correctly writing the tweet data to a file for successful parsing.
score: 0
comment on: http://stackoverflow.com/q/46802509

http://stackoverflow.com/q/46833006
has body: import paramiko import re import getpass username=raw_input("Enter the username: ") password=getpass.getpass(prompt="Enter your password: ") client = paramiko.client.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.load_system_host_keys() client.connect(host,22,username,password) stdin, stdout, stderr= client.exec_command('cat /etc/dhcp/dhcpd.conf') I'm looking to get the output of dhcpd.conf save it to a variable to parse and get the info that I need. I know that I cant print stdout and get the information that I am looking for but I do not see another way to send it to a variable. This is in python 2.6.6 . Any help Is appreciated.
tagged with: paramiko
tagged with: python-2.6
score: 0
tagged with: ssh
answer count: 1
has answer: http://stackoverflow.com/a/46833080
tagged with: linux
type: UnansweredQuestion
tagged with: python
type: Question
has title: How would you store the output of exec_command in paramiko with python

http://stackoverflow.com/q/46796276
tagged with: python
has answer: http://stackoverflow.com/a/46796657
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/23119413
tagged with: anaconda
has body: I am trying to work with opencv 3.0 on my Mac OS 10.12.6 I am working with Anaconda in a python 3.5 environment, and have tried the following command in terminal: conda install -c jlaura OpenCV3 from the following: https://anaconda.org/search?q=platform%3Aosx-64%20opencv3 However, this ends up giving the following output/error: PackageNotFoundError: Packages missing in current channels: opencv3 -> tbb We have searched for the packages in the following channels: (This is followed by a number of links, which stack overflow will not let me post as I don't have enough rep yet) What is the best way to get opencv 3.0 on conda with a python 3.5 environment? I need this because I am trying to implement the following: https://github.com/datitran/object_detector_app Thanks
has title: Installing OpenCV 3.0 in Anaconda (Python 3.5)
tagged with: conda
has comment: http://stackoverflow.com/comment/80539449
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/42617663
has comment: http://stackoverflow.com/comment/80539365
has answer: http://stackoverflow.com/a/49217034
type: UnansweredQuestion

http://stackoverflow.com/comment/80696245
comment on: http://stackoverflow.com/q/46874594
score: 0
type: QuestionComment
type: Comment
has text: There is a definition gap between 6 and 7 km. Which speed should be taken at e.g. 6.2 or 6.7 km?

http://stackoverflow.com/comment/93275621
comment on: http://stackoverflow.com/a/46810257
type: Comment
score: 1
type: AnswerComment
has text: how do you upgrade your webdriver?

http://stackoverflow.com/q/46896765
has answer: http://stackoverflow.com/a/46897497
type: Question
score: 0
answer count: 2
tagged with: beautifulsoup
has title: Python script is only extracting the last index rather than all - Beautiful Soup
has comment: http://stackoverflow.com/comment/80740705
tagged with: python
type: UnansweredQuestion
tagged with: web-scraping
has body: The output for the code below is only giving me the stock price and name for the second url rather than both. I tried looking through the comments to see if anybody else encountered this problem but nobody else asked this question. Code is in Python 2 quote_page = ['http://www.bloomberg.com/quote/SPX:IND', 'http://www.bloomberg.com/quote/CCMP:IND'] data = [] for pg in quote_page: page = urllib2.urlopen(pg) soup = BeautifulSoup(page, 'html.parser') name_box = soup.find('h1', attrs = {'class':'name'}) name = name_box.text.strip() price_box = soup.find('div', attrs = {'class':'price'}) price = price_box.text data.append((name, price)) with open('output/stock.csv','a') as csv_file: writer = csv.writer(csv_file) for name, price in data: writer.writerow([name, price, datetime.now()])
has answer: http://stackoverflow.com/a/46902265

http://stackoverflow.com/comment/80646669
comment on: http://stackoverflow.com/q/46845477
type: QuestionComment
score: 0
has text: @lenz It does not. I have mentioned that in the question itself.
type: Comment

http://stackoverflow.com/comment/80744029
type: Comment
has text: nope, pandas DataFrame is also non-primitive, so it is passed by ref, just like list
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46898248

http://stackoverflow.com/q/46873390
upvote count: 0
possible better answer: http://stackoverflow.com/a/46873418
has comment: http://stackoverflow.com/comment/80694107
favorite count: 0
has comment: http://stackoverflow.com/comment/80694276
accepted answer: http://stackoverflow.com/a/46873419
tagged with: python
has comment: http://stackoverflow.com/comment/80694670
has answer: http://stackoverflow.com/a/46873419
type: AnsweredQuestion
has body: My task is to calculate the k-permutations from the updated List by new element without recalculating the k-permutations already gotten from the previous state of the list. Example: liste = [1, 2, 3] 3-permutations are: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1] The updated list: liste = [1, 2, 3, 4] I would like to obtain directly 3-permutations[1, 2, 3, 4]-3-permutations[1, 2, 3] without recalculating 3-permutations[1, 2, 3] Calculate directly the new permutations: [1, 2, 4], [1, 3, 4], [1, 4, 2], [1, 4, 3], [2, 1, 4], [2, 3, 4], [2, 4, 1], [2, 4, 3], [3, 1, 4], [3, 2, 4], [3, 4, 1], [3, 4, 2], [4, 1, 2], [4, 1, 3], [4, 2, 1], [4, 2, 3], [4, 3, 1], [4, 3, 2] Thanks
downvote count: 2
has answer: http://stackoverflow.com/a/46873418
has comment: http://stackoverflow.com/comment/80694131
type: Question
has comment: http://stackoverflow.com/comment/80694090
has comment: http://stackoverflow.com/comment/80694220
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80694922
score: -2
has title: generate all k-Permutations from n+1 without recalculate the k-permutations from n python 3
has comment: http://stackoverflow.com/comment/80694056
answer count: 2
has comment: http://stackoverflow.com/comment/80695099

http://stackoverflow.com/q/46799541
has comment: http://stackoverflow.com/comment/80577877
score: 0
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46415979
has body: I am attempting to build a patient database that renders the Symptom_name and Symptom_description to the document object model. Each name and description should be attached to the patient for which it was created, however each time the fields are populated and saved the Symptom_name and Symptom_description is seen in all the patients created which is not what I want. In the below image both James and Jimmy has the same Symptom_name and Symptom_description however I only clicked the James Timmerson a tag to add the Symptom_name and Symptom_description. How do I ensure that only James Timmerson has that symptom_relation data. Essentially I want to ensure the relevant symptoms connect to the relevant patients. Here is my code : models.py from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime # Create your models here. class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) First_Name = models.CharField(max_length = 80, null = True, ) Last_Name = models.CharField(max_length = 80, null = True, ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) Contact = models.CharField(max_length = 15, null = True) class Symptom_relation(models.Model): Symptom_name = models.CharField(max_length = 80, default = '') Symptom_description = models.TextField(max_length = 1000, default = '') Unique_Identity = models.ManyToManyField(Identity_unique, blank = False) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView from nesting.forms import Identity_Form, Symptom_Form from nesting.models import Identity_unique, Symptom_relation class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): …
type: Question
has comment: http://stackoverflow.com/comment/80551390
has comment: http://stackoverflow.com/comment/80553429
tagged with: django
tagged with: python
has title: Connecting the symptom name and description data to the specific patient

http://stackoverflow.com/q/46771781
tagged with: python
accepted answer: http://stackoverflow.com/a/46774347
has answer: http://stackoverflow.com/a/46774347
has body: I am using Python Networkx to build a graph and I have the following node positions as an example (positions.txt): 1 21.5 23 2 24.5 20 3 19.5 19 4 22.5 15 5 24.5 12 Node ID, X, Y. I read the file using Pandas and set the positions as node attributes in Networkx. Nodes are added using add_edge(id1, id2, weight) method in a for loop (with no self edges). So far, I have assumed that all the nodes are connected to each other by default and have not taken parameters such as Radius or Distance of nodes into consideration. Now, I want to compute a Euclidean radius or distance matrix between the nodes using these node positions, and with this matrix I want to be able to print the neighbours of a node that fall within a given radius n and save the file as a csv matrix file. A friend suggested that I use scipy's euclidean method but I have no clue how to use this to build the matrix, hence I have no starting point. I tried using ego_graph() but it did not give me the desired results. Any help is appreciated in solving my problem. Thanks in advance. (Using Ubuntu 14.04 32-bit VM and Python 2.7)
tagged with: networkx
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80490971
score: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/80491811
has comment: http://stackoverflow.com/comment/80493308
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80491975
answer count: 1
has title: Python Scipy and Networkx: How to compute a Euclidean distance matrix?
favorite count: 0
tagged with: matrix
downvote count: 1

http://stackoverflow.com/a/46832222
has comment: http://stackoverflow.com/comment/80637909
has comment: http://stackoverflow.com/comment/80613799
has comment: http://stackoverflow.com/comment/80616939
upvote count: 5
has body: Here : password.islower=="False" First, you're not calling the method - you need to add parens - so you compare a method with a string. It will never be true... Then, once you fix this: password.islower() == "False" you end up comparing a boolean with a string. It will never be true either, you want to compare with the boolean False (no quotes): password.islower() == False As a last note, this is usually spelled: not passsword.islower()
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/80612142
answers question: http://stackoverflow.com/q/46832129
type: Answer

http://stackoverflow.com/comment/80525970
comment on: http://stackoverflow.com/a/46789693
score: 0
type: AnswerComment
has text: You do not have information of what `uni_town['State']` is, you only know that it has an apply method that accepts a function as a parameter.
type: Comment

http://stackoverflow.com/comment/80535029
score: 0
has text: so, you want it to work with rdd's or dataframes??? And if for rdd's (which do not have columns, hence column names), where will be your field names (first line, perhaps?). A sample of your data will be most useful...
type: QuestionComment
comment on: http://stackoverflow.com/q/46793129
type: Comment

http://stackoverflow.com/comment/80591659
has text: `numpy.fft` is a module containing lots of variations of fft functions. You want `numpy.fft.fft()`.
comment on: http://stackoverflow.com/q/46822073
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/80692371
has text: @tahsin314 you didn't provide the full code. Most essential part is missing. How is `logits` defined?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46871302
score: 0

http://stackoverflow.com/a/46893450
has comment: http://stackoverflow.com/comment/80734575
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80735692
has body: i % n = k will be a either: k if k &lt; n [] empty that is, if k &gt; n This is because i varies from 0 to n Hence there will be only one or no elements. For clarity: n = 50; print([i%n for i in range(n)]) , gives: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] That is, unique values between 0 to n-1
type: Answer
answers question: http://stackoverflow.com/q/46892857
has comment: http://stackoverflow.com/comment/80734489

http://stackoverflow.com/a/46853943
has body: You could add the optional parameters on numpy.where(condition[, x, y]) to keep the same array size. When True, yield x, otherwise yield y https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html To compare to the answer from @Zulfiqaar, the solution would be np.where(array1 &lt; 3, array1 ** 2, array1 / 3) Note that the condition is just a bool array, so you can combine multiple conditions at once using binary operators. For instance comparing to another array: array2 = np.random.randint(1, 11, 10) &gt;&gt;&gt; array2 Out[]: array([ 6, 1, 6, 2, 10, 4, 9, 10, 3, 3]) &gt;&gt;&gt; np.where((array1 &lt; 3) &amp; (array1 &gt; 5), array1 ** 2, array1 / 3) Out[]: array([ 0.33333333, 4. , 1. , 1.33333333, 1.66666667, 2. , 2.33333333, 2.66666667, 3. , 3.33333333])
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46852462
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80729637
score: 3
answers question: http://stackoverflow.com/q/46852462

http://stackoverflow.com/comment/80636735
comment on: http://stackoverflow.com/q/46844263
score: 0
type: QuestionComment
has text: yes... in simple.. i get some json data after some operations, i want to create a filename.json file in S3 and write that json to this file.
type: Comment

http://stackoverflow.com/a/46812260
type: AcceptedAnswer
downvote count: 0
has body: There's options like py2exe that just package the scripts into a Microsoft executable (files can exist inside Microsoft executables), or pyinstaller. However, Python's runtime and language specification is not designed to be converted to machine code. If it's not okay to distribute your program as a pyinstaller/py2exe package, then you should look towards compiled programming languages. Previously asked here How to compile python script to binary executable
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46811800
score: 1
has comment: http://stackoverflow.com/comment/80577157
accepted answer of: http://stackoverflow.com/q/46811800
has comment: http://stackoverflow.com/comment/80572371

http://stackoverflow.com/comment/80671414
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46861252
score: 0
has text: One quick question. Is it possible for a serializer to `exclude` some fields from GET and include/optional in POST request?

http://stackoverflow.com/a/46855962
score: 2
has comment: http://stackoverflow.com/comment/80659624
downvote count: 0
upvote count: 2
has body: Sometimes you'll encounter objects that look like a normal dict when printed, but really aren't. This is especially common in web frameworks. Try converting it to a normal dict that the json module knows how to serialize like: ask_session = dict(ask_session) One problem that may occur is if you have a nested data structure. In that case it might be good to add a custom encoder for that type. See for example: https://stackoverflow.com/a/3768975/982257 It may not be necessary though. Flask has a built-in utility function called jsonify that knows how to handle a lot of types that show up in Flask. I haven't tested it in this case, but I almost always use it when I'm writing Flask apps.
answers question: http://stackoverflow.com/q/46855071
has comment: http://stackoverflow.com/comment/80659652
type: Answer

http://stackoverflow.com/comment/80579592
has text: Sorry I can't help you with your coding problem. But about the disappeared "<" and ">": you have to write "&lt;" and "&gt;" instead, like I did when editing your question, see this link for [more information on markup](https://stackoverflow.com/help/formatting). BTW you can always edit your own question: click on the small "edit" beneath the `python`and `canvas`tags.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46815433

http://stackoverflow.com/q/46846794
has comment: http://stackoverflow.com/comment/80641709
duplicate of: http://stackoverflow.com/q/6244382
score: 1
type: Question
has title: Django: can't reset superuser password if not set at installation
linked to: http://stackoverflow.com/q/6244382
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80643699
favorite count: 0
tagged with: reset-password
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/80642253
has body: I'm deploying Django automatically. I create a superuser at installation with the command : python manage createsuperuser --username me --email me@example.org --noinput When I do this no password is set for the account and I'm not able to change the password with the "Forget password" functionality. If I do : python manage changepassword me Then I can reset the password. This behavior comes from this code : return (u for u in active_users if u.has_usable_password()) What would be the way to "activate" the reset function for all users without hacking the core ?
has comment: http://stackoverflow.com/comment/80641621
has comment: http://stackoverflow.com/comment/80641375

http://stackoverflow.com/comment/80653694
has text: @C8H10N4O2 I want a one (or an x) day lag
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46851293

http://stackoverflow.com/comment/80682989
type: AnswerComment
score: 0
type: Comment
has text: Aha I should have thought of that earlier. Exactly what I was looking for.
comment on: http://stackoverflow.com/a/46867828

http://stackoverflow.com/q/46819728
score: 1
has body: I have a folder which contains .py scripts and each contains a same variable which I need in other script if that certain script is used from that folder. folder_x main.py folder_y script1.py script2.py script3.py So all the scripts are not used at the same time just one of them. I found this solution https://stackoverflow.com/a/35524184/5708537 And it works well but I have to list all the scripts manually. I thought that I automate this and make a list of the files, and strip down the .py ending: path = '/home/folder_x/folder_y' files = os.listdir(path) module_list = [i for i in files if i.endswith('.py')] module_list = [os.path.splitext(x)[0] for x in module_list] Works like a charm. But this part of the code still thinks that the scripts are in folder_x variables = {} for mod_name in module_list: mod = import_module(mod_name) variables[mod_name] = getattr(mod, 'var') So how can I tell to that the scripts are in folder_y and take that variable from those? Or is there a better way to list scripts/modules from another folder, and get a variable from each of those?
tagged with: loops
tagged with: import
type: Question
tagged with: variables
has answer: http://stackoverflow.com/a/46819948
linked to: http://stackoverflow.com/q/35523396
upvote count: 1
answer count: 1
downvote count: 0
has title: Importing a same variable from multiple libraries from different folder
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80759186
type: QuestionComment
comment on: http://stackoverflow.com/q/46905576
score: 0
has text: @MaartenFabré sorry, you are correct. 6:30 should be removed too.
type: Comment

http://stackoverflow.com/q/46848408
type: UnansweredQuestion
has body: I have a QGraphicsItem that the user can drag around. I want to keep the item in the upper right quadrant of my scene, so I overrode mouseMoveEvent like this: def mouseMoveEvent(self, event): if self.x() &lt; 0: self.setPos(0, self.y()) if self.y() + self.rect().height() &gt; 0: self.setPos(self.x(), -self.rect().height()) Works like a charm, so far so good. Now I use the itemChanged to kick off calculations when the item moves. Although I made my item stand still when it reaches my defined boundary, itemChanged gets called also when my mouse is in the 'forbidden zone', which is understandable. I would like to block this behavior based on the above checks. Since QGraphicsItem is not a QObject, blockSignals does not work here. Any idea how I can achieve this?
tagged with: signals
tagged with: qgraphicsview
type: Question
tagged with: python
tagged with: qt
has answer: http://stackoverflow.com/a/46854486
has comment: http://stackoverflow.com/comment/80644403
score: 0
has title: Preeventing QGraphicsItem's itemChanged
answer count: 1

http://stackoverflow.com/q/46893060
has answer: http://stackoverflow.com/a/46893173
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/3862310
has body: Is there a function that takes a class as a parameter and returns True or False depending on the existence of its children classes? Can it be possible in principle? class A: pass class B(A): pass has_children(A) # should return True has_children(B) # should return False I would like to know a solution without access to globals(), locals(), vars().
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46893173
has title: How do I check whether a class has children classes in Python?
type: Question
upvote count: 4
downvote count: 0
score: 4
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/80734324
linked to: http://stackoverflow.com/q/3862310
tagged with: python
favorite count: 0

http://stackoverflow.com/q/46885938
has comment: http://stackoverflow.com/comment/80719130
favorite count: 0
accepted answer: http://stackoverflow.com/a/46886022
has body: def Check_InActive(Policy_Name): with open ('Inactive_Policy_list.txt','r+') as p: for word in p: if (Policy_Name == word): print (Policy_Name,word) return "Inactive" else: return "Active" Policy = raw_input("Enter Policy Name: ") Check_InActive(Policy) Flag = Check_InActive() if (Flag in "Inactive"): print(Policy,"is ",Flag) Can someone help me below error. ## Flag = Check_InActive() ## TypeError: Check_InActive() takes exactly 1 argument (0 given)
upvote count: 1
tagged with: python
type: AnsweredQuestion
downvote count: 3
type: Question
has title: python : TypeError: () takes exactly 1 argument (0 given)
answer count: 2
score: -2
has answer: http://stackoverflow.com/a/46886022
has answer: http://stackoverflow.com/a/46885986
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80719239
has comment: http://stackoverflow.com/comment/80719183
possible better answer: http://stackoverflow.com/a/46885986

http://stackoverflow.com/q/46795186
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46795233
has title: Standardize values in a data-frame column
possible better answer: http://stackoverflow.com/a/46795653
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/46795653
tagged with: python
has body: I have a dataframe df which looks like: id colour response 1 blue curent 2 red loaning 3 yellow current 4 green loan 5 red currret 6 green loan You can see the values in the response column are not uniform and I would like to get the to snap to a standardized set of responses. I also have a validation list validate which looks like validate current loan transfer I would like to standardise the response column in the df based on the first three characters in the entry against the validate list So the eventual output would look like: id colour response 1 blue current 2 red loan 3 yellow current 4 green loan 5 red current 6 green loan have tried to use fnmatch pattern = 'cur*' fnmatch.filter(df, pattern) = 'current' but can't change the values in the df. If anyone could offer assistance it would be appreciated Thanks
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/46795233

http://stackoverflow.com/a/52716468
has body: The problem is the double backslash as others have said. You want to escape both of the backslashes, for example: bad_str = '{"a" : "C:\\ b"}' good_str = '{"a" : "C:\\\\ b"}' #JSONDecodeError print(json.loads(bad_str)) # OK print(json.loads(good_str))
answers question: http://stackoverflow.com/q/46752466
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/80488911
has text: Thanks, my intuition was also telling me that a tuple sounds right, but I was (a) ignorant of the map/operator -like stuff you can do and (b) as you say, a bit put off by the fact that I can’t do tuple_coord[0] = 12. But I am starting to think that this inconvenience kind-of reflects the nature of coordinates in that they are related, and if an operation could change the one it could almost always potentially change the other.
score: 1
comment on: http://stackoverflow.com/a/46754359
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46801338
upvote count: 1
type: Answer
has body: The self.finished = True executes in another process and only changes the variable in that process, but you are printing the value from the main process. You need variables that are shared. from multiprocessing import Process,Value from ctypes import c_bool class test(Process): def __init__(self,name): super().__init__() self.name = name self._finished = Value(c_bool,False) def run(self): print(self.name,'executed') self._finished.value = True @property def finished(self): return self._finished.value if __name__ == '__main__': test_list = [test('first'), test('second')] for t in test_list: t.start() for t in test_list: t.join() for t in test_list: print(t.finished)
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46801284

http://stackoverflow.com/comment/80518164
type: Comment
comment on: http://stackoverflow.com/a/46772919
has text: @JanZeiseweis: This is what I am looking for. I am working on Python 2.7 and sadly html dont have escape and unescaped in for python 2.7
score: 0
type: AnswerComment

http://stackoverflow.com/q/46845052
has comment: http://stackoverflow.com/comment/80638025
upvote count: 0
has comment: http://stackoverflow.com/comment/80667160
favorite count: 0
has body: I am writing a code that read a large text file line by line and find the line that starts with UNIQUE-ID (there are many of them in the file) and it comes right before a certain line (in this example, the one that starts with 'REACTION-LAYOUT -' and in which the 5th element in the string is OLEANDOMYCIN). The code is the following: data2 = open('pathways.dat', 'r', errors = 'ignore') pathways = data2.readlines() PWY_ID = [] line_cont = [] L_PRMR = [] #Left primary car = [] #i is the line number (first element of enumerate), #while line is the line content (2nd elem of enumerate) for i,line in enumerate(pathways): if 'UNIQUE-ID' in line: line_cont = line PWY_ID_line = line_cont.rstrip() PWY_ID_line = PWY_ID_line.split(' ') PWY_ID.append(PWY_ID_line[2]) elif 'REACTION-LAYOUT -' in line: L_PWY = line.rstrip() L_PWY = L_PWY.split(' ') L_PRMR.append(L_PWY[4]) elif 'OLEANDOMYCIN' in line: car.append(PWY_ID) print(car) However, the output is instead all the lines that contain PWY_ID (output of the first if statement), like it was ignoring all the rest of the code. Can anybody help? Edit Below is a sample of my data (there are like 1000-ish similar "pages" in my textfile): // UNIQUE-ID - PWY-741 . . . . PREDECESSORS - (RXN-663 RXN-662) REACTION-LAYOUT - (RXN-663 (:LEFT-PRIMARIES CPD-1003) (:DIRECTION :L2R) (:RIGHT-PRIMARIES CPD-1004)) REACTION-LAYOUT - (RXN-662 (:LEFT-PRIMARIES CPD-1002) (:DIRECTION :L2R) (:RIGHT-PRIMARIES CPD-1003)) REACTION-LAYOUT - (RXN-661 (:LEFT-PRIMARIES CPD-1001) (:DIRECTION :L2R) (:RIGHT-PRIMARIES CPD-1002)) REACTION-LIST - RXN-663 REACTION-LIST - RXN-662 REACTION-LIST - RXN-661 SPECIES - TAX-351746 SPECIES - TAX-644631 SPECIES - ORG-6335 SUPER-PATHWAYS - PWY-5266 TAXONOMIC-RANGE - TAX-1224 //
accepted answer: http://stackoverflow.com/a/46845245
has comment: http://stackoverflow.com/comment/80645068
tagged with: python
has title: Python extracting specific line in text file
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46845183
has answer: http://stackoverflow.com/a/46845183
tagged with: tex
downvote count: 1
tagged with: line
has comment: http://stackoverflow.com/comment/80637681
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/80637704
has answer: http://stackoverflow.com/a/46845245
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/80637666

http://stackoverflow.com/q/46902334
tagged with: python
has comment: http://stackoverflow.com/comment/80751418
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46902860
has comment: http://stackoverflow.com/comment/80751374
downvote count: 3
type: Question
upvote count: 0
has body: i would like to extract the salary and the currency. A= "my name is adam. expected salary usd 5000 USD test test " B= "my name is sara. expected salary 8200 MYR test tessksjdkjs " C= "my name is sara. expected salary IDR 999944 and iam ksdjfjksdh " how can i search find the expected salary and the currency. The expected results: A= salary 5000 CURRENCY USD B= salary 8200 CURRENCY MYR C= salary 999944 CURRENCY IDR
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46902860
answer count: 1
has title: search text value then find a number
favorite count: 0
score: -3

http://stackoverflow.com/q/46801983
has body: I am running a Neural Network algorithm on a dataset but am running into errors.I am not sure what this error means or how to fix it. The dataset is simply 1 0 1 0 1 0 and so forth where the third column would be the category that I am classifying. My code is below: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import urllib import tensorflow as tf import numpy as np Stock_TRAINING = "Stocks.csv" Stock_TEST = "Workbook2.csv" # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv_with_header( filename=Stock_TRAINING, target_dtype=np.int, features_dtype=np.int) test_set = tf.contrib.learn.datasets.base.load_csv_with_header( filename=Stock_TEST, target_dtype=np.int, features_dtype=np.int) # Specify that all features have real-value data feature_columns = [tf.feature_column.numeric_column("x", shape=[2])] # Build 3 layer DNN with 10, 20, 10 units respectively. classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=2, model_dir="/tmp/stocks") # Define the training inputs train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(training_set.data)}, y=np.array(training_set.target), num_epochs=None, shuffle=True) # Train model. classifier.train(input_fn=train_input_fn, steps=2000) # Define the test inputs test_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(test_set.data)}, y=np.array(test_set.target), num_epochs=1, shuffle=False) # Evaluate accuracy. accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"] print("\nTest Accuracy: {0:f}\n".format(accuracy_score)) # Classify two new stock samples. new_samples = np.array( [[1, 0], [1,1] [0,0], [0,1], [1, 1]], dtype=np.float32) predict_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": new_samples}, num_epochs=1, shuffle=False) predictions = list(classifier.predict(input_fn=predict_input_fn)) predicted_classes = [p["UpDown"] for p in pr…
tagged with: python
has comment: http://stackoverflow.com/comment/80553009
answer count: 0
type: UnansweredQuestion
has title: Tensor flow Neural Network error
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/80561008
score: 0
tagged with: scikit-learn

http://stackoverflow.com/a/46863771
score: 4
type: Answer
has body: The usual way to do this is with a list comprehension, iterating directly over the list items, not indirectly via an index. mylist = [1, 2, 3, 4, 5] mylist = [2 * num for num in mylist] print(mylist) output [2, 4, 6, 8, 10] That replaces mylist with a new list object. That's generally ok, but sometimes you want to modify the existing object, eg when other objects have a reference to mylist. You can do that with a slice assignment. mylist[:] = [2 * num for num in mylist]
accepted answer of: http://stackoverflow.com/q/46863682
answers question: http://stackoverflow.com/q/46863682
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80484336
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46768828
has text: @kengu in every iteration of `for` loop, variable `sep` gets a new value from freshly read line, so the former line is forgotten.

http://stackoverflow.com/comment/89743045
comment on: http://stackoverflow.com/a/46842894
has text: this doesn't work for me. After the click, I use `driver.execute_script("window.history.go(-1)") ` to go back to the previous page. I got **"IndexError: list index out of range"** when click the next item.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80726616
has text: I want to plot the column from each df with the same name on the same plot.
comment on: http://stackoverflow.com/q/46875336
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46896502
has title: "hdfs: command not found" when trying to execute command "hdfs namenode -format" during hadoop installation
favorite count: 0
has body: Complete error statement : No command 'hdfs' found, did you mean: Command 'hfs' from package 'hfsutils-tcltk' (universe) Command 'hdfls' from package 'hdf4-tools' (universe) hdfs: command not found
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/75995170
has comment: http://stackoverflow.com/comment/80741292
has answer: http://stackoverflow.com/a/54589419
upvote count: 3
tagged with: java
has answer: http://stackoverflow.com/a/58579491
type: Question
has comment: http://stackoverflow.com/comment/80740208
tagged with: hadoop
has answer: http://stackoverflow.com/a/46912585
score: 3
has answer: http://stackoverflow.com/a/46897114
downvote count: 0

http://stackoverflow.com/comment/80571734
comment on: http://stackoverflow.com/q/46811800
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [How to compile python script to binary executable](https://stackoverflow.com/questions/12339671/how-to-compile-python-script-to-binary-executable)

http://stackoverflow.com/q/46864911
has title: WM_GETTEXT returns text separated with nulls
upvote count: 1
favorite count: 0
has body: import time import win32gui import win32con while True: time.sleep(1) buf = win32gui.PyMakeBuffer(255) window = win32gui.GetForegroundWindow() title = win32gui.GetWindowText(window) control = win32gui.FindWindowEx(window, 0, 'Edit', None) length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buf) result = buf[:length] print('Title: ', win32gui.GetWindowText(window)) print(str(buf[:length*2], "UTF_8") Why it returns string separated with nulls? When I've tried just buff[:length] I had half of my string because of that nulls bytearray(b'H\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x9dL\x03E\x888P\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\xedL\x03\xa9\xc4\xffb\xa0\tO\x00j\x8c\x1bZ\xa04\xc6\x02IP\x12\x8d\x00\x00\x00\x00\x00\x00\x00\x00\xa0X?\x03\xed`\x05\x89\xa0n\xfb\x02.\x02\xea\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0*X\x00\xf4b\x9c\xf9\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd6\x8d\x02\x98?n\xb2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00D\xcc\x02\xbey\xee\x08\x00\x00\x00\x00\x00\x00\x00') edit: result = buf.tobytes()[:length*2:2] print(result.decode("UTF-8")) The code follow work as I wanted but I'm not sure It has been written correctly
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/46865972
tagged with: win32gui
type: Question
has answer: http://stackoverflow.com/a/46865972
answer count: 1

http://stackoverflow.com/a/46820915
answers question: http://stackoverflow.com/q/46820625
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/80617857
score: -1
has comment: http://stackoverflow.com/comment/80612426
has body: First find the right version of python you want to use: $ which -a python3.6 /usr/bin/python3.6 then invoke that instance of python directly, e.g. $ /usr/bin/python3.6 -m venv usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] ENV_DIR [ENV_DIR ...] venv: error: the following arguments are required: ENV_DIR Next, pip does not create virtual environments. The module venv does. Read the venv documentation for recommended usage. In your case, you might want: $ /usr/bin/python3.6 -m venv myenv
has comment: http://stackoverflow.com/comment/80617336
type: Answer

http://stackoverflow.com/comment/80497896
type: QuestionComment
comment on: http://stackoverflow.com/q/46775963
has text: @Barmar The aim would be to contain a POST command to an API inside the loop, so that after each json is created it is posted and then the next one is created and posted etc. until the bottom of the csv has been hit.
score: 0
type: Comment

http://stackoverflow.com/a/46773488
upvote count: 1
has comment: http://stackoverflow.com/comment/80494661
has comment: http://stackoverflow.com/comment/80494797
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80494731
accepted answer of: http://stackoverflow.com/q/46772790
score: 1
answers question: http://stackoverflow.com/q/46772790
has body: You can change the alignment of each item using the QTableWidgetItem's setTextAlignment() method: item = self.myTable.item(i, j) item.setTextAlignment(QtCore.Qt.AlignCenter) But if you want to change the alignment to all the items you must use a delegate: class AlignDelegate(QtGui.QItemDelegate): def paint(self, painter, option, index): option.displayAlignment = QtCore.Qt.AlignCenter QtGui.QItemDelegate.paint(self, painter, option, index) class MyClass(your_widget, your_design) def __init__(self): super(myClass, self).__init__() # SETUP UI self.setupUi(self) # Table setup self.myTable.verticalHeader().hide() # Hide row numbers self.myTable.setColumnCount(4) self.myTable.setHorizontalHeaderLabels(['A', 'B', 'C', 'D']) self.myTable.horizontalHeader().setResizeMode(QHeaderView.Stretch) self.myTable.setItemDelegate(AlignDelegate())
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80494986
has comment: http://stackoverflow.com/comment/80494845
has comment: http://stackoverflow.com/comment/80495098

http://stackoverflow.com/a/65163639
answers question: http://stackoverflow.com/q/46792595
upvote count: 2
score: 2
has body: Had the same issue. I resolved it by another jupyter version. For me it did not work in the classic juypter notebook. I installed jupyterlab -&gt; pip install jupyterlab and start it with: jupyter-lab. Summary: pip install jupyterlab jupyter-lab Then it worked!
has comment: http://stackoverflow.com/comment/125763019
downvote count: 0
type: Answer

http://stackoverflow.com/a/55173445
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/110463287
answers question: http://stackoverflow.com/q/46805662
has body: Just ran into the same error. In my case the problem was I accessed serializer.data before doing serializer.save(). Google dropped me here, so maybe someone else will also find this helpful. Source: https://github.com/encode/django-rest-framework/issues/2964
score: 17
type: Answer
upvote count: 17
has comment: http://stackoverflow.com/comment/110463241
accepted answer of: http://stackoverflow.com/q/46805662

http://stackoverflow.com/comment/80479529
comment on: http://stackoverflow.com/a/46766378
type: AnswerComment
score: 0
type: Comment
has text: nothing happened (no error), I just put them after list.append(tag.text)

http://stackoverflow.com/comment/80595414
score: 0
type: AnswerComment
has text: `random.sample` function mentions already `Return a k length list of unique elements chosen from the population sequence` [Random](https://docs.python.org/2/library/random.html). You could you choice instead if multiple picks are allowed.
type: Comment
comment on: http://stackoverflow.com/a/46823319

http://stackoverflow.com/comment/80630062
type: QuestionComment
has text: hi @RonNorris, thanks for the pick up! I'm currently very new to Python and just trying to get as much help as I can. Will make sure to get a more complete script up and running before asking more questions haha
type: Comment
comment on: http://stackoverflow.com/q/46822951
score: 0

http://stackoverflow.com/a/46857565
score: 0
answers question: http://stackoverflow.com/q/46857500
type: Answer
has body: You should not remove elements from a list that you are iterating over with for. Your guess is close -- you can see more clearly what's happening if you use a longer list: a = [1,2,3,4,5] for x in a: print x a.remove(x) print a output: 1 [2, 3, 4, 5] 3 [2, 4, 5] 5 [2, 4] It prints the element at index 0, then index 1, then index 2... and by then there is no index 3. In your example it prints the element at index 1, then there is no index 2.

http://stackoverflow.com/q/46897468
answer count: 3
tagged with: python
has title: Python - Scrabble_score
has comment: http://stackoverflow.com/comment/80742167
has answer: http://stackoverflow.com/a/46897541
has comment: http://stackoverflow.com/comment/80743737
type: UnansweredQuestion
has body: Can someone break down the individual components that make up scrabble_score: score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, "x": 8, "z": 10} def scrabble_score(word): return sum([score[x] for x in word.replace(" ", "").lower() if x in score])
has comment: http://stackoverflow.com/comment/80742182
has answer: http://stackoverflow.com/a/46897634
has answer: http://stackoverflow.com/a/49162571
type: Question
score: 0

http://stackoverflow.com/a/46853001
has comment: http://stackoverflow.com/comment/80653822
answers question: http://stackoverflow.com/q/46852951
accepted answer of: http://stackoverflow.com/q/46852951
has body: You can use __in: objects = Games.objects.filter(...)[:5] items = Games.objects.exclude(pk__in=objects) Some databases may not let you use a limit in a subquery. In that case, you can covert the objects queryset to a list: objects = list(Games.objects.filter(...)[:5]) items = Games.objects.exclude(pk__in=objects) Note that in Django it's recommended to use the singular Game for your model name.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/80687359
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46869898
has text: @MuhammedEltabakh Fortunately for you, `ast` will convert it back. See my edit for a demo.

http://stackoverflow.com/a/46811064
score: 0
upvote count: 1
downvote count: 1
has body: Try this. You need to process the rest according to your need. Here is the gist part. It produces below results: import requests url = "http://nxsa.esac.esa.int/nxsa-sl/servlet/observations-metadata?RESOURCE_CLASS=OBSERVATION&amp;ADQLQUERY=SELECT%20DISTINCT%20OBSERVATION.OBSERVATION_OID,OBSERVATION.MOVING_TARGET,OBSERVATION.OBSERVATION_ID,EPIC_OBSERVATION_IMAGE.ICON,EPIC_OBSERVATION_IMAGE.ICON_PREVIEW,RGS_FLUXED_OBSERVATION_IMAGE.ICON,RGS_FLUXED_OBSERVATION_IMAGE.ICON_PREVIEW,EPIC_MOVING_TARGET_OBSERVATION_IMAGE.ICON,EPIC_MOVING_TARGET_OBSERVATION_IMAGE.ICON_PREVIEW,RGS_FLUXED_MOVING_TARGET_OBSERVATION_IMAGE.ICON,RGS_FLUXED_MOVING_TARGET_OBSERVATION_IMAGE.ICON_PREVIEW,OM_OBSERVATION_IMAGE.ICON_PREVIEW_V,OM_OBSERVATION_IMAGE.ICON_PREVIEW_B,OM_OBSERVATION_IMAGE.ICON_PREVIEW_L,OM_OBSERVATION_IMAGE.ICON_PREVIEW_U,OM_OBSERVATION_IMAGE.ICON_PREVIEW_M,OM_OBSERVATION_IMAGE.ICON_PREVIEW_S,OM_OBSERVATION_IMAGE.ICON_PREVIEW_W,OM_OBSERVATION_IMAGE.ICON_V,OM_OBSERVATION_IMAGE.ICON_B,OM_OBSERVATION_IMAGE.ICON_L,OM_OBSERVATION_IMAGE.ICON_U,OM_OBSERVATION_IMAGE.ICON_M,OM_OBSERVATION_IMAGE.ICON_S,OM_OBSERVATION_IMAGE.ICON_W,OBSERVATION.REVOLUTION,OBSERVATION.PROPRIETARY_END_DATE,OBSERVATION.RA_NOM,OBSERVATION.DEC_NOM,OBSERVATION.POSITION_ANGLE,OBSERVATION.START_UTC,OBSERVATION.END_UTC,OBSERVATION.DURATION,OBSERVATION.TARGET,PROPOSAL.TYPE,PROPOSAL.CATEGORY,PROPOSAL.AO,PROPOSAL.PI_FIRST_NAME,PROPOSAL.PI_SURNAME,TARGET_TYPE.DESCRIPTION,OBSERVATION.LII,OBSERVATION.BII,OBSERVATION.ODF_VERSION,OBSERVATION.PPS_VERSION,OBSERVATION.COORD_OBS,OBSERVATION.COORD_TYPE%20FROM%20FIELD_NOT_USED%20%20WHERE%20OBSERVATION.PROPRIETARY_END_DATE%3E%272017-10-18%27%20%20AND%20%20(PROPOSAL.TYPE=%27Calibration%27%20OR%20PROPOSAL.TYPE=%27Int%20Calibration%27%20OR%20PROPOSAL.TYPE=%27Co-Chandra%27%20OR%20PROPOSAL.TYPE=%27Co-ESO%27%20OR%20PROPOSAL.TYPE=%27GO%27%20OR%20PROPOSAL.TYPE=%27HST%27%20OR%20PROPOSAL.TYPE=%27Large%27%20OR%20PROPOSAL.TYPE=%27Large-Joint%27%20OR%20PROPOSAL.TYPE=%27Triggered%27%20OR%20PROPO…
type: Answer
has comment: http://stackoverflow.com/comment/80569541
answers question: http://stackoverflow.com/q/46792079
has comment: http://stackoverflow.com/comment/80569550

http://stackoverflow.com/comment/80579216
type: Comment
has text: I did not ask the question. I was merely interested in the answer :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46802764

http://stackoverflow.com/comment/80783381
has text: Ok, I get it now. If I use "from autoload import *" it works without the "autoload" prefix. If I use "import autoload" then I need to prefix any of its parameters with "autoload". This solves my other query on global variables. Thanks.
comment on: http://stackoverflow.com/a/46899360
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46882773
answer count: 2
has answer: http://stackoverflow.com/a/46882872
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52663493
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has title: AttributeError: 'module' object has no attribute '_create_unverified_context'
type: Question
score: 1
tagged with: ssl
has body: I got the following error AttributeError: 'module' object has no attribute '_create_unverified_context'. I'm using Python 3.4.2 . My code: import ssl ssl._create_default_https_context = ssl._create_unverified_context When I run this code, the error happens._create_unverified_context can be used in Python 3.4.2, so I really cannot understand why this error happens. How should I fix this? Traceback says Traceback (most recent call last): File "quickstart.py", line 3, in &lt;module&gt; ssl._create_default_https_context = ssl._create_unverified_context() AttributeError: 'module' object has no attribute '_create_unverified_context'

http://stackoverflow.com/comment/80610443
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46831437
has text: @ChetanVasudevan i ve updated. Sorry for missing information.

http://stackoverflow.com/a/46779858
answers question: http://stackoverflow.com/q/46764974
score: 0
has body: Based on the error and problem description, it sounds like your Luigi scheduler is running from a different Python environment/interpreter than the one used when calling a new process via os or subprocess It's been a while since I've used Luigi, but if your Luigi task dependency resolution involves inspection of a target that is defined in one of these packages, you generally want to have the task and target be importable and natively callable by your master task; this enables the graph of the originally called master task to be more easily seen against its Luigi task dependences, which may also have unsatisfied dependencies of their own. You can address this by ensuring that all of your package requirements are installed and available to the same Python interpreter running your Luigi scheduler.
type: Answer

http://stackoverflow.com/a/46831849
type: Answer
answers question: http://stackoverflow.com/q/46831733
upvote count: 2
score: 2
downvote count: 0
has body: You need to use re.search() instead of re.match() ! Your regex should check for one or more(+) than one special characters as re.search("[^a-zA-Z0-9]+", Numb) Checking for one or more will check for any match with zero or more special character which is not the intended one in your problem! Sample IO: &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","2343") #false &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","2343$") #true &lt;_sre.SRE_Match object at 0x7fdcbaed07e8&gt; &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","2343$3534") #true &lt;_sre.SRE_Match object at 0x7fdcbaed08b8&gt; &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","2345$$$43") #true &lt;_sre.SRE_Match object at 0x7fdcbaed07e8&gt; &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","34dsf") #false &gt;&gt;&gt; re.search("[^a-zA-Z0-9]+","fdsf") #false

http://stackoverflow.com/comment/80746887
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46850902
has text: Maybe it’s related to your/mine version of MS Excel. But I definitely could open it, in spite of the fact the file is clearly faulty.
score: 0

http://stackoverflow.com/comment/80510900
score: 0
type: QuestionComment
type: Comment
has text: And what is the problem? what have you tried to solve it?
comment on: http://stackoverflow.com/q/46782289

http://stackoverflow.com/comment/80623569
type: Comment
type: QuestionComment
has text: I'm not familiar enough with python to answer directly. What you want in other languages would be called a "detached process". Search for that in python and see what turns up
comment on: http://stackoverflow.com/q/46837914
score: 0

http://stackoverflow.com/q/46864680
has body: Why is the virtualenvwrapper mkproject command is not working in Windows 10? And what file do you edit for shell startup in Windows 10 to setup virtualenvwrapper?
has answer: http://stackoverflow.com/a/46867916
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: virtualenvwrapper
type: Question
accepted answer: http://stackoverflow.com/a/46867916
answer count: 2
possible better answer: http://stackoverflow.com/a/47361363
has answer: http://stackoverflow.com/a/47361363
downvote count: 0
tagged with: windows-10
has title: virtualenvwrapper mkproject and shell startup in windows issue?
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/80701275
comment on: http://stackoverflow.com/q/46877090
type: Comment
type: QuestionComment
has text: I could not see you importing Honeyword anywhere? And that is causing the error.
score: 1

http://stackoverflow.com/comment/80461341
type: Comment
type: AnswerComment
has text: The output is the same as before. Did it work for you? Out[9]: Empty DataFrame Columns: [] Index: [1,10333338573885 1,0200000484474 1,7133334147123 -8,35449504852295 69,9546737670898 1,10333338573885 1,0200000484474 1,7133334147123 0,206773042678833, 1,10666671923051 1,02333338193906 1,71666674820396
score: 0
comment on: http://stackoverflow.com/a/46756283

http://stackoverflow.com/comment/80593159
comment on: http://stackoverflow.com/a/46804012
score: 0
type: AnswerComment
type: Comment
has text: Hi and thanks a lot for the help, the sent interger was 0, so I will have to do a bit of research on the original byte's encoding

http://stackoverflow.com/comment/80603244
type: Comment
comment on: http://stackoverflow.com/a/46827834
type: AnswerComment
has text: I know that, but does it creates the file with the filename in the server and if so in which path does it creates and why am I getting file not found error?
score: 0

http://stackoverflow.com/q/46775023
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/36994414
linked to: http://stackoverflow.com/q/15680463
has comment: http://stackoverflow.com/comment/80504361
has title: Find the default local Jupyter directory
has body: I need the location of jupyter's local directory to use in another script. For example, when starting jupyter, the console prints: &gt; Serving notebooks from local directory: C:\Users\PC\Documents Somehow, jupyter has set this path as the default local location from which my notebooks are served. It is the "root" of my jupyter environment. How do I find this default setting? Is there a pre-existing file I can parse, or a command I can type? Among other attempts, I've tried the following: &gt; jupyter notebook --help-all --NotebookApp.notebook_dir=&lt;Unicode&gt; Default: '' The directory to use for notebooks and kernels. Note: I do not have a config file, nor do I not wish to generate a config file to get this information. For clarity, I am not concerned with changing the directory.
has comment: http://stackoverflow.com/comment/80498914
answer count: 1
tagged with: jupyter
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/39252884
has answer: http://stackoverflow.com/a/46780435
accepted answer: http://stackoverflow.com/a/46780435

http://stackoverflow.com/a/46828700
type: Answer
has body: That's because of the default behavior of print(). You can pass argument sep to override default seperator. print(s1, s2, s3, sep='') this code will help you. See the document in python interpreter with help(print)
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46828643
upvote count: 1

http://stackoverflow.com/a/46876886
answers question: http://stackoverflow.com/q/46874689
has comment: http://stackoverflow.com/comment/80736551
type: AcceptedAnswer
downvote count: 0
has body: The problem you run into is that the text bounding box is expanded to host the complete rotated text, but that box itself is still defined in cartesian coordinates. The picture below shows two texts with horizontalalignment "left" and vertical alignment "bottom"; the problem is that the rotated text has its bounding box edge much further away from the text. What you want is rather to have the text rotate about an edge point of its own surrounding as below. This can be achieved using the rotation_mode="anchor" argument to matplotlib.text.Text, which steers exactly the above functionality. ax.text(..., rotation_mode="anchor") In this example: from matplotlib import pyplot as plt import numpy as np lObjectsALLcnts = [1, 1, 1, 2, 2, 3, 5, 14, 15, 20, 32, 33, 51, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 6, 7, 7, 10, 10, 14, 14, 14, 17, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 5, 5, 6, 14, 14, 27, 27, 1, 1, 2, 3, 4, 4, 5] lObjectsALLlbls = ['DuctPipe', 'Column', 'Protrusion', 'Tree', 'Pole', 'Bar', 'Undefined', 'EarthingConductor', 'Grooves', 'UtilityPipe', 'Cables', 'RainPipe', 'Moulding', 'Intrusion', 'PowerPlug', 'UtilityBox', 'Balcony', 'Lighting', 'Lock', 'Doorbell', 'Alarm', 'LetterBox', 'Grate', 'Undefined', 'CableBox', 'Canopy', 'Vent', 'PowerBox', 'UtilityHole', 'Recess', 'Protrusion', 'Shutter', 'Handrail', 'Lock', 'Mirror', 'SecuritySpike', 'Bench', 'Intrusion', 'Picture', 'Showcase', 'Camera', 'Undefined', 'Stair', 'Protrusion', 'Alarm', 'Graffiti', 'Lighting', 'Ornaments', 'SecurityBar', 'Grate', 'Vent', 'Lighting', 'UtilityHole', 'Intrusion', 'Undefined', 'Protrusion'] iN = len(lObjectsALLcnts) arrCnts = np.array(lObjectsALLcnts) theta=np.arange(0,2*np.pi,2*np.pi/iN) width = (2*np.pi)/iN *0.9 bottom = 50 fig = plt.figure(figsize=(8,8)) ax = fig.add_axes([0.1, 0.1, 0.75, 0.75], polar=True) bars = ax.bar(theta, arrCnts, width=width, bottom=bottom) plt.axis('off') rotations = np.rad2deg(theta) for x, bar, rotation, label in zip(theta, bars, rotations, lObjectsALLlbls): lab = ax.text…
type: Answer
upvote count: 7
has comment: http://stackoverflow.com/comment/80737644
score: 7
accepted answer of: http://stackoverflow.com/q/46874689
has comment: http://stackoverflow.com/comment/80732174

http://stackoverflow.com/comment/80545130
comment on: http://stackoverflow.com/q/46798527
type: Comment
type: QuestionComment
has text: An example of Javascript injection in the browser from Python: https://johnpauljanecek.github.io/using-javascript-with-python-selenium/
score: 0

http://stackoverflow.com/comment/80611473
type: QuestionComment
comment on: http://stackoverflow.com/q/46831964
type: Comment
has text: Read this: https://pyformat.info/
score: 0

http://stackoverflow.com/a/46890716
score: 0
type: Answer
has body: If you have two booleans, there are four distinct possibilities: 00 01 10 and 11. If in each case something distinctly different is supposed to happen, there is not really something that could reduce the number of tests. Having said that, in some comparable cases pattern matching might feel more straightforward. I don't know about that in Python though.
answers question: http://stackoverflow.com/q/46890548

http://stackoverflow.com/comment/80447236
has text: It is worth mentioning that the string could be converted to bytes
type: Comment
comment on: http://stackoverflow.com/a/46750629
score: 1
type: AnswerComment

http://stackoverflow.com/comment/80869692
type: Comment
comment on: http://stackoverflow.com/a/46760304
type: AnswerComment
score: 2
has text: @cᴏʟᴅsᴘᴇᴇᴅ i still prefer your solution ~ :-)

http://stackoverflow.com/q/46857639
has answer: http://stackoverflow.com/a/46962260
linked to: http://stackoverflow.com/q/2385320
score: 8
has comment: http://stackoverflow.com/comment/80859945
type: AnsweredQuestion
has title: Problems to verify a file signed with python
type: Question
has comment: http://stackoverflow.com/comment/80730581
has comment: http://stackoverflow.com/comment/80764595
has comment: http://stackoverflow.com/comment/80839453
has comment: http://stackoverflow.com/comment/80737663
tagged with: google-cloud-storage
tagged with: openssl
has comment: http://stackoverflow.com/comment/80664302
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80730344
accepted answer: http://stackoverflow.com/a/46962260
has comment: http://stackoverflow.com/comment/80830977
favorite count: 0
has comment: http://stackoverflow.com/comment/80782739
has comment: http://stackoverflow.com/comment/80730035
upvote count: 8
has body: I'm trying to create a signed file using OpenSSL and Python, and I'm not receiving any error mesage, but the proccess is not working properly and I can't find the reason. Below is my step-by-step to sign the file and check the signature: First I create the crt in command line openssl req -nodes -x509 -sha256 -newkey rsa:4096 -keyout "cert.key" -out "cert.crt" -subj "/C=BR/ST=SP/L=SP/O=Company/OU=IT Dept/CN=cert" At this point, I have two files: cert.key and cert.crt Sign the file use a Python Script like below: import os.path from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from base64 import b64encode, b64decode def __init__(self): folder = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(folder, '../static/cert.key') self.key = open(file_path, "r").read() def sign_data(self, my_file): rsakey = RSA.importKey(self.key) # I opened the cert.key in __init__ signer = PKCS1_v1_5.new(rsakey) digest = SHA256.new() digest.update(my_file) sign = signer.sign(digest) return sign, b64encode(sign) All works fine and after save the files, I have other three files: my_file.csv (the original one), my_file.txt.sha256 and my_file.txt.sha256.base64. At this point, I can decode the base64 file and compare with the signed one and both are fine. The problem is when I try to verify the signature using the following command: `openssl dgst -sha256 -verify &lt;(openssl x509 -in "cert.crt" -pubkey -noout) -signature my_file.txt.sha256 my_file.csv` At this point I always receive the "Verification Failure" and don't understand why. Maybe the problem is my lack of Python's Knowledge, because when I sign the file using the following command (after step 1 and before use the Python script described in 2), the same verification works fine. openssl dgst -sha256 -sign "cert.key" -out my_file.txt.sha256 my_file.csv Am I doing anything wrong? UPDATE Based on the comments, I tried the script in a local virtualnv with python 2.7 an…
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/80674554
tagged with: python
tagged with: cryptography

http://stackoverflow.com/q/46760144
favorite count: 0
has comment: http://stackoverflow.com/comment/80467253
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80468378
tagged with: android
tagged with: kivy
has answer: http://stackoverflow.com/a/46775464
has title: Kivy and android notifications
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46775464
type: Question
has body: I'm trying to use android notifications in my kivy application and I'm having a problem. At first I've tried to use plyer but it doesn't work (app just crashes). So I've read some articles and looked some examples and tried to do it myself using jnius and made this simple application: from kivy.app import App from kivy.uix.button import Button from jnius import autoclass def notify(*args): AndroidString = autoclass('java.lang.String') PythonActivity = autoclass('org.kivy.android.PythonActivity') NotificationBuilder = autoclass('android.app.Notification$Builder') Drawable = autoclass('org.test.notify.R$drawable') icon = Drawable.icon notification_builder = NotificationBuilder(PythonActivity.mActivity) notification_builder.setContentTitle(AndroidString('Title'.encode('utf-8'))) notification_builder.setContentText(AndroidString('Message'.encode('utf-8'))) notification_builder.setSmallIcon(icon) notification_builder.setAutoCancel(True) notification_service = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE) notification_service.notify(0,notification_builder.build()) class NotifyApp(App): def build(self): return Button(text="notify", on_press=notify) if __name__ == '__main__': NotifyApp().run() But it doesn't work and crashes too. I can't understand why because it's the same as in this example or this example but I've just changed org.renpy.android to org.kivy.android because renpy is deprecated (however with org.renpy.android nothing changes). As far as I understand the problem is in the line: notification_service = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE) Because I've tested this code without 2 last lines in notify() function and it works (but of course does nothing). In buildozer adb log I can see this error: 10-15 16:57:00.432 22091 22112 F art : art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: static jfieldID 0x6fc46968 not valid for class java.lang.Class&lt;org.kivy.android.PythonA…
downvote count: 0
answer count: 1

http://stackoverflow.com/q/46866053
accepted answer: http://stackoverflow.com/a/46866199
upvote count: 0
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/80679715
favorite count: 0
tagged with: python-2.7
tagged with: python
has answer: http://stackoverflow.com/a/46866199
downvote count: 2
tagged with: lambda
type: AnsweredQuestion
has body: this is my lambda function- import boto3 def send_function(event, context): valu=event['VAL'] mname=event['MNAM'] d=boto3.client('cloudwatch') d.put_metric_data(Namespace='WebStatus', MetricData=[ { 'MetricName': mname, 'Dimensions': [ { 'Name': 'Status', 'Value': 'WebsiteStatusCode' }, ], 'Value': valu, }, ] ) and i get error - "errorMessage": "Unable to import module 'lambda_function'"
has title: Error Lambda Function handler
type: Question

http://stackoverflow.com/comment/80466628
type: QuestionComment
type: Comment
has text: `argsort` is part of the `numpy` package.
comment on: http://stackoverflow.com/q/46760626
score: 0

queue
tags question: http://stackoverflow.com/q/46856313
tags question: http://stackoverflow.com/q/46808342
tags question: http://stackoverflow.com/q/46899021
type: Tag
tags question: http://stackoverflow.com/q/46815043
tags question: http://stackoverflow.com/q/46846475
tags question: http://stackoverflow.com/q/46802272
tag name: queue
tags question: http://stackoverflow.com/q/46851963

http://stackoverflow.com/comment/80684572
score: 0
has text: Would like to ask you one more question then...isn't there a way in Python to evaluate a string into a class name. Maybe via eval?? In other words, I would think that this string can be matched against the class name and then be converted automatically into the reference. Thanks
comment on: http://stackoverflow.com/a/46864922
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46866300
type: Question
tagged with: pymssql
has body: I have SQL Server installed on my computer, on the same computer I try to connect to the database using python, but I get the following error: &gt;&gt;&gt; from os import getenv &gt;&gt;&gt; import pymssql &gt;&gt;&gt; server = getenv(“КОМП”) &gt;&gt;&gt; user = getenv(“user”) &gt;&gt;&gt; password = getenv(“”) &gt;&gt;&gt; conn = pymssql.connect(server, user, password, “Test”) Traceback (most recent call last): File “&lt;pyshell#6&gt;”, line 1, in &lt;module&gt; conn = pymssql.connect(server, user, password, “Test”) File “pymssql.pyx”, line 635, in pymssql.connect (pymssql.c:10734) File “_mssql.pyx”, line 1902, in _mssql.connect (_mssql.c:21821) File “_mssql.pyx”, line 552, in _mssql.MSSQLConnection.__init__ (_mssql.c:5891) TypeError: argument of type ‘NoneType’ is not iterable Friends please help. I guess I incorrectly wrote the name of the server, the user ... I attach the screenshot of the input window to the SQL Server database with the login data
tagged with: sql-server-2014
upvote count: 0
answer count: 1
favorite count: 0
has title: "type 'NoneType' is not iterable" error when calling pymssql.connect
tagged with: sql-server
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/46921146
downvote count: 1

http://stackoverflow.com/a/65334470
has body: Depending on your setup, you may need to uninstall and reinstall Pycharm. I had this problem on Linux Mint 20, and the issue was I was using the Flathub version of Pycharm. I uninstalled, and downloaded pycharm from the website, installed through terminal and suddenly everything works.
type: Answer
has comment: http://stackoverflow.com/comment/115505911
score: 0
answers question: http://stackoverflow.com/q/46894762

plot
tags question: http://stackoverflow.com/q/46870095
tags question: http://stackoverflow.com/q/46877710
tags question: http://stackoverflow.com/q/46796451
tags question: http://stackoverflow.com/q/46895674
tag name: plot
tags question: http://stackoverflow.com/q/46813949
tags question: http://stackoverflow.com/q/46869328
tags question: http://stackoverflow.com/q/46769026
tags question: http://stackoverflow.com/q/46844963
tags question: http://stackoverflow.com/q/46828031
tags question: http://stackoverflow.com/q/46859615
tags question: http://stackoverflow.com/q/46827915
tags question: http://stackoverflow.com/q/46836766
tags question: http://stackoverflow.com/q/46875691
type: Tag
tags question: http://stackoverflow.com/q/46811822
tags question: http://stackoverflow.com/q/46863224
tags question: http://stackoverflow.com/q/46801187
tags question: http://stackoverflow.com/q/46765617
tags question: http://stackoverflow.com/q/46772191
tags question: http://stackoverflow.com/q/46768859
tags question: http://stackoverflow.com/q/46762633
tags question: http://stackoverflow.com/q/46866529
tags question: http://stackoverflow.com/q/46836301
tags question: http://stackoverflow.com/q/46810480
tags question: http://stackoverflow.com/q/46875336
tags question: http://stackoverflow.com/q/46840152
tags question: http://stackoverflow.com/q/46790600

http://stackoverflow.com/q/46807801
has comment: http://stackoverflow.com/comment/80563603
score: 0
has body: Hi I am using Python to save the data of location using latitude, longitude, and timestamp(unix time). Using dictionary But I tried to add dictionary using function with append, I cannot run it because "append" cannot work with str Here is my code so far dic_loc = {'latitude': 'Value for latitude ', 'longitude': 'Value for longitude', 'timestamp': 'Time Stamp'} def make_timestamped_loc(La, Lng, Time): dic_loc['latitude'].append(La) dic_loc['longitude'].append(Lng) dic_loc['timestamp'].append(Time) make_timestamped_loc(37.481236, 126.952733, 1483196400) make_timestamped_loc(37.481126, 126.952733, 1498859012) print(dic_loc) If I can, I would like to eliminate the existed str value and adding the new value to each keys. Thank you very much
has answer: http://stackoverflow.com/a/46807854
has answer: http://stackoverflow.com/a/46807922
favorite count: 0
upvote count: 2
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46807882
tagged with: python
downvote count: 2
has title: adding value to existing keys using python
has answer: http://stackoverflow.com/a/46808066
type: Question
has answer: http://stackoverflow.com/a/46807917

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

http://stackoverflow.com/a/46801117
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46801059
downvote count: 0
type: Answer
has body: You can use with to open the file, and close it automatically when leaving the with block. Like this: Python3: def main(): filename = input("Input a file name: ") # Open the file, process it, and close it after processing. with open(filename) as f: process_file(f) def process_file(fp_in): for line in fp_in: print(line, end="") #and then do other stuff with it main() Python2: def main(): filename = raw_input("Input a file name: ") # Open the file, process it, and close it after processing. with open(filename) as f: process_file(f) def process_file(fp_in): for line in fp_in: print line, #and then do other stuff with it main()

http://stackoverflow.com/q/46844569
has title: How can i select a specific argument to handle using *args?
linked to: http://stackoverflow.com/q/46843310
tagged with: arguments
tagged with: python
type: Question
tagged with: function
tagged with: python-2.7
score: 0
has body: In my last question the answer helped me solve an issue of choosing Number against other arguments. Then out of curiosity I though what if I actually had to use char2 or char1 or char3 etc.. without referring to a list that'll let me use them based on their placement in the argument. The best way I could find after some research is creating a dynamic array for the arguments where each argument is an object in 1 class dedicated for that purpose, and actually separate them based on their object distinction. That being said couldn't find any examples to clarify that method or walk me through the process step by step. So I'd like to get ways on how to solve that issue and walking through the process.
has answer: http://stackoverflow.com/a/46849701
linked to: http://stackoverflow.com/q/3394835
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/80659990
comment on: http://stackoverflow.com/q/46856087
type: Comment
type: QuestionComment
has text: ... choose a list randomly, choose an item form that list randomly?
score: 0

http://stackoverflow.com/q/46814749
tagged with: syntax
linked to: http://stackoverflow.com/q/45419528
type: Question
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/18755059
score: 1
has comment: http://stackoverflow.com/comment/80576929
has answer: http://stackoverflow.com/a/46814796
accepted answer: http://stackoverflow.com/a/46814796
has title: Boolean comparison in python
upvote count: 1
answer count: 1
tagged with: boolean-logic
favorite count: 0
duplicate of: http://stackoverflow.com/q/45419528
tagged with: python
has body: Python seems to evaluate oddly with (what I thought) would be relatively straightforward syntax. Can anyone shed light on what's happening behind the scenes here? What does python think is happening in the first case? &gt;&gt;&gt; x = 'foo' &gt;&gt;&gt; 'f' in x == True False &gt;&gt;&gt; ('f' in x) == True True &gt;&gt;&gt; 'f' in (x == True) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: argument of type 'bool' is not iterable
downvote count: 0

http://stackoverflow.com/comment/80702818
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46877887
has text: I want the user to only input a integer and not a alphanumeric value
score: 0

http://stackoverflow.com/comment/80547269
score: 0
comment on: http://stackoverflow.com/q/46799662
type: QuestionComment
type: Comment
has text: Can yo please update with a better sample of data. Both inputs and outputs, use [this post](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as an example of how to add dataframs to SO

package
tags question: http://stackoverflow.com/q/46819547
tag name: package
type: Tag
tags question: http://stackoverflow.com/q/46897950
tags question: http://stackoverflow.com/q/46797392
tags question: http://stackoverflow.com/q/46850735
tags question: http://stackoverflow.com/q/46893891
tags question: http://stackoverflow.com/q/46860986

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

http://stackoverflow.com/a/46770446
score: 0
answers question: http://stackoverflow.com/q/46770167
type: Answer
has body: First of all in python its not a array , its list Below code will resolve your problem lst = [list([A1, B1]), list([A2,B2]), list([A3, B3 ])] for i in list: lst[i].sort() print lst[i][-1] That will give max value in each list in the main list

http://stackoverflow.com/comment/80488500
type: QuestionComment
has text: there is no right and wrong with floating points, just more or less accurate
comment on: http://stackoverflow.com/q/46771550
score: 0
type: Comment

http://stackoverflow.com/comment/80724146
comment on: http://stackoverflow.com/q/46888448
type: Comment
type: QuestionComment
score: 0
has text: So I was wondering if the screen size could be access by other libs, such as os/sys

http://stackoverflow.com/comment/80647530
has text: If I cythonize my code with the `import numpy as np` line outside of my module it works correctly. If I can get the import statement to work inside my module installation it should work as expected.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46848095

http://stackoverflow.com/q/46774723
has answer: http://stackoverflow.com/a/46775180
accepted answer: http://stackoverflow.com/a/46775180
has comment: http://stackoverflow.com/comment/80495390
type: AnsweredQuestion
upvote count: 0
has title: For loop can only process two steps
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46775311
has comment: http://stackoverflow.com/comment/80495270
score: -1
has comment: http://stackoverflow.com/comment/80495320
downvote count: 1
has body: I tried get the numbers in l2 start from the maximum one, and each pair of them do subtraction should more or equal than 2. That situation only works if l1 has more than 1 element. So for l2=[2,1,8,3,6,4], expecting output is l1=[8,6,4] since 4-3 &lt;2 the 4th largest 3 will not be taken. Here is my code l2=[2,1,8,3,6,4] l1=[] def check(): i = max(l2) l2.remove(i) if len(l1)&gt;1: for number in l1: if (abs(number - i)) &lt; int(2): break; else: l1.append(i) check() But the output is [8,6].Can anyone tell me how to correct that?
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46775311
tagged with: python

http://stackoverflow.com/comment/80953486
comment on: http://stackoverflow.com/a/46993925
score: 0
type: AnswerComment
type: Comment
has text: Great! To let the user play again, I'd put the game code into a function and then call it in another outer while loop. When the game is done, just ask the user if s/he wants to play again and if "no" is entered, break out of the while loop to quit.

multiprocessing
tags question: http://stackoverflow.com/q/46813568
tags question: http://stackoverflow.com/q/46793919
tags question: http://stackoverflow.com/q/46856313
tags question: http://stackoverflow.com/q/46801439
tags question: http://stackoverflow.com/q/46828371
tags question: http://stackoverflow.com/q/46820799
tags question: http://stackoverflow.com/q/46868031
tags question: http://stackoverflow.com/q/46886225
tags question: http://stackoverflow.com/q/46822226
tags question: http://stackoverflow.com/q/46832024
tags question: http://stackoverflow.com/q/46762533
tags question: http://stackoverflow.com/q/46902995
tags question: http://stackoverflow.com/q/46827515
tags question: http://stackoverflow.com/q/46755640
tags question: http://stackoverflow.com/q/46856826
tags question: http://stackoverflow.com/q/46841147
tags question: http://stackoverflow.com/q/46905530
tags question: http://stackoverflow.com/q/46811709
tags question: http://stackoverflow.com/q/46904699
tags question: http://stackoverflow.com/q/46878241
tags question: http://stackoverflow.com/q/46854555
tags question: http://stackoverflow.com/q/46776588
tags question: http://stackoverflow.com/q/46768813
tags question: http://stackoverflow.com/q/46842479
tags question: http://stackoverflow.com/q/46773552
tags question: http://stackoverflow.com/q/46768955
tags question: http://stackoverflow.com/q/46801284
tags question: http://stackoverflow.com/q/46815868
tags question: http://stackoverflow.com/q/46754524
tags question: http://stackoverflow.com/q/46812351
tags question: http://stackoverflow.com/q/46785153
type: Tag
tags question: http://stackoverflow.com/q/46779860
tags question: http://stackoverflow.com/q/46779617
tag name: multiprocessing

http://stackoverflow.com/a/46870602
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/46869971
accepted answer of: http://stackoverflow.com/q/46869971
has comment: http://stackoverflow.com/comment/80689968
has body: The problem is that you are trying to pass a string as the command instead of a function. Instead of command="m.showinfo('title', 'message')", try something like this: def TestCommand(): m.showinfo('title', 'message') class Gui: def __init__(self): pass def newButton(self, val, command=TestCommand): self.b=tk.Button(std.root, text=val, command=command).pack() Remember that the Button constructor takes a function as the command parameter and not a string.
score: 3

http://stackoverflow.com/q/46810824
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/80581896
answer count: 0
has comment: http://stackoverflow.com/comment/80569220
tagged with: clipboard
type: UnansweredQuestion
has title: Send pygments-highlighted code to Windows clipboard
has body: I am looking for answers that may present alternative methods / modifications related to: My method of sending data to the clipboard The choice of Lexer That may solve the following issue... I aim to be able to send raw python via some process to my clipboard such that I can paste it directly into a Microsoft application (such as Outlook) as formatted text as below I can only achieve the following raw pygments output. RtfFormatter shown but same occurs with HtmlFormatter Copy to Clipboard Method I use the copy func from the post https://stackoverflow.com/a/27291478/4013571 as import ctypes def copy(text): """Copies a string, ``text``, to Windows Clipboard (https://stackoverflow.com/a/27291478/4013571)""" GMEM_DDESHARE = 0x2000 CF_UNICODETEXT = 13 d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None) try: # Python 2 if not isinstance(text, unicode): text = text.decode('mbcs') except NameError: if not isinstance(text, str): text = text.decode('mbcs') d.user32.OpenClipboard(0) d.user32.EmptyClipboard() hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2) pchData = d.kernel32.GlobalLock(hCd) ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text) d.kernel32.GlobalUnlock(hCd) d.user32.SetClipboardData(CF_UNICODETEXT, hCd) d.user32.CloseClipboard() I have also tried pyperclip.copy with no success Syntax Highlighting Method from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import RtfFormatter # Same occurs using HtmlFormatter raw_python = ''' def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z ''' highlighted = highlight(raw_python, PythonLexer(), RtfFormatter()) copy(highlighted)
has comment: http://stackoverflow.com/comment/80569539
linked to: http://stackoverflow.com/q/17298897
tagged with: pygments
has comment: http://stackoverflow.com/comment/80569443
type: Question
linked to: http://stackoverflow.com/q/579687
score: 0

http://stackoverflow.com/comment/80615851
type: Comment
comment on: http://stackoverflow.com/a/46834052
has text: note: the to_datetime should not be necessary with your format, it was just habit to convert those
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80534311
comment on: http://stackoverflow.com/q/46791664
type: Comment
has text: The 'O' dtypes mean the fields are objects. Check the contents. Sometimes loads from matlab can be complex. It has to translate foreign things like cells and structs.
type: QuestionComment
score: 0

http://stackoverflow.com/q/46880887
type: Question
score: 3
has body: My question is very similar to what it seems this post is asking, although that post doesn't pose a satisfactory solution. To elaborate, I am currently using keras with tensorflow backend and a sequential LSTM model. The end goal is I have n time-dependent sequences with equal time steps (the same number of points on each sequence and the points are all the same time apart) and I would like to feed all n sequences into the same network so it can use correlations between the sequences to better predict the next step for each sequence. My ideal output would be an n-element 1-D array with array[0] corresponding to the next-step prediction for sequence_1, array[1] for sequence_2, and so on. My inputs are sequences of single values, so each of n inputs can be parsed into a 1-D array. I was able to get a working model for each sequence independently using the code at the end of this guide by Jakob Aungiers, although my difficulty is adapting it to accept multiple sequences at once and correlate between them (i.e. be analyzed in parallel). I believe the issue is related to the shape of my input data, which is currently in the form of a 4-D numpy array because of how Jakob's Guide splits the inputs into sub-sequences of 30 elements each to analyze incrementally, although I could also be completely missing the target here. My code (which is mostly Jakob's, not trying to take credit for anything that isn't mine) presently looks like this: As-is this complains with "ValueError: Error when checking target: expected activation_1 to have shape (None, 4) but got array with shape (4, 490)", I'm sure there are plenty of other issues but I'd love some direction on how to achieve what I'm describing. Anything stick out immediately to anyone? Any help you could give will be greatly appreciated. Thanks! -Eric
linked to: http://stackoverflow.com/q/39758190
has answer: http://stackoverflow.com/a/46890408
tagged with: lstm
tagged with: numpy
upvote count: 3
answer count: 1
tagged with: keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: Keras sequence prediction with multiple simultaneous sequences
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/46890408

http://stackoverflow.com/a/46798939
has body: It sounds like you are looking for something like df[df.score &gt; df.groupby('family').score.transform('median')].groupby('family').count()
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46798731
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46798731

http://stackoverflow.com/comment/80715597
comment on: http://stackoverflow.com/q/46884151
has text: What do you want in the other cells?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80624505
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46837578
has text: Can you please [edit] your question to make your code a [mcve]? Right now, you are not telling us where you import `pi` from. With `from sympy import pi` it works fine for me.

http://stackoverflow.com/a/46889368
type: Answer
score: 1
has body: No, it's not possible. Please vote for the related feature request. There was also a similar question already asked here.
downvote count: 1
has comment: http://stackoverflow.com/comment/80726192
answers question: http://stackoverflow.com/q/46882513
upvote count: 2

http://stackoverflow.com/a/46779693
has comment: http://stackoverflow.com/comment/80528005
score: 1
answers question: http://stackoverflow.com/q/46779264
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80515098
has body: I'd do something like this: Let s be a pandas.Series that represents the rule s = pd.Series(dict(rule)) Reassign the dataframe to be aligned with s d, s = self.data.align(s, 'inner', 1) Then compare and return only where true for the entire row self.data[d.eq(s).all(1)]
downvote count: 0

http://stackoverflow.com/comment/80719070
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46884428
has text: Player 2 played 2 matches.

http://stackoverflow.com/comment/80749798
comment on: http://stackoverflow.com/q/46901401
has text: thanks patrick, i'll take a look!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46790560
has title: OutOfRangeError: FIFOQueue is closed and has insufficient elements
has comment: http://stackoverflow.com/comment/80529590
has body: found a lot of posts related to this error, but didnt find a solution. When i start my training i get the following error: OutOfRangeError (see above for traceback): FIFOQueue '_1_batch/fifo_queue' is closed and has insufficient elements (requested 1, current size 0) [[Node: batch = QueueDequeueManyV2[component_types=[DT_DOUBLE, DT_DOUBLE], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, batch/n)]] The important code-parts are the following: with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) writer = tf.summary.FileWriter("./logs_path/run5", graph=tf.get_default_graph()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for e in range(10): _, summary = sess.run([train_step, summary_op]) writer.add_summary(summary, e) My pipeline functions are the following: 1) def get_inputs(batch_size): filenames = [] for ch in range(num_channels): for i in range(1): filenames.append(os.path.join(pipeline_path, "training_ch%d_%d_pipeline.bin" % (ch+1, i))) filename_queue = tf.train.string_input_producer(filenames) read_input = _read_pipeline_files(filename_queue) return _generate_spectrum_label_batch(read_input.spectrum, read_input.label, 1, batch_size, False) 2) def _read_pipeline_files(queue): class PipelineRecord(object): pass result = PipelineRecord() reader = tf.FixedLengthRecordReader(record_bytes=2*8*257) result.key, value = reader.read(queue) record_bytes = tf.decode_raw(value, tf.float64) result.spectrum = tf.reshape(tf.strided_slice(record_bytes, [0], [257]), [257]) result.label = tf.reshape(tf.strided_slice(record_bytes, [8*257], [2*257]), [257]) return result 3) def _generate_spectrum_label_batch(spectrum, label, min_queue_examples, batch_size, shuffle): if shuffle: spectrum_batch, label_batch = tf.train.shuffle_batch([spectrum, label], batch_size=batch_size, num_threads=8, capacity=min_queue_examples + 3*batch_size, min_after_dequeue=min_que…
has comment: http://stackoverflow.com/comment/80801153
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80843970
tagged with: tensorflow
type: Question
upvote count: 1
linked to: http://stackoverflow.com/q/44762532
has comment: http://stackoverflow.com/comment/80528164
favorite count: 0
has comment: http://stackoverflow.com/comment/84680100
answer count: 0
has comment: http://stackoverflow.com/comment/80529634
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/46897844
has body: This method allows the user multiple chances to enter a correct answer if they mess up the first time. It also checks to make sure that the number is a valid month. You can also add checks to see if the user needs to include the year. IE: if current_month - month_join &lt; 0 ask them for the year. import datetime current_month = datetime.date.today().month month_join = None while month_join is None: month_join = raw_input('Please enter the month you joined: ') if month_join == 'quit': exit(1) try: month_join = int(month_join) if month_join &gt; 12 or month_join &lt; 1 or not isinstance(month_join, int): print('Please enter a month value that is from 1 to 12') month_join = None except Exception as e: if isinstance(e, TypeError) or isinstance(e, ValueError): print('Please enter the month as an integer. IE. May = 5. If you want to close the program type "quit"') month_join = None else: raise e month_difference = current_month - month_join print month_difference
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46897691
type: Answer

http://stackoverflow.com/a/46865700
accepted answer of: http://stackoverflow.com/q/46865573
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46865573
type: Answer
score: 3
downvote count: 0
has body: Since you know, that your final list has 100 * 30 values, you can generate a numpy.array of the correct size first hand: import numpy as np a1 = np.random.randn(100) a2 = np.random.randn(100) start = np.minimum(a1, a2)[:, None] stop = np.maximum(a1, a2)[:, None] values = (np.linspace(0,1,30)[None, :] * (stop-start) + start).ravel()
has comment: http://stackoverflow.com/comment/80688198
upvote count: 3

http://stackoverflow.com/q/46894503
answer count: 1
tagged with: python
tagged with: python-multithreading
tagged with: selenium
accepted answer: http://stackoverflow.com/a/46916285
tagged with: phantomjs
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46916285
type: Question
has title: PhantonJS and Green GreenPile crash using python
tagged with: python-2.7
score: 0
has body: I'm trying to lunch multiple instances of PhantomJS and using the driver between the threads instead of destroying it and create the process again and again : import sys from datetime import datetime import eventlet from helpers import log, make_request import settings from selenium import webdriver from selenium.webdriver.common.keys import Keys import redis import lxml.html as html pool = eventlet.GreenPool(settings.max_threads) pile = eventlet.GreenPile(pool) redis = redis.StrictRedis(host='localhost', port=6379, db=0) def begin_crawl_phantomJSV2(): url = redis.spop("queue") if None == url: return driver = webdriver.PhantomJS(); process_urlv2(driver, url) def process_urlv2(driver, url): driver.get(url) ## some work url = redis.spop("queue") if None == url: driver.close() driver.quit() return pile.spawn(process_urlv2(driver, url)) if __name__ == '__main__': timea = datetime.now() log("Beginning crawl at {}".format(timea)) redis.sadd("queue", "http://linka.com") redis.sadd("queue", "http://linkb.com") [pile.spawn(begin_crawl_phantomJSV2) for _ in range(1)] pool.waitall() and getting the following error: Traceback (most recent call last): File "C:\Python27\lib\site-packages\eventlet\hubs\hub.py", line 457, in fire_timers timer() File "C:\Python27\lib\site-packages\eventlet\hubs\timer.py", line 58, in __call__ cb(*args, **kw) File "C:\Python27\lib\site-packages\eventlet\greenthread.py", line 214, in main result = function(*args, **kwargs) TypeError: 'NoneType' object is not callable when changing the methods to : def begin_crawl_phantomJS(): driver = webdriver.PhantomJS(); url = redis.spop("queue") if None == url: return process_url(driver, url) driver.close() driver.quit() pile.spawn(begin_crawl_phantomJS) def process_url(driver, url): driver.get(url) ## some work its work just fine but i'm losing some time for the phantomjs prosses to lunch, any idea what shell I do?

http://stackoverflow.com/a/48020158
answers question: http://stackoverflow.com/q/46873757
has body: recognizer = cv2.createLBPHFaceRecognizer(); This makes error for me I tried out, just view the image here. Try out the code below, it may give you result. recognizer = cv2.face.LBPHFaceRecognizer_create();
score: 0
type: Answer

http://stackoverflow.com/q/46852137
has comment: http://stackoverflow.com/comment/80651844
has comment: http://stackoverflow.com/comment/80652012
has body: I can't work out why this code is dropping values solddf'Name', 'Barcode', 'SalesRank', 'SoldPrices', 'SoldDates', 'SoldIds'.head() Out[3]: Name Barcode \ 62693 Near Dark [DVD] [1988] [Region 1] [US Import] ... 1.313124e+10 94823 Battlefield 2 Modern Combat / Game 1.463315e+10 24965 Star Wars: The Force Unleashed (PS3) 2.327201e+10 24964 Star Wars: The Force Unleashed (PS3) 2.327201e+10 24963 Star Wars: The Force Unleashed (PS3) 2.327201e+10 SalesRank SoldPrices SoldDates SoldIds 62693 14.04 2017-08-05 07:28:56 162558627930 94823 1.49 2017-09-06 04:48:42 132301267483 24965 4.29 2017-08-23 18:44:42 302424166550 24964 5.27 2017-09-08 19:55:02 132317908530 24963 5.56 2017-09-15 08:23:24 132322978130 Here's my dataframe. It stores each sale I pull from an eBay API as a new row. My aim to look for correlation between weekly sales and Amazon's Sales Rank. solddf['Week'] = solddf['SoldDates'].apply(lambda x: x.week) weeklysales = solddf.groupby(['Barcode', 'Week']).size().unstack() weeklysales = weeklysales.fillna(0) weeklysales['Mean'] = weeklysales.mean(axis=1) weeklysales.head() Out[5]: Week 29 30 31 32 33 34 35 36 37 38 39 40 41 \ Barcode 1.313124e+10 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.463315e+10 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 2.327201e+10 0.0 0.0 0.0 0.0 0.0 1.0 0.0 1.0 2.0 2.0 0.0 2.0 1.0 2.327201e+10 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 2.327201e+10 0.0 0.0 3.0 2.0 2.0 2.0 1.0 1.0 5.0 0.0 2.0 2.0 1.0 Week 42 Mean Barcode 1.313124e+10 0.0 0.071429 1.463315e+10 0.0 0.071429 2.327201e+10 0.0 0.642857 2.327201e+10 0.0 0.142857 2.327201e+10 0.0 1.500000 So, I've worked out the mean weekly sales for each item (or barcode) I then want to take the mean values and insert them back into my solddf dataframe that I started with. s1 = pd.Series(weeklysales.Mean, index=solddf.Barcode).reset_index() s1 = s1.sort_values('Barcode') s1.head() Out[17]: Barcode Mean 0 1.313124e+10 0.071429 1 1.463315e+10 0.071429 2 2.327201e+10…
type: Question
has comment: http://stackoverflow.com/comment/80651752
has comment: http://stackoverflow.com/comment/80652090
tagged with: dataframe
has title: Losing Values Joining DataFrames
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/46853238
answer count: 1
type: UnansweredQuestion
tagged with: python

selenium-webdriver
tags question: http://stackoverflow.com/q/46776610
tags question: http://stackoverflow.com/q/46770697
tags question: http://stackoverflow.com/q/46844771
tags question: http://stackoverflow.com/q/46880302
tags question: http://stackoverflow.com/q/46809135
tags question: http://stackoverflow.com/q/46822195
tags question: http://stackoverflow.com/q/46888006
tags question: http://stackoverflow.com/q/46856934
tags question: http://stackoverflow.com/q/46771226
tags question: http://stackoverflow.com/q/46881673
tags question: http://stackoverflow.com/q/46860669
tags question: http://stackoverflow.com/q/46843454
tags question: http://stackoverflow.com/q/46878471
tags question: http://stackoverflow.com/q/46825440
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/46756322
tags question: http://stackoverflow.com/q/46844935
tags question: http://stackoverflow.com/q/46830790
tags question: http://stackoverflow.com/q/46867510
tags question: http://stackoverflow.com/q/46771995
tags question: http://stackoverflow.com/q/46878621
tags question: http://stackoverflow.com/q/46754929
tags question: http://stackoverflow.com/q/46773924
tags question: http://stackoverflow.com/q/46798527
tags question: http://stackoverflow.com/q/46811465
tags question: http://stackoverflow.com/q/46779904
tags question: http://stackoverflow.com/q/46844555
type: Tag
tags question: http://stackoverflow.com/q/46820353
tags question: http://stackoverflow.com/q/46753393
tags question: http://stackoverflow.com/q/46790000
tags question: http://stackoverflow.com/q/46860547
tags question: http://stackoverflow.com/q/46801036
tags question: http://stackoverflow.com/q/46901209
tags question: http://stackoverflow.com/q/46889844
tags question: http://stackoverflow.com/q/46853377

http://stackoverflow.com/q/46783325
has answer: http://stackoverflow.com/a/46783395
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46783482
tagged with: python
accepted answer: http://stackoverflow.com/a/46783395
type: AnsweredQuestion
has title: Creating a cross-sectional dataframe from a time series in Python
possible better answer: http://stackoverflow.com/a/46783482
upvote count: 1
type: Question
tagged with: dataframe
has body: Suppose we have a time series indexed by the minute as follows: df = Time (HH:MM) Value 01/01/2014 00:00 1 01/01/2014 00:01 2 01/01/2014 00:02 3 01/01/2014 00:03 4 ... 01/08/2014 00:00 5000 ... I am looking to "group" the dataset by weeks, as follows: df2 = Week Val1 Val2 Val3 Val4 ... 1 1 2 3 4 ... 2 5000 ... 3 4 ... In other words, each 1-minute observation in Week 1 (01/01/2014-01/08/2014) is represented as a column in df2. (There should be 10,080 minutes/columns per week). I've tried a few functions including groupby() but most of them seem to aggregate the data, rather than splitting it into the individual columns I am looking for. edit: It doesn't necessarily have to be in a dataframe format, but I am using this for a function where the input is weeks. Similar to trying to create a histogram of the values for each week.
answer count: 2
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/80515253
comment on: http://stackoverflow.com/q/46784482
score: 0
has text: Are your inputs sorted by opening and closing times?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80531711
has text: I used pypy3 instead of python it worked 3 times faster than python3!! Python 3 needs to be improved!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46791139

http://stackoverflow.com/q/46811865
score: 1
type: Question
has comment: http://stackoverflow.com/comment/81116674
has answer: http://stackoverflow.com/a/46811957
answer count: 1
downvote count: 0
has body: I have a website which requires login (authentication) that has a messages page which I want to convert all the comments to pdfs. Originally I have been just clicking on every comment and choosing print in firefox browser and just saving the comment stream as pdf. The problem is there are so many, so I decided to write a python script but I am having issues. Here is my code: import mechanize import pdfkit import os br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [("User-agent","Firefox")] sign_in = br.open("www.mysite.com") br.select_form(nr = 0) br["username"] = "username" br["password"] = "password" logged_in = br.submit() br.open("comments_page") all_comment_links = [] # Iterate the links for link in br.links(): if "comment" in link.url: all_comment_links.append(link) for l in all_comment_links: ret = br.open("comments_page").read() pdfkit.from_url(l.url, l.text + ".pdf") # pdfkit.from_string(ret, l.text + ".pdf") file = open(l.text + ".html", "w") file.write(ret) file.close() # try from file #for f in glob.glob("*.html"): # pdfkit.from_file(f, f.replace(".html", ".pdf")) I am trying to use the pdfkit lib to convert each comment page to pdf but have been unsuccessful. I have tried using the url (pdfkit.from_url), just the string (pdfkit.from_string), and saving the html to a file (pdfkit.from_file) but cannot figure out why this isn't working. As far as I know, the mechanize stuff works because my html files contain all the comments I want with the right content. I have looked around for different approaches but this is as far as I have gotten to what I want. The script doesn't throw any errors, it just hangs with the first pdf like it cannot access the page/content. I have left it running for a while but only the first pdf file is created, but when I try to open it, it says it is corrupt. Am I using the pdfkit wrong or should I be using something else to convert these pages to pdf? Thanks, and any help is appreciated. Running on mac os x.
tagged with: python-2.7
tagged with: mechanize
has title: How to convert webpage to pdf in python like the save as pdf option in print
tagged with: python
tagged with: macos
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: pdfkit
has comment: http://stackoverflow.com/comment/80589028

http://stackoverflow.com/a/46859596
answers question: http://stackoverflow.com/q/46859242
score: 0
type: Answer
has body: Try this: for div in soup.select('.span4.listing'): if div.h3.text.lower()=='subscribers': output = [(ss.select('a.sfw')[0].text, ss.select('.listing-stat')[0].text) for ss in div.select('.listing-item')]
has comment: http://stackoverflow.com/comment/80669511

http://stackoverflow.com/a/46760304
has comment: http://stackoverflow.com/comment/91327796
has comment: http://stackoverflow.com/comment/91327420
has comment: http://stackoverflow.com/comment/80869692
score: 5
has body: with np.floor rename and groupby df.rename(columns=dict(zip(df.columns[1:], np.floor(df.columns[1:].values.astype(float)).astype(str))),inplace=True) df.set_index('TimeStamp').groupby(level=0,axis=1).mean().reset_index() Out[171]: TimeStamp 382.0 383.0 0 10:28:00 0.012405 0.012405 1 10:30:00 0.012405 0.012422 2 10:32:00 0.055138 0.056121 3 10:34:00 0.055655 0.056802 4 10:36:00 0.055681 0.057086
upvote count: 5
answers question: http://stackoverflow.com/q/46760083
type: Answer
has comment: http://stackoverflow.com/comment/91490705
downvote count: 0
has comment: http://stackoverflow.com/comment/91327635
has comment: http://stackoverflow.com/comment/80869713
has comment: http://stackoverflow.com/comment/80869576
has comment: http://stackoverflow.com/comment/91327205

http://stackoverflow.com/comment/80728177
comment on: http://stackoverflow.com/q/46890439
type: QuestionComment
type: Comment
score: 1
has text: It could be the \ in the path. Use a raw string: `r'C:\ ... '`

http://stackoverflow.com/comment/80741906
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46897363
has text: I figured that's my sticking point, but I can't figure out what to change my 'any' to to make it work. I initially thought 'all' would handle it, but it's still not validating correctly.
score: 0

http://stackoverflow.com/comment/80462024
type: QuestionComment
has text: This is just part of the code
comment on: http://stackoverflow.com/q/46758389
score: 0
type: Comment

http://stackoverflow.com/comment/80727900
type: QuestionComment
comment on: http://stackoverflow.com/q/46890257
has text: And fwiw, if it's just about reading informations (no side effects on the server) the request should be done with a GET. POST is for submitting data for processing by the server.
score: 0
type: Comment

http://stackoverflow.com/q/46889856
answer count: 0
type: UnansweredQuestion
has body: I'm interested in copying a file from my project to the CX_Freeze folder, with the include_files method you can bring files to your project, but I do not know how to do it to bring it out. I generate an .exe installer, which installs the program in Program Files, and manually I have to copy a file to a specific directory, I would like to be able to do it at the same time it is installed. In short, what I want to do is copy from my_project/path/to/archive to C:\Windows\SysWOW64 I share my setup that I have so far setup.py from cx_Freeze import setup, Executable import sys base = 'Win32GUI' if sys.platform == 'win32' else None import os os.environ['TCL_LIBRARY'] = r"C:\Users\puig\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6" os.environ['TK_LIBRARY'] = r"C:\Users\puig\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6" shortcut_table = [ ("DesktopShortcut", # Shortcut "DesktopFolder", # Directory_ "ScannerApp Connector", # Name "TARGETDIR", # Component_ "[TARGETDIR]connector.exe", # Target None, # Arguments None, # Description None, # Hotkey None, # Icon None, # IconIndex None, # ShowCmd 'TARGETDIR' # WkDir ) ] msi_data = {'Shortcut': shortcut_table} bdist_msi_options = {'data': msi_data} options = { 'build_exe': { 'include_files': [ 'my_project/GUI/templates', 'my_project/GUI/images', 'my_project/agent/config.cfg', os.path.join(sys.base_prefix, 'DLLs', 'sqlite3.dll'), os.path.join(sys.base_prefix, 'DLLs', 'tk86t.dll'), os.path.join(sys.base_prefix, 'DLLs', 'tcl86t.dll'), ], 'packages': [ 'PyQt5.uic', 'PyQt5.QtGui', 'PyQt5.QtWidgets', 'PyQt5.QtCore', 'PIL', 'zmq', 'os', 'tkinter', 'raven', ], 'excludes': [ 'django', 'Image', 'PyQt5.Qt', ], }, 'bdist_msi': bdist_msi_options, } executables = [ Executable(script='my_project/GUI/GUI.py', base=base), Executable(script='my_project/agent/connector.py', base=base) ] setup( name='x', version='0.2.9a0', description='description', options=options, executables=executables, author='x', license='MIT', skip_build=True ) Any …
has title: How to copy a file out of the project with cx_freeze
score: 1
type: Question
downvote count: 0
tagged with: cx-freeze
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/a/48089954
type: Answer
has body: Try using with following change: fgp.add_child(folium.GeoJson(data=open('World_Population.json').read(), style_function = lambda x: {'fillColor':'green' if x['properties']['POP2005']&lt; 10000000 else 'orange' if 10000000 &lt;= x['properties']['POP2005'] &lt; 20000000 else'red'}))
score: 0
answers question: http://stackoverflow.com/q/46784877

http://stackoverflow.com/a/46857016
answers question: http://stackoverflow.com/q/46856937
score: 5
has comment: http://stackoverflow.com/comment/80672794
downvote count: 0
has body: Can you remove the topic parameter from KafkaConsumer() and try again? example: # manually assign the partition list for the consumer from kafka import TopicPartition, KafkaConsumer consumer = KafkaConsumer(bootstrap_servers='localhost:1234') consumer.assign([TopicPartition('foobar', 2)]) msg = next(consumer) ref: http://kafka-python.readthedocs.io/en/master/
type: Answer
has comment: http://stackoverflow.com/comment/80678295
has comment: http://stackoverflow.com/comment/80678256
upvote count: 5

http://stackoverflow.com/q/46792379
tagged with: gaussian
score: 4
tagged with: bounds
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/46801817
favorite count: 0
has comment: http://stackoverflow.com/comment/80532605
has body: in the framework of my bachelor's thesis, I need to evaluate my data with python. Unfortunately there's no suiting script of my fellow students yet and I'm quite new to programming. I have this data set and I'm trying to fit it with a gaussian by using scipy.optimize.curve_fit. Since there are a lot of unusable counts especially at the end of the axis, I'd like to confine the part that is to be fitted. Picture raw data This is what I have so far: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit x=np.arange(5120) y=array([ 0.81434599, 1.17054264, 0.85279188, ..., 1. , 1. , 13.56291391]) #most of the data isn't interesting #to me, part of interest see below def Gauss(x, a, x0, sigma): return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) mean = sum(x * y) / sum(y) sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y)) popt,pcov = curve_fit(Gauss, x, y, p0=[max(y), mean, sigma], maxfev=360000) plt.plot(x,y,label='data') plt.plot(x,Gauss(x, *popt), 'r-',label='fit') On docs.scipy.org I've found a general description about curve_fit If I try using bounds=([2400,-np.inf, -np.inf],[2600, np.inf, np.inf]), I'm getting the ValueError: x0 is infeasible. What is the problem here? I also tried to confine it with popt,pcov = curve_fit(Gauss, x[2400:2600], y[2400:2600], p0=[max(y), mean, sigma], maxfev=360000) as suggested in a comment on this question: "Error when obtaining gaussian fit for graph" at stackoverflow In this case I only get a straight line though. Picture: Confinement with x[2400:2600],y[2400:2600] as arguments of curve_fit I really hope you can help me out here. I only need a way to fit a small part of my data. Thanks in advance! interesting data: y=array([ 0.93396226, 1.00884956, 1.15457413, 1.07590759, 0.88915094, 1.07142857, 1.10714286, 1.14171123, 1.06666667, 0.84975369, 0.95480226, 0.99388379, 1.01675978, 0.83967391, 0.9771987 , 1.02402402, 1.04531722, 1.07492795, 0.97135417, 0.99714286, 1.0248139 , 1.26223776, 1.1533101 , 0.990990…
upvote count: 5
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/46801817
type: AnsweredQuestion
tagged with: scipy
has comment: http://stackoverflow.com/comment/80531901
type: Question
has title: Confine a gaussian fit with curve_fit

http://stackoverflow.com/comment/80557743
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46805147
type: AnswerComment
has text: Updated my post again @neuhaus

http://stackoverflow.com/a/46766484
score: 0
answers question: http://stackoverflow.com/q/46764948
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80497004
has body: You can set a variable with the remaining time and check it when seconds are less than 0 so the final countdown script would look like this: from datetime import datetime import time def clock(): print ('Please enter a date and time in the format dd,mm,yyyy,hour,minute,second') response = input() #intake date and time respolist = response.split(',') #split into 5 individual items while True: try: remaining_time=datetime(int(respolist[2]), int(respolist[1]), int(respolist[0]), int(respolist[3]), int(respolist[4]), int(respolist[5])) - datetime.now() print (remaining_time) time.sleep(1) if remaining_time.seconds &lt;= 0: print ('CONGRATS !') break except ValueError: print('Something was wrong with the date entered, please try again.') clock() clock()
type: Answer
accepted answer of: http://stackoverflow.com/q/46764948

http://stackoverflow.com/a/46783761
upvote count: 6
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80538626
answers question: http://stackoverflow.com/q/46780690
type: Answer
accepted answer of: http://stackoverflow.com/q/46780690
downvote count: 0
has body: You can access and store the text from textarea with the following lines : @app.route('/submit', methods=['POST']) def submit_textarea(): # store the given text in a variable text = request.form.get("text") # split the text to get each line in a list text2 = text.split('\n') # change the text (add 'Hi' to each new line) text_changed = ''.join(['&lt;br&gt;Hi ' + line for line in text2]) # (i used &lt;br&gt; to materialize a newline in the returned value) return "You entered: {}".format(text_changed)
score: 6

http://stackoverflow.com/q/46829930
has answer: http://stackoverflow.com/a/46830044
has body: I am encountering a strange problem that relates to instance attributes. I have a variable logger, which I want to be an instance attribute. However, I get the error AttributeError: can't set attribute unless I move the attribute logger outside the __init__() function, which (IIRC), means that I am declaring logger as a class attribute (not what I want). Here is a snippet of my code: class MyScraper(ABC,scrapy.Spider): """Abstract base class for scraping non JS Web pages""" #logger = None # Commented out, as I don't want class instance def __init__(self, *args, **kwargs): self.connection = None self.channel = None self.topic = None log_format = "%(asctime)s - %(levelname)s - %(message)s" log_level = 10 handler = TimedRotatingFileHandler("{0}.log".format(kwargs['log_filename']), when="midnight", interval=1) handler.setLevel(log_level) formatter = logging.Formatter(log_format) handler.setFormatter(formatter) # add a suffix which you want handler.suffix = "%Y%m%d" #need to change the extMatch variable to match the suffix for it handler.extMatch = re.compile(r"^\d{8}$") self.logger = logging.getLogger('my_logger') # &lt;- barfs here # finally add handler to logger self.logger.addHandler(handler) # Set up messaging infrastructure ... Why am I getting this error, and how to fix it?
tagged with: python
has comment: http://stackoverflow.com/comment/80607370
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80607481
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/46830044
has title: AttributeError: can't set attribute - Python instance attribute assignment
downvote count: 0
has comment: http://stackoverflow.com/comment/80607237
answer count: 1
favorite count: 0

http://stackoverflow.com/a/46784916
has body: I've found that with older versions of pandas this can happen with when date fields are present in the dataframe (specifically datetime64 variants). In the past I've used a number of workarounds (see below), hard to know exactly what can help you without seeing the data. Cast all date fields into pandas timestamps (df[col_name].apply(pd.Timestamp)). Cast all date fields into strings (df[col_name].astype(str)). Your initial dataframe is an empty dataframe. Instead of trying to append a non-empty dataframe to an empty one, set the initial one to equal the first non-empty dataframe, and then keep appending. if df1.empty: df1 = perT else: df1 = df1.append(perT) Upgrade pandas :)
upvote count: 5
type: AcceptedAnswer
downvote count: 0
score: 5
type: Answer
answers question: http://stackoverflow.com/q/46781835
accepted answer of: http://stackoverflow.com/q/46781835
has comment: http://stackoverflow.com/comment/80545397

http://stackoverflow.com/a/46779431
answers question: http://stackoverflow.com/q/46775666
has body: You've got a little more in your selector than you need. I've found that it can be reduced to the below. td:nth-child(2) &gt; font[size='1'] CSS selectors are faster and better supported than XPath but there are some things, like locating an element by the contained text, that only XPath can do.
upvote count: 1
has comment: http://stackoverflow.com/comment/80588343
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/46830478
possible better answer: http://stackoverflow.com/a/46830683
tagged with: python
linked to: http://stackoverflow.com/q/2600775
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46831084
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80608444
has comment: http://stackoverflow.com/comment/80609502
has answer: http://stackoverflow.com/a/46831084
has body: I have two list of data one is with date and average values, another one is with index and another value, they look like: #list 1: (in total 62 raws) date d_mean 2017-3-1 15.3 2017-3-2 16.9 2017-3-3 18.2 ... 2017-4-30 17.7 2017-5-1 15.6 #list2: (in total 10 raws) sum 121 555 122 784 123 546 ... 142 568 143 658 144 847 I want to: group the dates into weeks calculate the average values for every week and create a new list with column 'week' and 'w_mean' make this two list same size then plot them against each other I tried to use chunks = [avg_T1[x:x+7] for x in range(4, len(avg_T1), 7)] but this just divided the list, I tried to add .mean() in the end, doesn't really work. I'm new to Python, I'm also glad to hear if there are any necessary materials that I need to read or practice I have to do to help me gut used to using Python.
has answer: http://stackoverflow.com/a/46830683
has title: How to divide dates into weeks and create a new list in Python 3.6?
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/62251463
score: 0
type: Answer
has body: I had a similar issue, and solve it by adding a line of code on the main process, before start the subprocesses: multiprocessing.set_start_method('spawn') Source: [https://stackoverflow.com/a/55812288/8664574]
answers question: http://stackoverflow.com/q/46904699

postgresql
tags question: http://stackoverflow.com/q/46846575
tags question: http://stackoverflow.com/q/46770201
tags question: http://stackoverflow.com/q/46891629
tags question: http://stackoverflow.com/q/46833173
tags question: http://stackoverflow.com/q/46849539
tags question: http://stackoverflow.com/q/46784330
tags question: http://stackoverflow.com/q/46838068
tags question: http://stackoverflow.com/q/46904444
tags question: http://stackoverflow.com/q/46812717
tags question: http://stackoverflow.com/q/46754153
tags question: http://stackoverflow.com/q/46848912
tags question: http://stackoverflow.com/q/46787332
tags question: http://stackoverflow.com/q/46818858
tags question: http://stackoverflow.com/q/46904559
tag name: postgresql
tags question: http://stackoverflow.com/q/46853839
tags question: http://stackoverflow.com/q/46817346
tags question: http://stackoverflow.com/q/46801838
tags question: http://stackoverflow.com/q/46772075
tags question: http://stackoverflow.com/q/46807886
tags question: http://stackoverflow.com/q/46800372
tags question: http://stackoverflow.com/q/46784426
type: Tag
tags question: http://stackoverflow.com/q/46888276
tags question: http://stackoverflow.com/q/46805623
tags question: http://stackoverflow.com/q/46879611
tags question: http://stackoverflow.com/q/46841912
tags question: http://stackoverflow.com/q/46758865
tags question: http://stackoverflow.com/q/46905119
tags question: http://stackoverflow.com/q/46801261
tags question: http://stackoverflow.com/q/46824027
tags question: http://stackoverflow.com/q/46777397
tags question: http://stackoverflow.com/q/46792276
tags question: http://stackoverflow.com/q/46801123
tags question: http://stackoverflow.com/q/46828251
tags question: http://stackoverflow.com/q/46763249
tags question: http://stackoverflow.com/q/46795215
tags question: http://stackoverflow.com/q/46797306
tags question: http://stackoverflow.com/q/46789586

http://stackoverflow.com/a/76235716
answers question: http://stackoverflow.com/q/46833212
has body: Just need to be careful with the variable "title" scope. Try this: # parse the page and store in var soup soup = BeautifulSoup(page, 'html.parser') # find the title title_box = soup.findAll('a', attrs={'class': 'vip'}} print(title_box) # loop through each iteration for each in title_box: if each.find('title_box'): title = title_box.text.strip().encode('utf-8') # print the result print(title) or, in case you want to store all the results # parse the page and store in var soup soup = BeautifulSoup(page, 'html.parser') # find the title title_box = soup.findAll('a', attrs={'class': 'vip'}} print(title_box) # loop through each iteration title_list=[] for each in title_box: if each.find('title_box'): title_list.append(title_box.text.strip().encode('utf-8')) # print the results for title in title_list: print(title)
type: Answer
score: 0

http://stackoverflow.com/comment/80584071
has text: @quintumnia "Don't ask about... Programming of artificial intelligence or machine learning" - https://ai.stackexchange.com/tour
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46818376

http://stackoverflow.com/comment/80753287
type: AnswerComment
has text: I dont fully understand this, where in my code would I put this so that it takes out whitespaces? From what I understand, thats just taking the permutations in my perms list and printing them, which I am already doing.
score: 0
comment on: http://stackoverflow.com/a/46902551
type: Comment

http://stackoverflow.com/comment/80587571
comment on: http://stackoverflow.com/q/46819982
score: 0
type: Comment
type: QuestionComment
has text: Forget python and programming at all for a second - go back to plain old english. What exactly do you want your application to do? Why is apple less than dog, why is pear more than dog? Try to break down your goal into a series of very discrete steps. Why is dog more than apple, but less than pear?

http://stackoverflow.com/q/46779979
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/80506052
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/46784186
score: -1
has body: For my assignment, I'm trying to make a 5 x 5 checkerboard with the user choice in color and square size. I got how to make square sizes and colors based on the user input and am having some trouble with how to start a loop or how to create a 5 x 5 checkerboard. I'm just not sure what I could do to move the turtle to make a 5x5 board. I have this much done so far, if anyone could help me get started, i would really appreciate it! import turtle def main(): length = int(input("Enter a desired length (from 1-150.)")) keepGoing = 'y' while keepGoing == 'y': print("What color would you like to draw?") print(" Enter 1 for Black") print(" 2 for Blue") print(" 3 for Red") print(" 4 for Green") choice = int(input(" Your choice?")) if choice == 1: square(0,0,length,'black') elif choice == 2: square(0,0,length,'blue') elif choice == 3: square(0,0,length,'red') elif choice == 4: square(0,0,length,'green') else: print("ERROR: only enter 1-4.") def square(x, y, width, color): turtle.clear() turtle.penup() # Raise the pen turtle.goto(x, y) # Move to (X,Y) turtle.fillcolor(color) # Set the fill color turtle.pendown() # Lower the pen turtle.begin_fill() # Start filling for count in range(4): # Draw a square turtle.forward(width) turtle.left(90) turtle.end_fill() #calling main function main()
answer count: 1
favorite count: 0
tagged with: turtle-graphics
type: UnansweredQuestion
has title: Python User Input Checkerboard

http://stackoverflow.com/comment/80515962
score: 0
type: QuestionComment
has text: Change the contents of `my_dict` as per your needs before `w.writerow(my_dict)` in the for loop.
type: Comment
comment on: http://stackoverflow.com/q/46784832

http://stackoverflow.com/comment/80558009
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46802739
score: 0
has text: Related: https://stackoverflow.com/questions/17008441/why-do-sqlalchemy-session-close-not-log-rollback

http://stackoverflow.com/comment/80558056
has text: @Jean-FrançoisFabre: I don't know exactly which APIs in Windows don't accept forward slashes, but I believe they are no longer that relevant in Python 3.
comment on: http://stackoverflow.com/q/46805462
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80595905
has text: I’m happy to help.
type: AnswerComment
comment on: http://stackoverflow.com/a/46823604
score: 0
type: Comment

http://stackoverflow.com/q/46770709
has comment: http://stackoverflow.com/comment/80487111
favorite count: 0
tagged with: python-3.x
tagged with: tuples
has comment: http://stackoverflow.com/comment/80487247
tagged with: python
has answer: http://stackoverflow.com/a/46771174
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80486810
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80487591
has body: I have a script that makes a DB call then returns the results as a tuple of tuples. The DB call tracks data from a year-to-data, month-to-date, and week-to-date format. Because of the new fiscal year I am no longer getting any Year-to-date data for some items, as expected, but I need to create an entry in the tuple if the DB didn't return anything so the final table will display all locations and write a zero if nothing returned. Here is what I have: def Main(): template = (('ham', '0905', 0), ('Wind', '852', 0), ('Wash', '3292', 0), ('Chitt', '3367', 0)) yr = sql_fin('year') yr = db_query(yr) # Yearly Data Returned Here print("YEAR: {} ".format(yr)) if yr: pass else: yr = template if len(yr) &lt; len(template): for each in yr: for part in template: if each[0] == part[0]: pass else: yr = yr + (part,) else: pass mnth = sql_fin('month') mnth = db_query(mnth) # Monthly Data Returned Here print("MONTH: {} ".format(mnth)) wk = sql_fin('week') wk = db_query(wk) # Weekly Data Returned Here print("WEEK: {} ".format(wk)) data = {(name, n): [y, 0, 0] for name, n, y in yr} print("DATA:".format(data)) for name, n, m in mnth: data[name, n][1] = m for name, n, w in wk: data[name, n][2] = w data = tuple(tuple([*k, *v]) for k, v in data.items()) print("DATA: {}".format(data)) return data I tried to add a default template in but I did not do it well. Now the other numbers (monthly and weekly) are coming in but all yearly data is zeroed out. What am I not seeing?? Compared to the template, if something like this returned: (('ham', '0905', 3), ('Wind', '852', 4)) How can I ensure the other entries make it in without altering data
has title: Using a Tuple of Tuples Template
accepted answer: http://stackoverflow.com/a/46771174
has comment: http://stackoverflow.com/comment/80486791
linked to: http://stackoverflow.com/q/46774105
downvote count: 0
answer count: 1
score: 1

http://stackoverflow.com/comment/80495195
comment on: http://stackoverflow.com/q/46774551
has text: "Something is going wrong"? What is "something" here? Please clearly state what problem you have.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46767597
linked to: http://stackoverflow.com/q/1373164
type: AnsweredQuestion
has title: Printing content of different variables with iterating name in a for loop
has body: Can someone explain to me, how to print the content of the following variables in a loop? Week23 = [12-9, "free", 15.30-12.30, "free", 12-9] Week24 = [] Week25 = [] Week26 = [] Week27 = [] Week28 = [] Week29 = [] ... I have tried playing around with the following, but it is not printing the content. The exec statement merely prints out "Week23" etc. The eval statement doesn't work due to a parsing error. import numpy as np length = np.linspace(23,42,42-23+1) for i in length: print("Week" + str(i)) # print(eval("Week" + str(i))) # exec('print("Week" + str(i))')
has answer: http://stackoverflow.com/a/46767829
accepted answer: http://stackoverflow.com/a/46767812
has answer: http://stackoverflow.com/a/46768128
has comment: http://stackoverflow.com/comment/80480696
type: Question
tagged with: printing
has comment: http://stackoverflow.com/comment/80480988
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80480673
has comment: http://stackoverflow.com/comment/80480792
has answer: http://stackoverflow.com/a/46767812
has comment: http://stackoverflow.com/comment/80482373
score: 0
has comment: http://stackoverflow.com/comment/80480760
has comment: http://stackoverflow.com/comment/80481487
possible better answer: http://stackoverflow.com/a/46767829
tagged with: python
has comment: http://stackoverflow.com/comment/80490500
answer count: 4
has answer: http://stackoverflow.com/a/46767905
has comment: http://stackoverflow.com/comment/80481202

http://stackoverflow.com/comment/80628785
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46840384
has text: Python makes it pretty easy. Take a look here: https://docs.python.org/2/howto/sockets.html
score: 0

http://stackoverflow.com/q/46798761
tagged with: python-appium
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50829087
downvote count: 0
score: 1
type: Question
tagged with: appium
has body: I recently took over a project which is using Appium to do some automated mobile testing. I have a few python scripts that are supposed to be ran with Appium however when attempting to run them I run into "[INSTALL_FAILED_VERSION_DOWNGRADE]". After much research on the matter I have included that this is a problem related to Android and it's APK version. However I am new to Android so this makes it challenging to fully understand both what Appium and Android are doing. I am leaning more towards a problem when it is trying to install the application to the device, however I feel I had addressed the steps to troubleshooting that. Some examples are ensuring that I had the latest version of the app, de-installing the app, reinstalling an older version of the app, and finally checking for updates. Python script traceback: Traceback (most recent call last): File "main.py", line 310, in &lt;module&gt; launch() File "main.py", line 26, in launch driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) File "C:\Python\lib\site-packages\appium\webdriver\webdriver.py", line 36, in __init__ super(WebDriver, self).__init__(command_executor, desired_capabilities, browser_profile, proxy, keep_alive) File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__ self.start_session(desired_capabilities, browser_profile) File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute self.error_handler.check_response(response) File "C:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: A new session could not be created. (Original error: Command failed: C:\AndroidSDK\platform-tools\adb.exe -s GCNPC…
linked to: http://stackoverflow.com/q/4162447
has title: Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
has answer: http://stackoverflow.com/a/47417468
has answer: http://stackoverflow.com/a/50829087
upvote count: 1
accepted answer: http://stackoverflow.com/a/47365565
favorite count: 0
has answer: http://stackoverflow.com/a/59990023
tagged with: android
tagged with: apk
tagged with: python
has answer: http://stackoverflow.com/a/47365565

http://stackoverflow.com/comment/80660277
type: AnswerComment
has text: yes it is included u can see in question itself the CSV data is exactly the same and I have pandas installed.
type: Comment
comment on: http://stackoverflow.com/a/46851134
score: 0

http://stackoverflow.com/a/46808684
has comment: http://stackoverflow.com/comment/80565079
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/80565286
has body: Take a look at the below code. I took the liberty to make additional changes to make the whole thing more Pythonic and efficient. Update2: I took the liberty to make some small adjustments (Antonvbr) from random import randint # 1 def main(saldo): while True: y = input("[R]oll or [S]top").lower() # 3 if y == "r" : p = input("What is your prediction?") #4 while p not in list("123456"): print("Enter a valid number 1-6") p = input("What is your prediction?") p = int(p) # convert to integer x = randint(1, 6) print(x) if p == x: saldo += 5 elif abs(p-x) == 1: saldo -= 1 else: saldo -= 3 print ("saldo is {}".format(saldo)) # 5 elif y == "s" : print ("stop! saldo is {}".format(saldo)) return saldo else: print ("Enter R/r or S/s") # Not case sensitivt anymore startsaldo = 5 saldo = main(startsaldo) #2 Explanation: you do not want to import on every iteration, import functions are always made first as mentioned by others saldo needs to be initialized once only. Normally parameters like these are injected in the function and returned back when the function quits. you are asking for "R" or "S" but comparing against "r" and "s". In Python, case matters. you only want inputs 1-6 to be valid list("123456") returns ["1","2...] and then we convert that to an int string formatting is a very valuable tool to learn. Also generally, var = var + 1 is written like var += 1 in Python. Same applies with - too.
score: 2
has comment: http://stackoverflow.com/comment/80565299
has comment: http://stackoverflow.com/comment/80565136
has comment: http://stackoverflow.com/comment/80564775
answers question: http://stackoverflow.com/q/46808391
downvote count: 0

http://stackoverflow.com/q/46794694
accepted answer: http://stackoverflow.com/a/46799231
tagged with: heroku
has comment: http://stackoverflow.com/comment/80537208
has title: Deployment of Python App on Heroku
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46799231
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/80542399
tagged with: deployment
has comment: http://stackoverflow.com/comment/80545380
has body: I created my first chatbot with Chatterbot library. Now I want to deploy it through Heroku, but this is impossible. My chatbot is composed of some files (py, csv, yml, json, txt). This is the structure: botusers (csv file) Magghy (py file) magghybot (py file) Procfile Requirements (txt file) telegramtoken (txt file) conversation.yml (in folder named lang) math_words.json (in folder named lang) I created a "Procfile" (worker: python magghybot.py) and "Requirements.txt" Then, I create my Heroku Profile and I tried to deploy my project but on terminal I have this problem: Counting objects: 13, done. Delta compression using up to 4 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (13/13), 5.22 KiB | 0 bytes/s, done. Total 13 (delta 0), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to magghy. remote: To https://git.heroku.com/magghy.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/magghy.git' What am I missing?
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/80545038
type: AnswerComment
type: Comment
has text: Oh the modal isn’t getting detected have a look at this one https://stackoverflow.com/q/17676036/5912110 apologies if this want helpful
comment on: http://stackoverflow.com/a/46798872
score: 0

http://stackoverflow.com/a/46774201
has comment: http://stackoverflow.com/comment/80495800
has comment: http://stackoverflow.com/comment/80495654
has comment: http://stackoverflow.com/comment/80514679
downvote count: 0
has comment: http://stackoverflow.com/comment/80495193
score: 1
has comment: http://stackoverflow.com/comment/80511284
has comment: http://stackoverflow.com/comment/80498000
has comment: http://stackoverflow.com/comment/80496266
has comment: http://stackoverflow.com/comment/80495900
has comment: http://stackoverflow.com/comment/80496534
has comment: http://stackoverflow.com/comment/80495830
has comment: http://stackoverflow.com/comment/80496160
has comment: http://stackoverflow.com/comment/80496972
has comment: http://stackoverflow.com/comment/80501185
has body: Depending on your Django version you may need to specify TEMPLATE_DIR = in settings.py (in newer versions this isn't required). Here is some helpful information on template and tag logic: Main/templates/myapp/base.html Main/templates/myapp/index.html Main/templates/myapp/includes/yes_js.html Main/templates/myapp/includes/no_js.html base.html: {% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; {% block content %} {% endblock %} &lt;/body&gt; &lt;/html&gt; index.html: {% extends 'myapp/base.html' %} {% load staticfiles %} {% block content %} &lt;noscript&gt; {% include 'no_js.html' %} &lt;/noscript&gt; {% include 'yes_js.html' %} {% endblock %}
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46773416
has comment: http://stackoverflow.com/comment/80523423

http://stackoverflow.com/comment/80615783
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46834013
type: QuestionComment
has text: So, do you want to make us guess which line is throwing the error?

http://stackoverflow.com/q/46835067
has comment: http://stackoverflow.com/comment/80630019
has comment: http://stackoverflow.com/comment/80628237
has answer: http://stackoverflow.com/a/46835140
type: Question
has comment: http://stackoverflow.com/comment/80628257
has body: I'm quite new in Python, but googling around did not match any answer for it . I created a module, containing 10 GUI buttons classes. To use a button I write in code ButtonLib.TypeA(**kwargs), ButtonLib.TypeB(**kwargs) and so on. kwargs is same for all buttons. Buttons ( amount and type ) are selected by user (stored in button_type_vector) and not known in advance. I wish to know if there is a way writing code more efficiently rather than: for x in button_type_vector: if x == 'TypeA': ButtonLib.TypeA(**kwargs) elif x== 'TypeB' : ButtonLib.TypeB(**kwargs) and so on. by efficiently I mean something like: for x in button_type_vector: ButtonLib.x(**kwargs) thnks
has comment: http://stackoverflow.com/comment/80617748
has title: Python - Calling a class as a parameter
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80617783
has comment: http://stackoverflow.com/comment/80617858
accepted answer: http://stackoverflow.com/a/46835140
possible better answer: http://stackoverflow.com/a/46835183
has answer: http://stackoverflow.com/a/46835183
has comment: http://stackoverflow.com/comment/80618479
has comment: http://stackoverflow.com/comment/80618010
linked to: http://stackoverflow.com/q/2612610
tagged with: python
duplicate of: http://stackoverflow.com/q/2612610
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80619961
has comment: http://stackoverflow.com/comment/80618086

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

http://stackoverflow.com/q/46796287
downvote count: 0
possible better answer: http://stackoverflow.com/a/46797739
has answer: http://stackoverflow.com/a/46797739
favorite count: 0
tagged with: elasticsearch
tagged with: python
type: AnsweredQuestion
has title: Accesing elasticsearch on Heroku Bonsai from my computer
has answer: http://stackoverflow.com/a/46806728
upvote count: 1
tagged with: https
tagged with: bonsai-elasticsearch
type: Question
tagged with: heroku
score: 1
has body: I'm trying to ping my Elasticsearch instance (Deployed through Bonsai an Heroku add on). I have followed their guidelines and try to execute the following code on my computer: from elasticsearch import Elasticsearch from settings import BONSAI_URL import re, logging # Log transport details (optional): logging.basicConfig(level=logging.INFO) # Parse the auth and host from env: bonsai = BONSAI_URL print(bonsai) auth = re.search('https\:\/\/(.*)\@', bonsai).group(1).split(':') host = bonsai.replace('https://%s:%s@' % (auth[0], auth[1]), '') # Connect to cluster over SSL using auth for best security: es_header = [{ 'host': host, 'port': 443, 'use_ssl': True, 'http_auth': (auth[0],auth[1]) }] # Instantiate the new Elasticsearch connection: es = Elasticsearch(es_header) # Verify that Python can talk to Bonsai (optional): es.ping() I've got the following error message: elasticsearch.exceptions.ImproperlyConfigured: Root certificates are missing for certificate validation. Either pass them in using the ca_certs parameter or install certifi to use it automatically. I believe this error is coming from the fact that I don't have a https certificates so I used HTTP, by removing the s in the URL and the regex and switching the use_ssl to False but I got the following error: urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer')) How can I insert data from my computer into elasticsearch on Heroku?
answer count: 2
accepted answer: http://stackoverflow.com/a/46806728

flask-sqlalchemy
tags question: http://stackoverflow.com/q/46826035
tags question: http://stackoverflow.com/q/46819254
tags question: http://stackoverflow.com/q/46748896
tags question: http://stackoverflow.com/q/46789423
type: Tag
tags question: http://stackoverflow.com/q/46856436
tags question: http://stackoverflow.com/q/46879611
tags question: http://stackoverflow.com/q/46783346
tags question: http://stackoverflow.com/q/46758066
tags question: http://stackoverflow.com/q/46766989
tags question: http://stackoverflow.com/q/46778860
tags question: http://stackoverflow.com/q/46869376
tags question: http://stackoverflow.com/q/46811342
tags question: http://stackoverflow.com/q/46864673
tags question: http://stackoverflow.com/q/46749550
tags question: http://stackoverflow.com/q/46828088
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/46863829
tags question: http://stackoverflow.com/q/46876259
tags question: http://stackoverflow.com/q/46830131

http://stackoverflow.com/comment/113480630
score: 0
comment on: http://stackoverflow.com/q/46899443
type: Comment
type: QuestionComment
has text: no coincidence for me googling "Sandia Dakota TUI", what are you referring to?

http://stackoverflow.com/q/46860547
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80668699
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
has body: I am trying to web scrape using selenium in Python. I find all the links on the webpage using elems = self.driver.find_elements_by_xpath("//a[@href]") Below are the attributes of the individual links from the list above. URL 1: {u'href': u'/video/ca02339f-f8b3-4c34-a34c-5cb317b4618b/fda2decb-2d6c-4d48-9535-7362381688b3', u'_ngcontent-c15': u'', u'class': u'slider-item'} URL 2: {u'href': u'/video/ca02339f-f8b3-4c34-a34c-5cb317b4618b/cdc7f553-e176-49ff-a8a5-d7413dfef534', u'_ngcontent-c15': u'', u'class': u'slider-item'} URL 3: {u'href': u'/video/ca02339f-f8b3-4c34-a34c-5cb317b4618b/710a09a8-6c59-4195-9f1d-991b7807ec94', u'_ngcontent-c15': u'', u'class': u'slider-item'} URL 4: {u'href': u'/video/ca02339f-f8b3-4c34-a34c-5cb317b4618b/9659cf42-35b5-4e48-9a86-3cb2e97ed8bd', u'_ngcontent-c15': u'', u'class': u'slider-item'} I would like to click one of the href link. There are no link texts associated with the links. Is there a way to click just the link without any other information. I could not find any information regarding following stand-alone links without any meta info.
has comment: http://stackoverflow.com/comment/80668673
answer count: 0
tagged with: selenium
has title: click a href link using selenium on python
type: Question
tagged with: javascript
has comment: http://stackoverflow.com/comment/80668657

http://stackoverflow.com/q/46769257
accepted answer: http://stackoverflow.com/a/46769522
has comment: http://stackoverflow.com/comment/80483819
has comment: http://stackoverflow.com/comment/80484181
type: AnsweredQuestion
downvote count: 0
tagged with: key
favorite count: 0
has comment: http://stackoverflow.com/comment/80483889
type: Question
score: 5
tagged with: python
has title: Adding keys to dicts within a list, from values in a list
tagged with: dictionary
has answer: http://stackoverflow.com/a/46769522
tagged with: list
answer count: 3
tagged with: loops
possible better answer: http://stackoverflow.com/a/46769466
has answer: http://stackoverflow.com/a/46769466
upvote count: 5
has answer: http://stackoverflow.com/a/46769458
has body: How can I add keys to a dict within a list, if the dict contains a certain key, from values in another list? I have a list of dicts. Those dicts either contain only one key ('review'), or two keys ('review' and 'response'). When the dict contains the key 'response', I want to add two keys, with values from two lists. data = [{'response': 'This is a response', 'review': 'This is a review'}, {'review': 'This is only a review'}, {'response': 'This is also a response', 'review': 'This is also a review'}] date = ['4 days ago', '3 days ago'] responder = ['Manager', 'Customer service'] I have tried the following, but since for each dict that contains the key 'response' I only want to add 1 from the values from each lists, I am not sure how to do this. for d in data: if 'response' in d: for i in date: d['date'] = i for i in responder: d['responder'] = i The output shows me that it of course only adds the last values of the lists since I'm looping over the lists. How can I fix this? [{'date': '3 days ago', 'responder': 'Customer service', 'response': 'This is a response', 'review': 'This is a review'}, {'review': 'This is only a review'}, {'date': '3 days ago', 'responder': 'Customer service', 'response': 'This is also a response', 'review': 'This is also a review'}]

http://stackoverflow.com/q/46850610
tagged with: cython
has answer: http://stackoverflow.com/a/46851063
type: Question
tagged with: arrays
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80655845
has comment: http://stackoverflow.com/comment/80667859
score: 3
accepted answer: http://stackoverflow.com/a/46851063
has comment: http://stackoverflow.com/comment/80651018
has body: I try to rewrite a complex function form Python to Cython to speed it up massively and I encounter the following problem: while compiling my function hh_vers_vector.pyx using setup( ext_modules=cythonize("hh_vers_vector.pyx"), ) it throws the following error cdef int numSamples = len(Iext); # initial values cdef float v[numSamples] ^ ------------------------------------------------------------ hh_vers_vector.pyx:47:27: Not allowed in a constant expression If, however, I give "numSamples" as a number into the function, there is no problem. I don't understand that, because I thought that len(Iext) will return a number as 10.000 as well. So why does Cython have a problem with this expression? cdef float v[numSamples] # ERROR cdef float v[10000] # NO ERROR My function looks like this so far: from math import exp import time def hhModel(*params, Iext, float dt, int Vref): ## Unwrap params argument: these variables are going to be optimized cdef float ENa = params[0] cdef float EK = params[1] cdef float EL = params[2] cdef float GNa = params[3] cdef float GK = params[4] cdef float GL = params[5] ## Input paramters # I : a list containing external current steps, your stimulus vector [nA/1000] # dt : a crazy time parameter [ms] # Vref : reference potential [mV] # T : Total simulation time in [ms] def alphaM(float v, float vr): return 0.1 * (v-vr-25) / ( 1 - exp(-(v-vr-25)/10) ) def betaM(float v, float vr): return 4 * exp(-(v-vr)/18) def alphaH(float v, float vr): return 0.07 * exp(-(v-vr)/20) def betaH(float v, float vr): return 1 / ( 1 + exp( -(v-vr-30)/10 ) ) def alphaN(float v, float vr): return 0.01 * (v-vr-10) / ( 1 - exp(-(v-vr-10)/10) ) def betaN(float v, float vr): return 0.125 * exp(-(v-vr)/80) ## steady-state values and time constants of m,h,n def m_infty(float v, float vr): return alphaM(v,vr) / ( alphaM(v,vr) + betaM(v,vr) ) def h_infty(float v, float vr): return alphaH(v,vr) / ( alphaH(v,vr) + betaH(v,vr) ) def n_infty(float v, float vr): return alphaN(v,vr) /…
has comment: http://stackoverflow.com/comment/80650711
favorite count: 0
has title: Cython: creating an array throws "not allowed in a constant expression"
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46306737
upvote count: 3

http://stackoverflow.com/q/46895062
has body: I am trying to chaining two decorators . but some how end up running only one. can some one suggest me solution for that def decorator_redis(func_name): def redis_decorator(func): @wraps(func) def redis_wrapper(*args): redis_utilty = RedisUtilties() entity_id = args[0] return 'hello' + entity_id return redis_wrapper return redis_decorator def decorator_ES(func_name): def ES_decorator(func): @wraps(func) def ES_wrapper(*args): return args[0]+ '!' return ES_wrapper return ES_decorator @decorator_redis('find') @decorator_ES('find') def fetch_entity(name): return print(fetch_entity('John')) I need to print hello John!. But able to print out hello John or John ! depending on which decorator I used individually.
duplicate of: http://stackoverflow.com/q/739654
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80737428
favorite count: 0
accepted answer: http://stackoverflow.com/a/46895127
upvote count: 2
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80737406
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80737267
linked to: http://stackoverflow.com/q/739654
type: Question
has title: Chaining decorators
has answer: http://stackoverflow.com/a/46895127

amazon-web-services
tags question: http://stackoverflow.com/q/46760166
tags question: http://stackoverflow.com/q/46802777
tags question: http://stackoverflow.com/q/46778792
tags question: http://stackoverflow.com/q/46874385
tags question: http://stackoverflow.com/q/46784767
tags question: http://stackoverflow.com/q/46752867
tags question: http://stackoverflow.com/q/46781281
tags question: http://stackoverflow.com/q/46829144
tags question: http://stackoverflow.com/q/46840920
type: Tag
tags question: http://stackoverflow.com/q/46900804
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/46770325
tags question: http://stackoverflow.com/q/46801711
tags question: http://stackoverflow.com/q/46820932
tags question: http://stackoverflow.com/q/46867246
tags question: http://stackoverflow.com/q/46904410
tags question: http://stackoverflow.com/q/46760297
tags question: http://stackoverflow.com/q/46846275
tags question: http://stackoverflow.com/q/46821113
tags question: http://stackoverflow.com/q/46819590
tags question: http://stackoverflow.com/q/46836493
tags question: http://stackoverflow.com/q/46799070
tags question: http://stackoverflow.com/q/46812351
tags question: http://stackoverflow.com/q/46791798
tags question: http://stackoverflow.com/q/46846295
tags question: http://stackoverflow.com/q/46860191
tags question: http://stackoverflow.com/q/46754707
tags question: http://stackoverflow.com/q/46868702
tags question: http://stackoverflow.com/q/46883321
tags question: http://stackoverflow.com/q/46855004
tags question: http://stackoverflow.com/q/46751551

http://stackoverflow.com/comment/80598804
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46825434
has text: Maybe you are looking for merge. Please put some data so we better understand what your actual prob is.
score: 0

http://stackoverflow.com/comment/140120090
type: AnswerComment
score: 0
type: Comment
has text: The values for `fields` is a path within the returned JSON. However, the default `spreadsheet.get()` function does not return all the data, so it's far from clear where the `hyperlink` value comes from. To see all the fields, make the call with no fields, and with `includeGridData=true`.
comment on: http://stackoverflow.com/a/46880090

http://stackoverflow.com/q/46867272
upvote count: 1
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/80682257
has answer: http://stackoverflow.com/a/46867552
has answer: http://stackoverflow.com/a/46867396
downvote count: 1
type: Question
has body: I have a list called movies with two sublists embedded it. Do the sublists have names too? I want to use len() BIF to measure all items in the list and sublists, how do I do that?
has answer: http://stackoverflow.com/a/46867418
score: 0
has answer: http://stackoverflow.com/a/46867335
has comment: http://stackoverflow.com/comment/80681998
has title: Python len function on list with embedded sublists and strings
favorite count: 0
has comment: http://stackoverflow.com/comment/80682282
has comment: http://stackoverflow.com/comment/80682250
type: UnansweredQuestion

http://stackoverflow.com/q/46901513
tagged with: multi-index
type: Question
has answer: http://stackoverflow.com/a/46901539
has answer: http://stackoverflow.com/a/46901626
has comment: http://stackoverflow.com/comment/80749891
tagged with: dataframe
upvote count: 2
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/80749901
has answer: http://stackoverflow.com/a/46901776
favorite count: 0
has body: Given a sample MultiIndex: idx = pd.MultiIndex.from_product([[0, 1, 2], ['a', 'b', 'c', 'd']]) df = pd.DataFrame({'value' : np.arange(12)}, index=idx) df value 0 a 0 b 1 c 2 d 3 1 a 4 b 5 c 6 d 7 2 a 8 b 9 c 10 d 11 How can I efficiently convert this to a tabular format like so? a b c d 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 Furthermore, given the dataframe above, how can I bring it back to its original multi-indexed state? What I've tried: pd.DataFrame(df.values.reshape(-1, df.index.levels[1].size), index=df.index.levels[0], columns=df.index.levels[1]) Which works for the first problem, but I'm not sure how to bring it back to its original from there.
possible better answer: http://stackoverflow.com/a/46901626
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/46901539
type: AnsweredQuestion
downvote count: 0
has title: Reshape MultiIndex dataframe to tabular format

amazon-redshift-spectrum
tags question: http://stackoverflow.com/q/46834392
tag name: amazon-redshift-spectrum
type: Tag

http://stackoverflow.com/a/46890408
downvote count: 0
has comment: http://stackoverflow.com/comment/81210931
type: Answer
has comment: http://stackoverflow.com/comment/81165288
has body: Keras is already prepared to work with batches containing many sequences, there is no secret at all. There are two possible approaches, though: You input your entire sequences (all steps at once) and predict n results You input only one step of all sequences and predict the next step in a loop Suppose: nSequences = 30 timeSteps = 50 features = 1 #(as you said: single values per step) outputFeatures = 1 First apporach: stateful=False: inputArray = arrayWithShape((nSequences,timeSteps,features)) outputArray = arrayWithShape((nSequences,outputFeatures)) input_shape = (timeSteps,features) #use layers like this: LSTM(units) #if the first layer in a Sequential model, add the input_shape #if you want to return the same number of steps (like a new sequence parallel to the input, use return_sequences=True Train like this: model.fit(inputArray,outputArray,....) Predict like this: newStep = model.predict(inputArray) Second approach: stateful=True: inputArray = sameAsBefore outputArray = inputArray[:,1:] #one step after input array inputArray = inputArray[:,:-1] #eliminate the last step batch_input = (nSequences, 1, features) #stateful layers require the batch size #use layers like this: LSMT(units, stateful=True) #if the first layer in a Sequential model, add input_shape Train like this: model.reset_states() #you need this in stateful=True models #if you don't reset states, #the stateful model will think that your inputs are new steps of the same previous sequences for step in range(inputArray.shape[1]): #for each time step model.fit(inputArray[:,step:step+1], outputArray[:,step:step+1],shuffle=False,...) Predict like this: model.reset_states() predictions = np.empty(inputArray.shape) for step in range(inputArray.shape[1]): #for each time step predictions[:,step] = model.predict(inputArray[:,step:step+1])
accepted answer of: http://stackoverflow.com/q/46880887
answers question: http://stackoverflow.com/q/46880887
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/46897332
has comment: http://stackoverflow.com/comment/80742089
answer count: 1
has body: I have floating error on Django server in production, it does not causes exceptions, only some wrong behaviour. But I can't reproduce it on my locale machine; So I need to debug it on server side. Are there any tools, that can log all states of all variables so then I could replay problematic requests and figure out what behaves wrong?
has answer: http://stackoverflow.com/a/46898549
score: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46898549
has title: Is there any solution for delayed python debugging?
type: Question

http://stackoverflow.com/q/46831044
accepted answer: http://stackoverflow.com/a/46831805
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
upvote count: 1
tagged with: jinja2
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80610104
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80611063
has body: I have a flask web app set up using jinga2 templates and Json. I'm trying to display the data stored in the json file in my html template. I ideally would like it to display and looks like a list in the html. The page should display the json in a recipe format e.g step my step but I can't seem to get it to work. I have included my python file, json and html template to help with reproducing the issue. This is my python file: @app.route('/recipes/pumpkin_pie/') @app.route('/recipes/halloween/pumpkin_pie/') def pumpkin_pie(): recipes = [] with open('recipes.json', 'r') as f: recipes = json.load(f) f.close() print recipes p = {} for item in recipes: if item['name'] == "pumpkin pie": print item p = item print p return render_template('pumpkin_pie.html', pumpkin=p) This is my html tempate file: {{ pumpkin.ingredients }} {% for result in pumpkin %} {% for methods in result %} {{pumpkin.methods }} {% endfor %} {% endfor %} This is my json file: { "name": "pumpkin pie", "ingredients": [" large eggs plus 1 yolk", "1 tsp ground cinnamon"], "methods": { "1": "Pre-heat the oven to 200C/400F/Gas 6", "2": "If using a shop bought sweet crust pastry case, use one that is 23cm/9in diameter and 4cm/1.5in deep. If using your own pastry, roll it out and use it to line a 23cm/9in pie plate (not loose bottomed). Bake the pastry case blind for 20 minutes." } }
has title: Using jinja2 templates to display json
has answer: http://stackoverflow.com/a/46831805
answer count: 1
tagged with: flask
favorite count: 0

http://stackoverflow.com/a/46852551
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46852242
type: Answer
downvote count: 0
score: 1
has body: Use In [4974]: dff = df2.merge(df1) In [4975]: (dff[dff['status'].eq('CHARGED') &amp; (dff['date']-dff['reg_date']).dt.days.le(7)] .groupby('userid')['amount'].sum() .reindex(df1['userid'].unique(), fill_value=0) .reset_index()) Out[4975]: userid amount 0 1 11.68 1 2 18.98 2 3 0.00
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46852242

http://stackoverflow.com/comment/80467472
type: QuestionComment
comment on: http://stackoverflow.com/q/46761067
has text: Problem is: `cv2.waitKey(50)` reduce 50 to, say, 1. That's the delay between each frame, you'll want to reduce that.
score: 0
type: Comment

http://stackoverflow.com/a/47018094
score: 2
upvote count: 2
has body: I would first try to understand the root cause of the slowness before building a cache or monkeypatching socket.getaddrinfo. Are your nameservers configured correctly in /etc/resolv.conf? Are you seeing packet loss on the network? If you're experiencing loss that's outside your control, running a caching server (nscd) will mask but not completely eliminate the problem.
downvote count: 0
answers question: http://stackoverflow.com/q/46836616
type: Answer

http://stackoverflow.com/a/46847678
accepted answer of: http://stackoverflow.com/q/46846950
answers question: http://stackoverflow.com/q/46846950
score: 0
type: AcceptedAnswer
has body: Using solutions provided in Getting distance between two points based on latitude/longitude and Iterate a list as pair (current, next) in Python I was able to build a Pythonic approach of this problem: import itertools from collections import namedtuple from math import sin, cos, sqrt, atan2, radians Location = namedtuple('Location', ['long', 'lat', 'time']) all_locations = [ Location(lat=37.481236, long=126.952733, time=1488323400), Location(lat=37.310045, long=127.101255, time=1488323255), Location(lat=37.383065, long=126.672596, time=1488323531), Location(lat=37.383065, long=116.672596, time=1488323230), ] def distance(loc_a, loc_b): """Extracted from: https://stackoverflow.com/questions/19412462""" R = 6373.0 lat_a, lat_b = radians(loc_a.lat), radians(loc_b.lat) long_a, long_b = radians(loc_a.long), radians(loc_b.long) dlat = lat_b - lat_a dlong = long_b - long_a a = sin(dlat / 2)**2 + cos(lat_a) * cos(lat_b) * sin(dlong / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) return R * c def pairwise(iterable): """Extracted from: https://stackoverflow.com/questions/5434891""" a, b = itertools.tee(iterable) next(b, None) return zip(a, b) sorted_locations = sorted(all_locations, key=lambda l: l.time) total_distance = sum(distance(a, b) for a, b in pairwise(sorted_locations)) delta_time = sorted_locations[-1].time - sorted_locations[0].time print(total_distance, delta_time, total_distance / delta_time) Using namedtuple is not mandatory, but I felt like it would simplify the code. FTR named tuple are simple structures only containing declared fields (here long, lat and time). The pairwise function allows to iterate over 2 pairs of a list (i.e. current and next element). By using it on the sorted location list by time, I can easily evaluate the distance. Basically: sorted_locations = [l1, l2, l3] distances = [distance(a, b) for a, b in pairwise(sorted_locations)] # equivalent to [distance(l1, l2), distance(l2, l3)] total_distance = sum(distances) Not using intermediate list w…
type: Answer

http://stackoverflow.com/comment/80605040
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46828549
has text: yes the red points Show the gaussian distribution
type: QuestionComment

http://stackoverflow.com/q/46831672
downvote count: 0
tagged with: azure-dsvm
has body: My job collects multiple times a day from a streaming job and drops a csv into blob storage. After a few weeks of collecting data, I will run a python script to do some machine learning. To set up the training data, I am first moving all data within a range into a single csv on the virtual machine so it can train on that single csv in one pass. Using the code below, I find that moving the data from blob storage to the virtual machine using blob_service.get_blob_to_path() takes on average 25 seconds per file, even if they're small 3mb files. The appending portion goes incredibly fast at milliseconds per file. Is there a better way to do this? I thought increasing max connections would help, but I do not see any performance improvement. blob_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY) # get list of blob files? blobs = [] marker = None while True: batch = blob_service.list_blobs(CONTAINER_NAME, marker=marker) blobs.extend(batch) if not batch.next_marker: break marker = batch.next_marker for blob in blobs: print(time.time()-start_time) split_name = blob.name.split('/') # year/month/day... blob_date = pd.to_datetime(str(split_name[0])+'-'+str(split_name[1])+'-'+str(split_name[2])) # s=arg start date, e=arg end date if blob_date &gt; s and blob_date &lt;= e: print('Appending: '+ blob.name, end='') blob_service.get_blob_to_path(CONTAINER_NAME,blob.name, './outputs/last_blob.csv', open_mode='wb', max_connections=6) print(' ... adding to training csv ' +str(time.time()-start_time)) with open('./outputs/all_training_data.csv','ab') as f_out: with open('./outputs/last_blob.csv','rb') as blob_in: for line in blob_in: f_out.write(line) else: print('** SKIPPING: '+ blob.name) Additional notes: This is being done using Azure Machine Learning Workbench as part of my train.py process. --edit-- Data Science VM and Storage Account are both in SC US. DSVM is DS4_V2 standard (8c cpu, 28gb memory). Total size of all blobs combined for my current test is…
favorite count: 0
type: UnansweredQuestion
tagged with: azure
tagged with: python
has comment: http://stackoverflow.com/comment/80612210
has comment: http://stackoverflow.com/comment/80616186
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/80611782
upvote count: 1
type: Question
tagged with: azure-blob-storage
tagged with: azure-machine-learning-service
has title: Is there a way to speed this up - moving csvs from Azure Blob storage to vm, appending to single csv, using python
has comment: http://stackoverflow.com/comment/80611746

http://stackoverflow.com/q/46861179
type: AnsweredQuestion
has title: Separate row of a dataframe based on a condition by renaming it in pandas / python
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/46861605
answer count: 1
score: 0
tagged with: pandas
has body: For each of my id column, I want to check for each row the column job and rename the id rows below if a specific job appears. In this example below, if the job seller appears or barber, the rows below must be renamed. Do you have a clue ? entry = pd.DataFrame([['1','35','fireman'],['2','35','policeman'],['3','35','seller'],['4','35','seller'],['5','35','accountant'],['6','35','barber'],['7','35','fireman']],columns=['index','id','job']) output = pd.DataFrame([['1','35','fireman'],['2','35','policeman'],['3','35','seller'],['4','35','seller'],['5','35(1)','accountant'],['6','35(1)','barber'],['7','35(2)','fireman']],columns=['index','id','job'])
tagged with: python
has answer: http://stackoverflow.com/a/46861605

http://stackoverflow.com/comment/80585072
comment on: http://stackoverflow.com/q/46818555
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Merge two tables based on multiple keys in Python pandas](https://stackoverflow.com/questions/32277473/merge-two-tables-based-on-multiple-keys-in-python-pandas)

http://stackoverflow.com/comment/80524243
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46789020
has text: The solution doesnt work since I have like 2000 columns like this... I can't write all the 2000 cases by hand.

http://stackoverflow.com/q/46761361
has answer: http://stackoverflow.com/a/46761424
tagged with: python
has comment: http://stackoverflow.com/comment/80468005
linked to: http://stackoverflow.com/q/11059390
has title: Reading rows in csv file
type: UnansweredQuestion
upvote count: 1
has body: I have a csv file that has data looks similar to this: Year Age 2001 58 2006 52 2006 12 2001 50 2012 59 2017 46 So I want to extract these two rows into two different list. with open('age.csv', 'r') as files: next(files) # skip header for row in file_path: years = row[0] return years, average_age But this will only give me 20, 20, 20, something that I didn't want it to show. So that I can have like: years = [2001, 2006, 2006, 2001, blabla] However, for age, I am planning to get the average age for each year. But I don't know how in this case.
has answer: http://stackoverflow.com/a/46761407
score: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80468077
has comment: http://stackoverflow.com/comment/80468018
has comment: http://stackoverflow.com/comment/80468713
has comment: http://stackoverflow.com/comment/80468055
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80468611

http://stackoverflow.com/comment/80507351
type: QuestionComment
has text: Sorry, my knowledge of conda is very surface level. I hope someone who knows the answer sees this question.
comment on: http://stackoverflow.com/q/46780521
score: 0
type: Comment

http://stackoverflow.com/a/46874833
has comment: http://stackoverflow.com/comment/80714115
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80714307
downvote count: 0
has comment: http://stackoverflow.com/comment/80714239
has comment: http://stackoverflow.com/comment/80729090
has comment: http://stackoverflow.com/comment/80714774
has comment: http://stackoverflow.com/comment/80727968
has comment: http://stackoverflow.com/comment/80713824
has body: Here is a basic demo that shows how to add an extra column with icons and other formatting. Note that an attempt is made to normalise the file-paths so that comparisons and dictionary look-ups should be more reliable: import sys from PySide.QtCore import * from PySide.QtGui import * database = { QFileInfo('C:\Program Files\Internet Explorer\ExtExport.exe').absoluteFilePath(): (1, 3), QFileInfo('C:\Program Files\Internet Explorer\iexplore.exe').absoluteFilePath(): (0, 0), } class FileSystemModel(QFileSystemModel): def __init__(self, parent=None): super().__init__(parent) style = qApp.style() self.icons = [ style.standardIcon(QStyle.SP_MessageBoxInformation), style.standardIcon(QStyle.SP_MessageBoxWarning), ] def columnCount(self, parent=QModelIndex()): return super().columnCount(parent) + 1 def data(self, index, role=Qt.DisplayRole): extra = False if index.isValid(): extra = index.column() == self.columnCount(index.parent()) - 1 info = self.fileInfo(index) path = info.absoluteFilePath() if path in database: major, minor = database[path] print('found:', (major, minor), path) if extra: if role == Qt.DecorationRole: if major &gt; 0: return self.icons[0] else: return self.icons[1] elif role == Qt.DisplayRole: return '%s/%s' % (major, minor) elif role == Qt.ForegroundRole: if minor &gt; 2: return QColor('red') if not extra: return super().data(index, role) def headerData(self, section, orientation, role=Qt.DisplayRole): if (orientation == Qt.Horizontal and role == Qt.DisplayRole and section == self.columnCount() - 1): return 'Extra' return super().headerData(section, orientation, role) class FileSystemBrowser(QTreeView): def __init__(self, parent=None): super().__init__(parent) self.fileSystemModel = FileSystemModel() self.fileSystemModel.setRootPath(QDir.currentPath()) self.setModel(self.fileSystemModel) self.header().moveSection(self.fileSystemModel.columnCount() - 1, 1) if __name__ == '__main__': app = QApplication(sys.argv) window = FileSystemBrowser() window.show() s…
has comment: http://stackoverflow.com/comment/80734793
upvote count: 2
has comment: http://stackoverflow.com/comment/80731560
accepted answer of: http://stackoverflow.com/q/46835109
type: Answer
has comment: http://stackoverflow.com/comment/80728152
has comment: http://stackoverflow.com/comment/80696730
answers question: http://stackoverflow.com/q/46835109
has comment: http://stackoverflow.com/comment/80696765

http://stackoverflow.com/q/46816099
has comment: http://stackoverflow.com/comment/80579653
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/2009379
has comment: http://stackoverflow.com/comment/80579633
has title: Scipy Interpolate splrep Data Error?
answer count: 1
downvote count: 0
favorite count: 0
has body: I am writing the following code, pretty basic , just calling splrep in scipy.interpolate. However it throws and error on the dataset. Following is the code x_nodesTrial = np.array([ 1321., 1327., 1329., 1326., 1329., 1327., 1328., 1336., 1335., 1326., 1327., 1323., 1337., 1338., 1337., 1338., 1338., 1338., 1340., 1340., 1337., 1334., 1333., 1342., 1343., 1340., 1344., 1343., 1346., 1347., 1348., 1346., 1374., 1377., 1372., 1378., 1380., 1384., 1390., 1391., 1386., 1397., 1395., 1396., 1397., 1398., 1399., 1399., 1399.]) y_nodesTrial = np.array([ 0.97897541, 0.60222801, 0.95832816, 1.2578326 , 1.08685326, 1.29256113, 0.78091064, 0.96806139, 0.92957363, 0.46117087, 0.72456884, 1.04872371, 0.87137002, 1.03914457, 0.74450367, 0.96806139, 0.93808315, 0.79181076, 0.84673744, 1.15069855, 0.8782084 , 1.14509825, 0.97970477, 0.91182705, 1.12178111, 1.07171425, 0.58492979, 0.89831191, 1.17473401, 0.97970477, 0.87013956, 1.1568893 , 1.01242284, 0.7309485 , 1.00418766, 1.04394513, 1.08947891, 0.81053333, 1.21184629, 0.94566681, 0.73630351, 0.86839343, 1.07495847, 0.87003695, 0. , 1.01559272, 0.97504579, 1.0377689 , 1.05694979]) k = 3 tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0) I get the following error: k = 3 tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0) Traceback: Traceback (most recent call last): File "&lt;ipython-input-24-a978d88e9773&gt;", line 2, in &lt;module&gt; tck = inter.splrep(x_nodesTrial, y_nodesTrial, k=k, s=0) File "C:\Anaconda\lib\site-packages\scipy\interpolate\fitpack.py", line 278, in splrep res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet) File "C:\Anaconda\lib\site-packages\scipy\interpolate\_fitpack_impl.py", line 515, in splrep raise _iermess[ier][1](_iermess[ier][0]) ValueError: Error on input data Can someone help point out what is wrong with the above code/dataset ? Appreciate the help. Thanks
has answer: http://stackoverflow.com/a/54913914
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6

http://stackoverflow.com/a/46824532
type: Answer
answers question: http://stackoverflow.com/q/46818255
score: 0
has body: I had similar problem working with Gmail to send mails. Try only the following codes to send emails. Hope it helps: In settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "sender_email@gmail.com" EMAIL_HOST_PASSWORD = "email_password" EMAIL_PORT = 0 EMAIL_USE_TLS = True Codes to send emails: # Imports for sending emails: from django.conf import settings from django.core.mail import EmailMultiAlternatives, send_mail emailFrom = [settings.EMAIL_HOST_USER] emailTo = email_here text_content = 'Your content here' email_subject = "Subject here" msg = EmailMultiAlternatives(email_subject, text_content, emailFrom, [emailTo], ) msg.send() Also change the settings in the 'sender gmail account' to create a passage for the mail to be send from the sender to the receiver. Hope this helps.

http://stackoverflow.com/comment/80585047
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46818555
score: 0
has text: Just use df1.merge(df2, on = ['ticker', 'year', 'quarter'])

http://stackoverflow.com/comment/80571276
has text: I ve tried with alpha =0.5 and alpha = 0.1 but it is still very confused... is it possible to plot the bigger ones on the background?
comment on: http://stackoverflow.com/a/46811939
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80645853
type: QuestionComment
type: Comment
has text: If it works locally and not on production then obviously production doesn't run the same code... So first check what you really have on production (source code etc) AND that you restarted your server processes after deployment. Oh and yes : do NOT edit your code directly on a production server - do your changes locally, _test them_, and once you have a working release deploy it on production.
comment on: http://stackoverflow.com/q/46848912
score: 0

http://stackoverflow.com/q/46886438
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/80720245
has body: How could I make an if/else condition about the status of myAarduino? If the status of my Arduino is connected, I want to have a Connected Message. If not, message is Disconnected. import serial serialTransferRate = 115200 arduinoPort = '/dev/tty.usbmodem411' def connectToArduino(): arduino = serial.Serial(arduinoPort, serialTransferRate) if(arduino.timeout == None): print ("connected") else: print ("disconnected") arduino = connectToArduino() The error code below: File "python", line 12, in <module> File "python", line 6, in connectToArduino SerialException: [Errno 2] could not open port /dev/tty.usbmodem411: [Errno 2] No such file or directory: '/dev/tty.usbmodem411'
has comment: http://stackoverflow.com/comment/80720631
downvote count: 14
has answer: http://stackoverflow.com/a/46886604
has comment: http://stackoverflow.com/comment/80720956
answer count: 1
has title: Arduino Python connect or disconnect message
favorite count: 0
has comment: http://stackoverflow.com/comment/80720122
type: UnansweredQuestion
tagged with: python
score: -10
upvote count: 4
has comment: http://stackoverflow.com/comment/80729426
tagged with: arduino
has comment: http://stackoverflow.com/comment/80720507

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

http://stackoverflow.com/comment/80656019
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46854127
has text: Sure it does. The only possible problem: if your existing notebooks are very old; well... let's see. Multiple possible problems there (e.g. changes in pandas...). But one should go for recent versions of those libs, even if one has to port old code somehow.

http://stackoverflow.com/comment/80794217
has text: Can are u help me please?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46902979
type: Comment

http://stackoverflow.com/q/46779617
type: Question
has comment: http://stackoverflow.com/comment/80528382
has title: multiprocessing.Pool graceful termination of child processes
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80506018
has comment: http://stackoverflow.com/comment/80505461
has comment: http://stackoverflow.com/comment/80505297
has body: I am trying to have better control over my pool of processes. I found that calling break in the pool loop calls pool.terminate() and forcibly terminates child processes, but I would like to have them finish their chunks and exit gracefully. Manual says I should use pool.close(): close() Prevents any more tasks from being submitted to the pool. Test process: chunks = range(7) with Pool(2) as pool: ret = pool.imap_unordered(work, chunks) for reply in ret: info(reply) if reply == "processed 2": pool.close() Child process: def work(arg): sleep(1) return "processed {}".format(arg) I expect at most 2 more tasks to be completed after close() has been called, but nothing is stopped: 22:46:00 processed 0 22:46:00 processed 1 22:46:01 processed 2 22:46:01 processed 3 22:46:02 processed 4 22:46:02 processed 5 22:46:03 processed 6
answer count: 0
tagged with: multiprocessing

http://stackoverflow.com/q/46796985
possible better answer: http://stackoverflow.com/a/46797342
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46797342
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/46797105
has comment: http://stackoverflow.com/comment/80541593
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80547660
accepted answer: http://stackoverflow.com/a/46797105
upvote count: 1
has comment: http://stackoverflow.com/comment/80542245
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80547650
has title: Organize data in CSV into multiple lists in Python 3
linked to: http://stackoverflow.com/q/46820888
has comment: http://stackoverflow.com/comment/80589183
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80540701
has body: I'm working with a large CSV file with two columns - IP address and a Group name. Below is an example data: ip group 192.168.1.1 A 192.168.1.2 B 192.168.1.3 C 192.168.1.4 A 192.168.1.5 B 192.168.1.6 C I need to organize the data into separate lists of IPs, based on the Group name. Something like this: sorted_data = (A, B, C), where A = (192.168.1.1, 192.168.1.4), B = (192.168.1.2, 192.168.1.5) and so forth. The whole file is about 10K records with about 20 unique groups. Please help!
has comment: http://stackoverflow.com/comment/80540800

http://stackoverflow.com/comment/80729930
type: Comment
comment on: http://stackoverflow.com/a/46890666
has text: `Highcharts.charts[0]` is the first chart in the page. To get the chart related to a DOM element: `Highcharts.charts[document.querySelector("#head-chart").dataset["highchartsChart"]]`
type: AnswerComment
score: 0

http://stackoverflow.com/q/46905530
tagged with: parallel-processing
tagged with: concurrency
has answer: http://stackoverflow.com/a/46905653
type: Question
tagged with: multiprocessing
answer count: 2
has answer: http://stackoverflow.com/a/46905620
has title: Python multiprocessing and concurency vs paralellism
linked to: http://stackoverflow.com/q/1050222
score: 0
has body: I have created and application. In this application I use multiprocessing library. In that application I do spin two processes (instances of the same class) to consume data from Kafka and put into Python Queue. This is the library I used: Python multiprocessing Q1. Is it concurrency or is it parallelism? Q2. Is it multithreading or is it multiprocessing? Q3. How does Python maps Processes to CPUs? (does this question make sense?) I understand in order to speak about multithreading I need to use separate / multiple CPUs (so separate threads are mapped to separate CPU threads). I understand in order to speak about multiprocessing I need to use separate memory space for both processes? Is it correct? I assume if I spin two processes within one Application instance => we talk about concurrency. If I spin multiple instances of above application then we would talk about parallelism? (multiple CPUs, separate memory spaces used)? I see that Python library defines it as follows: Python multiprocessing library The multiprocessing package offers both local and remote concurrency ... Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. ... A prime example of this is the Pool object which offers a convenient means of parallelizing the execution of a function across multiple input values, distributing the input data across processes (data parallelism).
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80622822
score: 0
type: Comment
has text: Thanks! Is there any way I can credit an answer via comment here?
type: QuestionComment
comment on: http://stackoverflow.com/q/46837492

http://stackoverflow.com/comment/80476807
score: 0
type: Comment
type: QuestionComment
has text: Did you merge two dataframes to get this result?
comment on: http://stackoverflow.com/q/46765766

http://stackoverflow.com/comment/80626290
type: Comment
score: 1
type: AnswerComment
has text: @AsheKetchum Yes. If the functions are mostly the same you can probably extract the code they have in common into an extra function. By the way, your suggestion of writing a class for each region may be appropriate too (especially if you have this problem of having to call different functions depending on the region more than once.) - I expanded my answer to adress this
comment on: http://stackoverflow.com/a/46839133

http://stackoverflow.com/q/46781697
linked to: http://stackoverflow.com/q/588004
has answer: http://stackoverflow.com/a/46781725
score: 0
answer count: 2
duplicate of: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/80509721
has title: Python - Algorithm to compute k fractions of form 1/r summing up to 1
has comment: http://stackoverflow.com/comment/80511740
has answer: http://stackoverflow.com/a/46781714
type: UnansweredQuestion
tagged with: python
has body: I have the code already figured out and have found a way to get around the problem that for k &gt; 6 the largest denominator is very large. But when my code adds up for example 1/float(2) + 1/float(3) + 1/float(7) + 1/float(42) python says that it is not equal to 1, but it should be. Why does python recognize other sums as being equal to 1 but not this one?
tagged with: fractions
has comment: http://stackoverflow.com/comment/80509810
type: Question
tagged with: algorithm

http://stackoverflow.com/a/46850353
has body: You can use numpy.reshape to reshape randomly generated numbers. &gt;&gt;&gt; N = 3 &gt;&gt;&gt; np.random.rand(N*N*3).reshape([N,N,3]) array([[[ 0.48513983, 0.49582462, 0.96211702], [ 0.95061997, 0.63674441, 0.51228963], [ 0.06988701, 0.9018317 , 0.63418989]], [[ 0.31213247, 0.75325276, 0.04600117], [ 0.23449785, 0.04731562, 0.89007085], [ 0.25746369, 0.96337201, 0.6032985 ]], [[ 0.2207508 , 0.43560328, 0.75067189], [ 0.84054857, 0.28190793, 0.08875157], [ 0.00419059, 0.13464854, 0.63074635]]]) Result is a 2d array of array of 3 numbers. &gt;&gt;&gt; temp = np.random.rand(N*N*3).reshape([N,N,3]) &gt;&gt;&gt; temp[0][0] array([ 0.48513983, 0.49582462, 0.96211702])
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46849949
type: Answer

http://stackoverflow.com/comment/80558363
type: QuestionComment
has text: @luschn ah..I SEE...
comment on: http://stackoverflow.com/q/46805634
score: 0
type: Comment

http://stackoverflow.com/a/46870886
has body: Looks like you can achieve this by collections.defaultdict person_dict = {1665845 : Person(1665845, stuff), 1294919 : Person(1294919, stuff)} # existing dictionary l = [['1665845', '2001-01-06', '28,448,615,27,705'], ['1665845', '2001-01-10', '218,37,356,621,466,319,147,774,231,167,399,150,417,34,3'], ['1294919', '2001-01-04', '639,118,328,413,222,491,738,389,11,372,183,650,281,643,26,398,685,171'], ['1294919', '2001-01-10', '314,611,485,208,515,240,586,511,713,58,28,392,140,529,353,489,375,412,596'], ['1665845', '2001-01-04', '670,665,681,184,22,752,390,523,507,171,467,19,296,720,58,230,721,686'], ['1665845', '2001-01-02', '432,210,732,204,771,555,448,82,343'], ['1294919', '2001-01-06', '113,225,564,554,392,544,313'], ['1294919', '2001-01-05', '437,219,239,545,588,303,477,384,87,254,429,635,188,372,572,712,383'], ['1294919', '2001-01-03', '771,373'], ['1294919', '2001-01-08', '650,679,492,524,202,689,224,268,195,455,400,235,518,505']] from collections import defaultdict d_dict = defaultdict(int) for k,_,v in l: d_dict[int(k)]+=sum(int(i) for i in v.split(',')) #dict(d_dict) #{1294919: 31022, 1665845: 17701} for k in person_dict: person_dict[k] = Person(k, stuff, d_dict[k])
has comment: http://stackoverflow.com/comment/80691332
answers question: http://stackoverflow.com/q/46870263
has comment: http://stackoverflow.com/comment/80689189
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/80689262
has comment: http://stackoverflow.com/comment/80689299

http://stackoverflow.com/comment/80599109
comment on: http://stackoverflow.com/q/46825319
score: 0
has text: I suppose the main issue was using `.find_one()`. Thanks..
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80621586
type: Comment
has text: I want to prefill database with 100 records, where and how should i do this function? I have created my model bu actually i can add items by shell or by admin panel. As i said i want to prefill 100 records with prepared in model defaults, and then create another function that uptates that 100 records with prepared data. But where i should create these functions? and how to run it automaticly? let's say when some1 enters the page
comment on: http://stackoverflow.com/a/46834750
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80788980
has text: I would use https://uwsgi-docs.readthedocs.io/en/latest/ to run Django app, perhaps behind Nginx. You can either run some amount of workers (threads x processes) and hope that such Popen-blocks are OK (they're OK, but it will handle small load, bigger amount of users can make server stuck). If you need higher load - check Celery. You will run a task, get task-id immediately, and you can return ID to client (browser). Browser will poll when task is ready and can load task results. But you will need to update both django view and template (some ajax polling)
comment on: http://stackoverflow.com/a/46898947
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80452189
comment on: http://stackoverflow.com/q/46751063
has text: I know the question I've flagged as a duplicate isn't quite the same as yours, but I believe the answer tells you what you want to know. If this isn't the case then I'm happy to withdraw the flag
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46822006
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46821950
has comment: http://stackoverflow.com/comment/80591749
has body: total_non_zeros = np.count_nonzero(ground_truth) # sample 1d index idx = np.random.choice(total_non_zeros, int(total_non_zeros * 0.2)) # subset non zero indices and set the value at corresponding indices to zero ground_truth[tuple(map(lambda x: x[idx], np.where(ground_truth)))] = 0 ground_truth #array([[ 0, 99, 98], # [ 0, 84, 0], # [55, 0, 0]])
answers question: http://stackoverflow.com/q/46821950
has comment: http://stackoverflow.com/comment/80592092
type: Answer
has comment: http://stackoverflow.com/comment/80591701
has comment: http://stackoverflow.com/comment/80592234

http://stackoverflow.com/q/46828740
has body: I have designed a username and password program. When the user enters their username and password, it should check if it matches the data in a text file. The problem is that it displays access denied when I input the correct username and password. Please help me find a solution. from tkinter import * class Application(Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): self.instruction = Label(self,text='Enter your Username') self.instruction.grid(row=0, column=0, columnspan=2,sticky=W) self.username=Entry(self) self.username.grid(row=1, column =1, sticky=W) self.sumbit_button=Button(self,text='Submit',command= self.reveal) self.sumbit_button.grid(row=5,column=0,sticky=W) self.instruction = Label(self,text='Enter a password') self.instruction.grid(row=3, column=0, columnspan=2,sticky=W) self.password=Entry(self) self.password.grid(row=4, column =1, sticky=W) self.text = Text(self,width=35, height=5, wrap=WORD) self.text.grid(row=6, column=0, columnspan=2,sticky=W) def reveal(self): file=open('data.RTF','r') data1=file.readlines() file.close content2=self.username.get() content=self.password.get() if content2==(data1[0]) and content==(data1[1]): message='You have access to something special.' else: message='Access denied.' self.text.delete(0.0,END) self.text.insert(0.0,message) root=Tk() root.title('Username and Password') root.geometry('250x150') app=Application(root) root.mainloop()
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80604870
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/80604918
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80604955
has comment: http://stackoverflow.com/comment/80604724
has title: Username and Password must match to data in text file
tagged with: tkinter
has answer: http://stackoverflow.com/a/46828892
accepted answer: http://stackoverflow.com/a/46828892
tagged with: python
has comment: http://stackoverflow.com/comment/80605195

http://stackoverflow.com/comment/80484799
comment on: http://stackoverflow.com/a/46769787
score: 0
type: AnswerComment
has text: You have any example please... this will clear my thoughts.
type: Comment

http://stackoverflow.com/comment/80543408
score: 0
comment on: http://stackoverflow.com/a/46797640
type: AnswerComment
has text: Okay, thanks. I installed what I thought was the latest version of seaborn earlier today via conda install (v. 0.8). I just installed [from Github](https://github.com/mwaskom/seaborn) and now the colors are differentiated and the y-axis is scaled appropriately. However, I don't believe the y-scaling issue was addressed in that workaround as you mention. You can see that the kde curves are off the y-axis scale.. Unless I am missing something?
type: Comment

http://stackoverflow.com/q/46769954
answer count: 2
upvote count: 1
tagged with: python
has body: I am creating an azure runbook to connect to a sql database to make some queries . I was trying to import one of two libraries : pymssql , pyodbc but the machine runs the runbook does not have that library. Do you have any other idea to make some queries to sql database , or install these two libraries on that machine. Thank you very much.
has title: Azure runbook using python to connect to Sql databae
tagged with: runbook
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49706412
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/49706412
has answer: http://stackoverflow.com/a/46786120
type: Question
tagged with: azure
score: 1
accepted answer: http://stackoverflow.com/a/46786120

http://stackoverflow.com/q/46857382
has comment: http://stackoverflow.com/comment/81199936
upvote count: 9
has title: TensorFlow estimator.predict() gives WARNING:tensorflow:Input graph does not contain a QueueRunner
has comment: http://stackoverflow.com/comment/82088397
answer count: 3
has answer: http://stackoverflow.com/a/47648795
accepted answer: http://stackoverflow.com/a/47648795
possible better answer: http://stackoverflow.com/a/51745365
downvote count: 0
has answer: http://stackoverflow.com/a/49079562
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51745365
tagged with: tensorflow
score: 9
type: Question
has body: I'm trying to get a prediction with a custom input function with estimator.predict, but it gives me this: WARNING:tensorflow:Input graph does not contain a QueueRunner. That means predict yields forever. This is probably a mistake. It doesn't give me an error, but predict just says that its restoring parameters and doesn't return the actual predictions. Here is my code: test_data = [0.03, 0.91, 0.95, 0.10, 0.56, 0.93] test_data_in = { k: test_data[index] for index, k in enumerate(FEATURES) } print(test_data_in) def predict_input_fn(data_set): feature_cols = { k: tf.reshape(tf.constant(data_set[k], dtype=tf.float32), [-1]) for k in FEATURES } return feature_cols predictions = estimator.predict(input_fn=lambda: predict_input_fn(test_data_in)) print(list(predictions)) I've looked at this issue, but I couldn't find a solution related to my problem. Why does TensorFlow show this warning and how do I get rid of it?

http://stackoverflow.com/comment/80466585
type: QuestionComment
has text: first you need to search manage.py on your drives, then coy and paste its address and put it on command line like this: python "youraddress/manage.py" runserver
score: 1
comment on: http://stackoverflow.com/q/46760589
type: Comment

http://stackoverflow.com/comment/80615909
score: 0
comment on: http://stackoverflow.com/q/46834013
has text: @ juanpa.arrivillaga The error is related to accuracy_score() function.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80669300
type: QuestionComment
comment on: http://stackoverflow.com/q/46860908
score: 1
has text: what should be the result if `string1 = 'Hello how are you now?'` ? (`now?` added)
type: Comment

http://stackoverflow.com/q/46899627
score: 6
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/70374478
tagged with: date
type: Question
has title: Business Hours Between Two Dates in Pandas Dataframe (including holidays)
has answer: http://stackoverflow.com/a/46899909
downvote count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48965189
favorite count: 0
type: UnansweredQuestion
has body: Novice Python user here - I'm attempting to Calculate the Business Hours between two dates in a pandas DataFrame given 9am-5pm, Mon-Fri Working Hours and to exclude Australian Public Holidays. I have tried to hack together a lot of solutions over the past few days and apply it to my problem but I'm having significant trouble. I will post my current iteration but also looking for feedback as the best way to handle this overall and to gain some understanding of how to tackle these problems in the future. My lastest attempt is using pandas CDay then creating a custom holiday calendar for Australian dates which all seems to be working - it's then going from this step to applying it to the pandas dates which I am having trouble understanding. I am using a custom function from this https://codereview.stackexchange.com/questions/135142/calculate-working-minutes-between-two-timestamps/135200#135200 solution to count the minutes between the dates but having no luck. Appreciate any help! import datetime from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar from pandas.tseries.offsets import CDay class HolidayCalendar(AbstractHolidayCalendar): rules =[Holiday('New Years Day',year=2016,month=1,day=1), Holiday('Australia Day',year=2016,month=1,day=26), Holiday('Good Friday',year=2016,month=3,day=25), Holiday('Easter Monday',year=2016,month=3,day=28), Holiday('ANZAC Day',year=2016,month=4,day=25), Holiday('Queens Birthday',year=2016,month=6,day=13), Holiday('Christmas Day',year=2016,month=12,day=25), Holiday('Boxing Day',year=2016,month=12,day=26), Holiday('New Years Day',year=2017,month=1,day=1), Holiday('Australia Day',year=2017,month=1,day=26), Holiday('Good Friday',year=2017,month=4,day=15), Holiday('Easter Monday',year=2017,month=4,day=17), Holiday('ANZAC Day',year=2017,month=4,day=25), Holiday('Queens Birthday',year=2017,month=6,day=12), Holiday('Christmas Day',year=2017,month=12,day=25), Holiday('Boxing Day',year=2017,month=12,day=26), Holiday('New Years Day'…

http://stackoverflow.com/comment/80554990
has text: What language? What have you tried up to now?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46803997
score: 1

http://stackoverflow.com/q/46898979
answer count: 1
has comment: http://stackoverflow.com/comment/80746324
has comment: http://stackoverflow.com/comment/80746955
favorite count: 0
has title: How to check the channel order of an image?
tagged with: python
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80746724
accepted answer: http://stackoverflow.com/a/46903077
tagged with: python-imaging-library
downvote count: 0
has comment: http://stackoverflow.com/comment/80752392
linked to: http://stackoverflow.com/q/30802493
type: Question
has comment: http://stackoverflow.com/comment/80751099
tagged with: numpy
has answer: http://stackoverflow.com/a/46903077
has body: Question With an image loaded into Python as shown below, how do I know which order the channels are in? (e.g. BGR or RGB) Code from PIL import Image import numpy as np image_pil = Image.open("Stonehenge.jpg") image_np = np.array(image_pil) image_np[0][0] Result array([ 52, 123, 155], dtype=uint8) Specific question How do I know whether the 52 corresponds to the red channel, the blue channel, or a different channel? Or does this question not make sense on a conceptual level? Notes In a similar question for Java instead of Python, one person claims: If you are reading in the image file, or you have access to the code that reads in the file, know it is: BGR order if you used cv2.imread(), RGB order if you used mpimg.imread(), (assuming import matplotlib.image as mpimg) If you don't know how the file was opened, the accepted answer BufferedImage is great for Java.
tagged with: image
upvote count: 14
tagged with: colors
has comment: http://stackoverflow.com/comment/80747199
has comment: http://stackoverflow.com/comment/80746916

http://stackoverflow.com/q/46784471
has comment: http://stackoverflow.com/comment/80515309
downvote count: 1
has answer: http://stackoverflow.com/a/46785182
has comment: http://stackoverflow.com/comment/80515291
tagged with: flask
type: AnsweredQuestion
has body: I am a beginner with Flask and python. I want to create a handler function for paths that start with "/favicon". For example the following should be handled: /favicon /faviconFOO /favicon_bar /favicon/buzz /favicon1337 The following should not be handled: /favico /favicoN /whatever If Flask supporeted wildcards, it would be "/favicon*" EDIT: I don't need support for regular expressions. How can I do this?
has comment: http://stackoverflow.com/comment/80523380
linked to: http://stackoverflow.com/q/5870188
accepted answer: http://stackoverflow.com/a/46785182
has comment: http://stackoverflow.com/comment/80515420
favorite count: 0
tagged with: python-3.x
type: Question
score: 12
duplicate of: http://stackoverflow.com/q/5870188
tagged with: path
tagged with: python
answer count: 1
has title: Flask app route for paths that start with X
tagged with: app-route
upvote count: 13
has comment: http://stackoverflow.com/comment/80515745

http://stackoverflow.com/comment/80702785
score: 0
has text: That's what `isalnum()` does, makes sure the string is alpha-numeric chars
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46877887

http://stackoverflow.com/comment/80571608
has text: nope its fully readable and writable all sub-folders were generated dynamically...don't understand why my system can't detect its trace
score: 0
comment on: http://stackoverflow.com/q/46812002
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46823627
type: Answer
has comment: http://stackoverflow.com/comment/80594681
upvote count: 2
has comment: http://stackoverflow.com/comment/80596075
has comment: http://stackoverflow.com/comment/80597559
answers question: http://stackoverflow.com/q/46823480
score: 2
downvote count: 0
has body: You are forgetting to add in reference_date1 when calculating the the datetime using fromtimestamp(). Here is the updated code from datetime import datetime, timedelta reference_date1 = datetime(2001, 1, 1, 0, 0, 0) delta_since_reference = timedelta(seconds=530023775) print(str(reference_date1 + delta_since_reference)) print(datetime.fromtimestamp(530023775 + float(datetime.strptime(str(reference_date1), "%Y-%m-%d %H:%M:%S").strftime('%s')))) Which prints 2017-10-18 12:49:35 2017-10-18 12:49:35
has comment: http://stackoverflow.com/comment/80597132
has comment: http://stackoverflow.com/comment/80594598
has comment: http://stackoverflow.com/comment/80597439

http://stackoverflow.com/comment/114389352
comment on: http://stackoverflow.com/a/56312295
score: 0
type: AnswerComment
type: Comment
has text: In my case doesn' t work with python and but work with python3 thank you!

http://stackoverflow.com/q/46859958
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/80679195
answer count: 1
tagged with: unicode
has comment: http://stackoverflow.com/comment/80667551
favorite count: 0
downvote count: 3
has title: python3.6: can i use (\\u\w\w\w\w) to remove all unicode from tweet json
tagged with: regex
has answer: http://stackoverflow.com/a/46860067
has body: I was doing some twitter mining, and pulled the json of tweets into python3 via pandas before processing further, i noticed alot of the data was not consistent/clean or even useful to me (for now) so i used regex to make the string of tweet messages consistent or delete the offending item below is that: data['full_text'] = data['full_text'].replace('^@ABC(\\u2019s)*[ ,\n\t]*', '', regex=True) data['full_text'] = data['full_text'].replace('(\\n)', '', regex=True) data['full_text'] = data['full_text'].replace('(\\t)', '.', regex=True) data['full_text'] = data['full_text'].replace('(\\u2018)|(\\u2019)', "'", regex=True) data['full_text'] = data['full_text'].replace('(\\u201c)|(\\u201d)', "\"", regex=True) data['full_text'] = data['full_text'].replace('(\\n)|(\\t)', '', regex=True) i.e. - remove twitter handle if used at beginning (including punctuation linked to it) - json should have no issue with apostrophes. Keep everything consistent and replace unicode for left/right apostrophe with single ' -some tweets have backslash for quote, others use unicode. keep consistent and replace unicode with \" -delete all tabs -assume all new lines are new sentences so replace them with a fullstop as far as I'm aware, this this is all that is really needed. things like ~ are likely to be useless, with no real purpose to them. The tweets will also have emoticons that i dont care about (for now) the rest of the punctuation and these emoticons follow the format \uXXXX where x is a number or letter so my last line was planning to be the below: data['full_text'] = data['full_text'].replace('(\\u\w\w\w\w)', "", regex=True) given the large number of tweets i have, i cant verify if everything worked correctly, which is why if anyone could give some advice? From my research i kept seeing people post things like: ([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF]) but when i try these, i also still see emoticons etc left in the json. So why not jus…
tagged with: python-3.x
linked to: http://stackoverflow.com/q/13729638
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/80667566

http://stackoverflow.com/comment/80727575
score: 0
comment on: http://stackoverflow.com/q/46890172
type: QuestionComment
has text: Presumably you tried something? What didn't work? In my last job, I used `setx` to put python in the path when there was mandatory User Acount Control. That allows you to modify the path without admin rights.
type: Comment

http://stackoverflow.com/a/46849578
downvote count: 0
answers question: http://stackoverflow.com/q/46849507
type: Answer
has body: As mentioned by @JeanFrancoisFabre, this is the perfect example for collections.Counter: from collections import Counter text = """CPO 1 CL 1 SL 1 EL 1 CPO 1 SL 1 CPO 1""" count = Counter() for line in text.split("\n"): k,v = line.split() count[k] += int(v) print(count) Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1}) If you want lowercase keys, you could use count[k.lower()] += int(v): Counter({'cpo': 3, 'sl': 2, 'cl': 1, 'el': 1}) If the quantity is always 1, you could simply write a one-liner: Counter(line.split()[0] for line in text.split("\n")) # Counter({'CPO': 3, 'SL': 2, 'CL': 1, 'EL': 1})
has comment: http://stackoverflow.com/comment/80648702
has comment: http://stackoverflow.com/comment/80648544
upvote count: 5
score: 5

http://stackoverflow.com/comment/80734521
type: AnswerComment
comment on: http://stackoverflow.com/a/46858837
type: Comment
has text: @lorsp000 I made a change to `pointers.i` that might fix the problem. Your compiler is indicating that the initialization of `obj` can be skipped. I changed the way it was declared so SWIG will declare the variable at the top of the wrapper instead of inline.
score: 0

http://stackoverflow.com/comment/80525600
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46789278
has text: Need `df = df[df.groupby('wikidataType')['wikidataType'].cumcount() < 100]`
score: 0

http://stackoverflow.com/q/46855815
accepted answer: http://stackoverflow.com/a/46856186
tagged with: qcombobox
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has title: Using new style signal and slots for combobox?
tagged with: qt-signals
tagged with: pyqt5
type: Question
has body: I have two lines using the old SIGNAL and SLOT style.. combobox.emit(SIGNAL("activated(int)"), combobox.currentIndex()) combobox.emit(SIGNAL("activated(const QString &amp;)"), combobox.currentText()) I was wondering what the new style would look like. I'm new to python and I don't have much experience with signals and slots. Is there a really good resource floating around that covers this? The documentation didn't really help me understand what was going on.
has answer: http://stackoverflow.com/a/46856186
downvote count: 0
tagged with: pyqt
answer count: 1
favorite count: 0

http://stackoverflow.com/q/46894556
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80759916
score: 1
tagged with: pyqt
has comment: http://stackoverflow.com/comment/80736953
has comment: http://stackoverflow.com/comment/82851717
downvote count: 0
favorite count: 0
has title: Install PyQt4 in Python 3 on mac
tagged with: python
tagged with: macos
has body: I am trying to install PyQt4 on my mac. My python version is 3.6.3. I've tried Homebrew to do that but it didn't work. The codes I used are as following in Terminal. brew install qt brew install sip --with-python3 brew install pyqt --with-python3 Also, I've set an path as following: PYTHONPATH=/usr/local/lib/python3.3/site-packages:$PYTHONPATH After running these installs, it does install PyQt on my mac but the version is PyQt5. However, the version I want is PyQt4. I've looked up all the similar questions here, but it all kinda out of date. If anyone knows how to solve this, please let me know. Appreciated!
answer count: 0
tagged with: homebrew
type: UnansweredQuestion

http://stackoverflow.com/q/46836053
type: AnsweredQuestion
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/46836563
downvote count: 1
type: Question
answer count: 1
has title: Can I have an array of nested numba objects?
has body: Say I have 2 classes, A and B, that I have jitted, where B has a list of A. Is this possible in numba? from numba import jitclass, deferred_type from numba.types import string spec = [('name', string)] @jitclass(spec) class A: def __init__(self, name): self.name = name a_type = deferred_type() a_type.define(A.class_type.instance_type) spec2 = [('name', string), ('alist', a_type[:])] @jitclass(spec2) class B: def __init__(self, name, alist): self.name = name self.alist = alist When I run this, I get the following error: python3: /opt/miniconda/conda-bld/llvmdev_1498055795382/work/llvm-4.0.0.src/lib/IR/DataLayout.cpp:638: unsigned int llvm::DataLayout::getAlignment(llvm::Type*, bool) const: Assertion `Ty-&gt;isSized() &amp;&amp; "Cannot getTypeInfo() on a type that is unsized!"' failed. Aborted (core dumped) Is there any way I could get around this error?
favorite count: 0
has answer: http://stackoverflow.com/a/46836563
tagged with: llvm
tagged with: numba
tagged with: python

http://stackoverflow.com/q/46822679
tagged with: keras
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46830288
type: AnsweredQuestion
has body: I'm using Keras for a (character) sequence-to-sequence RNN application. Since I have a relatively small set of examples of A -> B, and a much larger set of examples of B, I decided to try an autoencoder approach: first train a network to learn the identity function on B, producing an embedding for members of B, then train a network to learn A -> embedding(B). By combining the second network with the decoder-half of the first network, hopefully it will generalize to produce plausible Bs. The code, modeled after the Building Autoencoders in Keras tutorial, looks something like this (several layers, dropouts, regularizations, etc. have been left out for the sake of simplicity): class Example: def __init(self, ...): # Sets dense_size, rnn, rnn_size, embed_size, input_len, output_len, etc. def apply_encoder(self, input_word): input_masked = Masking()(input_word) input_dense = TimeDistributed(Dense(self.dense_size), name='input_dense')(input_masked) rnn = self.rnn(self.rnn_size, name='input_rnn')(input_dense) embedding = Dense(self.embed_size, name='embedding')(rnn) return embedding def apply_decoder(self, embedding): repeated = RepeatVector(self.output_len, name='repeat')(embedding) rnn = self.rnn(self.rnn_size, name='output_rnn')(repeated) output_dense = TimeDistributed(Dense(self.dense_size), name='output_dense')(rnn) output_word = TimeDistributed( Dense(self.chars, activation='softmax'), name='output_word' )(output_dense) return output_word def build_net(self): input_word = Input(shape=(self.input_len, self.chars), name='input_word') embedding = self.apply_encoder(input_word) output_word = self.apply_decoder(embedding) self.autoencoder = Model(input_word, output_word) self.encoder = Model(input_word, embedding) embed_input = Input(shape=(self.embed_size,), name='input_embedding') decoder_output = self.apply_decoder(embed_input) self.decoder = Model(embed_input, decoder_output) def save_models(self): open('models/autoencoder.json', 'w').write(self.autoencoder.to_json()…
tagged with: machine-learning
type: Question
score: 4
accepted answer: http://stackoverflow.com/a/46830288
upvote count: 4
has title: Training two Keras models in tandem with partially shared weights
linked to: http://stackoverflow.com/q/40278868
downvote count: 0
answer count: 1

http://stackoverflow.com/q/46774696
has comment: http://stackoverflow.com/comment/80496164
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80495957
has comment: http://stackoverflow.com/comment/80495074
has answer: http://stackoverflow.com/a/46774771
has comment: http://stackoverflow.com/comment/80496193
score: -1
has body: I have a string like so: string = "abc" my dictionary will have a key for every letter and number in the alphabet: letters = {"a" : "Ayeee", "b" : "Beeee", "c" : "Seee"} how do I use the letters within the string as a key to print my dictionary so the end result will be similar to: print(letters["a"], letters["b"]) output: Ayeee Beeee but I want to be able to take in a string of any length, and I don't want to use loops. The only thing I could think of is converting the string to a list, but then I really don't know what to do from there. Thanks for the help!
has comment: http://stackoverflow.com/comment/80496030
has comment: http://stackoverflow.com/comment/80495876
answer count: 3
upvote count: 0
has title: Using a string as a dictionary key?
favorite count: 0
has comment: http://stackoverflow.com/comment/80495883
has answer: http://stackoverflow.com/a/46774920
has comment: http://stackoverflow.com/comment/80495884
tagged with: python
has comment: http://stackoverflow.com/comment/80495219
has comment: http://stackoverflow.com/comment/80495230
has answer: http://stackoverflow.com/a/46774736
has comment: http://stackoverflow.com/comment/80496065
has comment: http://stackoverflow.com/comment/80496102
type: UnansweredQuestion

http://stackoverflow.com/a/46762045
answers question: http://stackoverflow.com/q/46761643
upvote count: 1
has body: This is too complex to write code for you, so a conceptual answer: Use find module locally on path in a loop over packages. Flatten the results to get a list of paths to existing files in a variable named files_before. Use build web packages task as posted in your question. Use find module locally on path in a loop over packages (same as the first task). Flatten the results to get a list of paths to existing files in a variable named files_after. Use copy module (not synchronize) in a loop over a difference between files_after and files_before. You can implement flattening either in separate set_fact tasks, or directly in the with_items declaration in the last task. You might also have to use path filters and string manipulation to convert paths to relative ones to specify destination directories. Now, if your build process creates also subdirectories and you want to retain the structure, add tasks equivalent to the above ones, but limit find scope to directories and use file module to create them on targets machines. If you think that the above looks complicated, it is, but bear in mind that you specified the requirement and the tool. On top of that, the whole play would be able to run only once (unless you deleted and recreated the local repository earlier in the play).
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46761643
score: 1

http://stackoverflow.com/q/46878848
type: AnsweredQuestion
tagged with: thread-safety
type: Question
accepted answer: http://stackoverflow.com/a/46895658
has title: Flask/RabbitMQ: consume messages on a separate thread than the app
downvote count: 0
tagged with: flask
has body: I have a Flask microservice which serves user requests by an endpoint (say): /getdata The data can be fetched in one of the two ways 1) cache or 2) from database directly - if the cache is in the process of being updated Another service updates the database (thus making the cache stale). Once the service is done updating the database, it publishes a message to the rabbitmq stating: "update done" Back to the microservice: I'd like it to have two threads: Thread 1: runs the app.run() Thread 2: subscribes to the queue - where "update done" messages are published Given the two threads, I don't want the /getdata to be fetching database from the cache when it's being updated. At the same time, I don't want to update the cache when data is being fetched from the endpoint. Here's one solution I can think of: 1) Have a threading.Lock() as a "global" 2) /getdata checks if the lock is available; if so, it will acquire, fetch data from cache and release the lock. If the lock is unavailable, it will fetch the data from the database directly, thereby incurring a performance hit - but still getting the "latest" data 3) RabbitMQ "subscriber" checks the state of the lock; if so, it acquires the lock , updates the cache from the database and releases the lock. If not, it adds the request to a local "queue", and waits for say one minute before trying to acquire the lock again. When it does, it will pop the first item from queue and update the cache from the database. My questions: Given the multitude of libraries and options in Python/Flask - is there a library that allows me to do task like this in a "safe" way (I am using pika for rabbitmq access) Is it possible to launch the flask app.run() via one thread and the queue subscriber via another (i.e. in if __name__ == "main": ) How do I declare a "global" threading.Lock() which can coordinate the two threads? Notes: I expect that in the worse case the lock won't be acquired for more than one minute.
answer count: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/46895658
tagged with: multithreading
tagged with: python
tagged with: rabbitmq
score: 2

http://stackoverflow.com/q/46852876
has title: Converting URL titles to standard titles
has answer: http://stackoverflow.com/a/46853231
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80653382
score: 0
has answer: http://stackoverflow.com/a/46853335
has comment: http://stackoverflow.com/comment/80653344
tagged with: python
has body: Suppose I have this following list [('2015-2016-regular', '2016-playoff'), ('2016-2017-regular', '2017-playoff'), ('2017-2018-regular',)] which represents the two previous complete NHL years and the current one. I would like to convert it so that It will give me [('Regular Season 2015-2016 ', 'Playoff 2016'), ('Regular Season 2016-2017', 'Playoff 2017'), ('Regular Season 2017-2018 ',)] My English is bad and those writing will be used as titles. Are there any errors in the last list? How could I construct a function which will do such conversions in respecting the 80 characters long norm?
accepted answer: http://stackoverflow.com/a/46853231
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46853335
tagged with: data-conversion

http://stackoverflow.com/comment/80607208
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46820036
score: 0
has text: Are you trying to use os without importing it?

http://stackoverflow.com/comment/80602088
comment on: http://stackoverflow.com/a/46813694
has text: @galaxyan nothing prevents you from mutating a list in place. What you usually want to avoid is adding to/removing from a sequence while you iterate over this same sequence as it messes up the iterator...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/111696921
has text: As has been noted, `.split(expand=True).stack().value_counts()` takes a TON of extra memory if your string data is variable length. Try this `.str.split().explode().value_counts()`. It does the exact same thing without allocating any extra memory.
type: Comment
comment on: http://stackoverflow.com/a/46786277
score: 3
type: AnswerComment

http://stackoverflow.com/comment/136747528
comment on: http://stackoverflow.com/a/46866058
type: AnswerComment
has text: concat is a bad idea... This is not the same than if you merge on a specific column and you may have unexpected results.
score: 0
type: Comment

http://stackoverflow.com/a/46879574
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46879491
type: Answer
accepted answer of: http://stackoverflow.com/q/46879491
has body: To set the coordinates of the Alien sprite on the top left corner, you should use : self.rect.x = 0 self.rect.y = 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80713598

http://stackoverflow.com/comment/80736733
has text: Are you using Pandas?
score: 0
comment on: http://stackoverflow.com/q/46894751
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80673167
has text: [Edit] your question to include your input, your expected output __and__ your observed output.
comment on: http://stackoverflow.com/q/46862849
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/46835568
has body: when I open the link 0.0.0.0:5000 in my browser I always get the message on the browser "This site can't be reached" the code seems to be working since I get this message on the console Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) here is the code that I am using from flask import Flask, render_template, request from scipy.misc import imsave, imread, imresize import numpy as np import keras.models import re import sys import os from load import * sys.path.append(os.path.abspath('./model')) app = Flask(__name__) global model, graph model, graph = init() def convertImage(imData): imgstr = re.search(r'base64(.*'.imData).group(1) with open('output.png', 'wb') as output: output.write(imgstr.decode('base64')) @app.route('/') def index(): return render_template('index.html') @app.route('/predict', methods=['GET', 'POST']) def predict(): imData = request.get_data() convertImage(imData) x = imread('output.png', mode = 'L') x = np.invert(x) x = imresize(x, 48, 48) x = x.reshape(1,48,48,1) with graph.as_default(): out = model.predict(x) response = np.array_str(np.argmax(out)) return response if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
upvote count: 16
type: AnsweredQuestion
score: 15
has answer: http://stackoverflow.com/a/46836687
tagged with: google-chrome
downvote count: 1
type: Question
has title: This site can’t be reached [flask, python]
has answer: http://stackoverflow.com/a/71076388
possible better answer: http://stackoverflow.com/a/54495499
has answer: http://stackoverflow.com/a/65467115
has answer: http://stackoverflow.com/a/69588149
has answer: http://stackoverflow.com/a/64479367
has answer: http://stackoverflow.com/a/54495499
has comment: http://stackoverflow.com/comment/80619136
has comment: http://stackoverflow.com/comment/80619440
accepted answer: http://stackoverflow.com/a/46836687
has answer: http://stackoverflow.com/a/65470780
answer count: 7
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/80618967
tagged with: python

http://stackoverflow.com/q/46831915
downvote count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/46853885
has answer: http://stackoverflow.com/a/46853885
favorite count: 0
tagged with: astronomy
tagged with: python
has answer: http://stackoverflow.com/a/46832217
accepted answer: http://stackoverflow.com/a/46832217
type: AnsweredQuestion
tagged with: fits
has title: Picking out a single row in a FITS table with Astropy
type: Question
answer count: 2
tagged with: idl-programming-language
has comment: http://stackoverflow.com/comment/80779747
has body: I "simply" want to read in an (Astronomy) FITS table, and pick out all the information on one object via its name:: from astropy.io import fits dr7q = fits.open('Shen_dr7_bh_May_2010.fits') tbdata = dr7q[1].data w = tbdata[tbdata['SDSS_NAME'] == 'J000006.53+003055.2'] print(tbdata[w]) gives an IndexError: arrays used as indices must be of integer (or boolean) type Trying: mask = (tbdata['SDSS_NAME'] == 'J000006.53+003055.2') print(mask) then gives an array the size of the original FITS table file. This is straight-forward in IDL. Why's it so hard here?!?!
tagged with: astropy
score: -1

http://stackoverflow.com/q/46764881
accepted answer: http://stackoverflow.com/a/46765184
upvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Python HTTPServer serve_forever console input
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I am writing a very simplistic application in Python3 which simply runs certain server-side commands from POST input received via the Python http.server.BaseHTTPRequestHandler, HTTPServer modules. Currently, my code is as follows: mysql_tools.f_print("Starting HTTP server on %s:%s.." % SERVER_ADDRESS) httpd = HTTPServer(SERVER_ADDRESS, S) mysql_tools.f_print("Server started. Now serving port %s." % SERVER_ADDRESS[1]) httpd.serve_forever() Where S is the BaseHTTPRequestHandler class. Now, I want to be able to have console input also. The application runs in a CMD window and simply displays "Server started. Now serving port 1010", however I want to be able to type, for example, "stop" into the CMD window and process accordingly, or "restart" or "forcerequest" etc etc. But as you may know, it does not have any input because of the "serve_forever()", it disregards any future lines of code as it appears to loop indefinitely. Any advice or alternate ways to serve the port would be appriciateted.
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/46765184

http://stackoverflow.com/a/46838174
answers question: http://stackoverflow.com/q/46837820
score: 0
has body: You can easily achieve this using os.path.join. I have used H:\os directory as my desired directory and shovon as my desired filename. Change it as your own input. import os test = os.path.join("H:",os.sep,"os","shovon") if os.path.exists(test + '.csv'): system_file = open(test + '.csv', 'a') print("File already exists") else: system_file = open(test + '.csv', 'w') print("New file is created") The os.sep is used for adding separator sign based on your operating system. The path are concatenated as string and drive letter is with an extra colon as you see.
type: Answer

http://stackoverflow.com/comment/80698368
type: QuestionComment
comment on: http://stackoverflow.com/q/46875691
has text: It's plt.savefig()
score: 0
type: Comment

http://stackoverflow.com/comment/83447977
comment on: http://stackoverflow.com/a/46775606
type: AnswerComment
type: Comment
has text: I believe the only thing the [extra] syntax does is specify additional from extras_requires that will be installed. That is, `pip install splinter` will install fewer requirements than `pip install splinter[django]`. The additional packages that are installed may indeed (and probably do) enable additional features of splinter to work, but it doesn't change anything about the splinter package itself. It just tells pip about additional dependencies.
score: 1

http://stackoverflow.com/a/46759443
answers question: http://stackoverflow.com/q/46759206
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80464397
has body: You can do this: class Baseline: def __init__(self): self.benchmark = input("Select benchmark: ") self.model = input("Enter model: ") self.processor = input("Enter processor: ") Which will make your code less duplicated as creating new instances will be: old_server = inputs.Baseline() new_server = inputs.Baseline() Side note you can also implement the __str__ method to print it all out: def __str__(self): return '\n'.join(str(item) for item in self.__dict__.values()) And then printing is easy: print(old_server) As a general advice I wouldn't count on a user's "free" input for processor models and benchmarks since most of the time it contains a mixture of lowercase, uppercase numbers etc. What I would do, especially because you said you want to use Flask (so thats going to be more simple), is narrow it down to the processor models and benchmarks you support only. Implementation-wise this means a drop-down list on your application and a set or list of the models, benchmarks etc. This will also save you the trouble of input validation. In the case that not all of the models go with all of the benchmarks you can use dict to do some book-keeping. But if the book-keeping is getting complicated, consider using classes for "automatic" book-keeping. Those classes can then be pickled, jsonified and other methods for saving them into databases. If you share more code, we could help a little bit more. In any case, I suggest you post this question on code review for deeper analysis.

http://stackoverflow.com/a/46869959
answers question: http://stackoverflow.com/q/46853754
score: 0
type: Answer
has body: You are getting the index out of range because your "vec" list has zero elements. You need to initialize it in some way. One way is to do something like: vec = [e] * 100 This will create a list of 100 elements, each initialized to the value of e.

http://stackoverflow.com/a/47215471
downvote count: 0
has body: The first hex of your result, "'" is exactly 39 in signed char. In python, you can use built-in function ord("'") to get 39. You can probably get what you want in this python code value = '270000f31d32d1051400000000000000000000000006000000000000000000000000000000000000' result = binascii.unhexlify(value) bytes = [ord(x) for x in result] You will be getting this unsigned char: [39, 0, 0, 243, 29, 50, 209, 5, 20, 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]
type: Answer
answers question: http://stackoverflow.com/q/46849854
score: 2
upvote count: 2

http://stackoverflow.com/a/46814360
type: Answer
score: 6
has body: Since you want to retain the previous columns, you can make a Series out of the new columns, and then append that new Series object to the original Series. Keep in mind that the input to get_cols is an individual row (and is thus a Series) from the original DataFrame. import pandas as pd import numpy as np def get_cols(cols): col4 = cols[0] * 2 col5 = cols[1] * 2 col6 = cols[2] * 2 return cols.append(pd.Series([col4, col5, col6], index=['col4', 'col5', 'col6'])) col1 = [np.random.randn()] * 10 col2 = [np.random.randn()] * 10 col3 = [np.random.randn()] * 10 df = pd.DataFrame({'col1': col1, 'col2': col2, 'col3': col3 }) df = df.apply(get_cols, axis=1) print(df) col1 col2 col3 col4 col5 col6 0 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 1 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 2 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 3 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 4 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 5 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 6 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 7 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 8 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122 9 -0.809803 0.522547 0.064061 -1.619606 1.045093 0.128122
answers question: http://stackoverflow.com/q/46810642
downvote count: 0
upvote count: 6

http://stackoverflow.com/comment/80611061
type: Comment
has text: What is happening and what would you like to be happening?
score: 0
comment on: http://stackoverflow.com/q/46831733
type: QuestionComment

http://stackoverflow.com/comment/80641146
type: Comment
has text: What if i wanted to create a for loop that replaces for example \*\**TITLE*** with its respective 2 string list, \*\**IMGURL*** with its respective 2 string list, \*\**DESCRIPTION*** with its respective 2 string list, and so on for the rest of the placeholders?
comment on: http://stackoverflow.com/a/46846713
score: 0
type: AnswerComment

http://stackoverflow.com/q/46865289
type: AnsweredQuestion
has title: PyQt5 - Passed reference is None
upvote count: 2
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/80678082
has answer: http://stackoverflow.com/a/46865407
tagged with: qwidget
score: 2
tagged with: window
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/46865407
has body: so I'm pretty new to Python. And for the life of me can't figure out why the following code isn't working (I'm using PyQt5). I'm basically trying to have 2 widgets inside a stackedwidget so I can switch between them. And the button to switch from window 0 to window 1 would be in window 0 obviously. So I would need to be able to somehow reference the stackedwidget. But when I try to pass the stackedwidget as a reference, it complains that the variable is None, even when that shouldn't be the case. from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QGridLayout, QPushButton, QHBoxLayout, QVBoxLayout, QStackedWidget from PyQt5.QtCore import QCoreApplication class DeviceSelectionWindow(QWidget): def __init__(self, mainWindow): super().__init__() self.initUI() def initUI(self): testB = QPushButton("test",self) #------------------------------------------------------------ class ModeSelectionWindow(QWidget): def __init__(self, mainWindow): super().__init__() self.mainWindow = mainWindow self.initUI() def initUI(self): recordButton = QPushButton("Record tutorial") watchButton = QPushButton("Watch tutorial") recordButton.setFixedSize(200,100) recordButton.setStyleSheet("font-size:30px") watchButton.setFixedSize(200,100) watchButton.setStyleSheet("font-size:30px") recordButton.clicked.connect(self.mainWindow.setCurrentIndex(1)) #Add horizontal strech layout box (centered) hbox = QHBoxLayout() hbox.addWidget(recordButton) hbox.addWidget(watchButton) #Add vertical strech layout box (centered) vbox = QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) #------------------------------------------------------------ class MainWindow(QStackedWidget): def __init__(self, **kwargs): super().__init__(**kwargs) self.initUI() def initUI(self): self.resize(1200,600) self.centerWindow() self.setWindowTitle("MultiPov Tutorial") modeSelectionWindow = ModeSelectionWindow(self) deviceSelectionWindow = DeviceSelectionWindow(self) self.addWidget(modeSelectionWindow) self.addWidg…

http://stackoverflow.com/q/46889084
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has body: Let's say I have this object which is a core part of my system, and most of its work is to communicate with a remote agent - send tasks and get responses: class AgentAPI: ... # Constructor etc. def do_foo(self, args): .... # Send data and wait for response return result def do_bar(self, args): .... # Send data and wait for response return result The way I would go about unit-testing this object is with a mock, right? So: def test_agent_api_foo(): agent_api = AgentAPI(someargs) agent_api.do_foo = Mock() .... # test logic That means the methods are not really executed, of course... So how do I keep my unit-tests reliable on highly distributed systems?
has title: How to keep test coverage high when mocking?
has comment: http://stackoverflow.com/comment/80725310
has comment: http://stackoverflow.com/comment/80729735
has comment: http://stackoverflow.com/comment/80728700
has comment: http://stackoverflow.com/comment/80729666
has comment: http://stackoverflow.com/comment/80726219
has comment: http://stackoverflow.com/comment/80728240
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/80728746
tagged with: mocking
answer count: 0
type: UnansweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/comment/80710261
type: QuestionComment
comment on: http://stackoverflow.com/q/46881328
has text: Never try to manipulate IP addresses as strings. That is a recipe for failure. IP addresses are binary numbers.
score: 0
type: Comment

http://stackoverflow.com/a/46799832
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/80547055
has comment: http://stackoverflow.com/comment/80546939
score: 2
has comment: http://stackoverflow.com/comment/80547022
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46799766
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46799766
has body: You can use pivot and then plot df.pivot('Type', 'Name', 'Count').plot(kind = 'bar', stacked = True, color = ['b','g','orange','m', 'r']) Edit: To sort the values df.pivot('Type', 'Name', 'Count').sort_values(by = 'A', ascending = False, axis = 1)\ .plot(kind = 'bar', stacked = True, color = ['g','r','b','orange', 'm'])

listbox
tags question: http://stackoverflow.com/q/46787429
tag name: listbox
type: Tag

http://stackoverflow.com/q/46868798
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/80684849
tagged with: pandas
has answer: http://stackoverflow.com/a/46868834
answer count: 1
has body: I have a pandas column like this train['finally'].head(5) 0 [0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, ... 1 [0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 6, 0, 0, 0, 0, ... 2 [0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, ... 3 [2, 0, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, ... 4 [0, 0, 0, 0, 7, 0, 0, (3, 1), 0, 0, 0, 0, 0, 0... I want to use it to create a separate pandas data frame using this column I tried using this visits_df = train['finally'].apply(lambda x: pd.Series(str(x).split(','))) and this df = pd.DataFrame(train.visits.str.split(' ').tolist()) I tried splitting on commas and space, but the same result but the problem is that there are some elements inside the column that are tuple like this (3, 1) I tried splitting on commas and space, but the same result. 0 [0 0 0 0 3 0 0 0 0 0 ... 0 2 3 0 0 0 0 0 0] NaN 1 [0 0 0 4 0 0 0 5 0 0 ... 6 0 0 4 0 0 (2 4) 0 0] 2 [0 0 0 0 0 0 0 3 0 0 ... 5) 0 3 0 0 0 0] NaN NaN NaN 3 [2 0 7 2 0 0 0 0 0 0 ... 0 0 5 0 0 6 0 0] NaN NaN 4 [0 0 0 0 7 0 0 (3 1) 0 ... 0 0 0 0 0 0 0 0 0 0] it splits tuples into separate columns and I see extra columns and there should only be 143 columns How do I fix this?
has title: How do I create a data frame from a list that contains different elements in pandas?
accepted answer: http://stackoverflow.com/a/46868834
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80684845

http://stackoverflow.com/a/46881859
answers question: http://stackoverflow.com/q/46880810
upvote count: 1
downvote count: 0
has body: date_from = fields.Date(string='From date', required=True,default=lambda *a: time.strftime('%Y-%m-%d')) did you tried this
type: Answer
has comment: http://stackoverflow.com/comment/80721653
score: 1
has comment: http://stackoverflow.com/comment/80721976

http://stackoverflow.com/q/46873212
accepted answer: http://stackoverflow.com/a/46882828
tagged with: windows
has answer: http://stackoverflow.com/a/46883057
tagged with: python
tagged with: cmd
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80694298
score: 6
linked to: http://stackoverflow.com/q/46645190
type: Question
has answer: http://stackoverflow.com/a/46882828
has comment: http://stackoverflow.com/comment/80693880
answer count: 2
has title: Python to close own CMD shell window on exit
downvote count: 0
has body: I am running multiple processes (hundreds), each of which is in python and invoked using: command = 'start cmd /k call python %s' % (some_py_prog) os.system(command) where the /k leaves the cmd window open after execution. This is good to inspect for errors. However, as I call hundreds of jobs, my screen gets cluttered. How then to make python close its own host cmd window on successful completion only? I need the errored jobs to remain visible.
favorite count: 0
possible better answer: http://stackoverflow.com/a/46883057
linked to: http://stackoverflow.com/q/25343351

http://stackoverflow.com/q/46795989
score: 0
tagged with: python
tagged with: css
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46796018
tagged with: jinja2
type: Question
accepted answer: http://stackoverflow.com/a/46796018
has body: In a small blog application I pull the data from the database and show each post similiar to this: {% extends 'layout.html' %} {% block content %} Single post --> {% endblock %} Posts are in markdown format. Is it possible to change the class name of the first paragraph like this: [I suppose may be it should be done with Jquery more easy] This is first paragraph Another paragraph . . . Update : Problem is solved. It seems that I made a typo using this method. https://jsfiddle.net/qd0pb41v/
has title: Flask how to apply the first paragraph of a post different class attribute
answer count: 1
tagged with: jquery
tagged with: flask

http://stackoverflow.com/q/46902362
tagged with: ipython
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I'm using python's CatBoostClassifier(). Can I change its verbose to an int? The output is currently the measured loss functions to stdout, every single iteration, turning this output exhaustively long to analyse. I'd like to see this output in 50-iterations intervals, like verbose=50 (verbose=int). Is this possible? If so, how?
has answer: http://stackoverflow.com/a/51193804
accepted answer: http://stackoverflow.com/a/51193804
downvote count: 0
score: 1
tagged with: machine-learning
tagged with: catboost
type: Question
has title: Can Catboost's verbose be an int?

http://stackoverflow.com/q/46781708
has comment: http://stackoverflow.com/comment/80509764
favorite count: 0
has comment: http://stackoverflow.com/comment/80509783
has comment: http://stackoverflow.com/comment/80509916
has answer: http://stackoverflow.com/a/46781740
has title: Save filenames as variable's name in Python
tagged with: python
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/14622314
tagged with: filenames
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I want to save my python to json file, but the thing is, I need to name my json file's name as title's name. code: data={ "Title" : title.text, "Registration": doctor.text, "Keywords": list2, "Article": list } #title.text="banana" with open('title.text.json', 'w',encoding='UTF-8') as f: json.dump(data, f,ensure_ascii=False) The result I expected: Save it as banana.json Edit: It works with this with open('%s.json' % title_tag.text, 'w',encoding='UTF-8') as f: json.dump(data, f,ensure_ascii=False)
has comment: http://stackoverflow.com/comment/80509923
score: -2
downvote count: 2
accepted answer: http://stackoverflow.com/a/46781740
answer count: 1

http://stackoverflow.com/comment/80613542
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46832711
has text: The error message does seem to indicate a different line than the ones you posted: os.rename(self._filename, self._backupfilename)

http://stackoverflow.com/comment/80686727
comment on: http://stackoverflow.com/q/46869701
has text: You could use format to output the int and other variable. eg. print("Hello {} , what would you like? You have $ {} ".format(name, currency))
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46842774
tagged with: django
tagged with: python
tagged with: google-analytics
has title: Add Aldryn Google Analytics to Django CMS
score: 1
has answer: http://stackoverflow.com/a/46845273
type: Question
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46906111
tagged with: django-cms
tagged with: divio
has body: I currently have a django cms website and will like to have google analytics installed, using the aldryn-google-analytics plugin. I don't have a Divio Cloud account, and I'm really new to python. May I seek your advice on the GitHub files to be added to my project please and where the files should be placed into project.
type: UnansweredQuestion

http://stackoverflow.com/comment/80511582
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46777236
has text: Hmmm. Are you sure? I tried just now and it works. Gave me : `[(0.27, 0.56), (0.24, 0.06), (0.44, 0.35)]`
type: Comment

http://stackoverflow.com/a/46749024
answers question: http://stackoverflow.com/q/46748917
type: Answer
has comment: http://stackoverflow.com/comment/80444213
has body: See if this helps you understand what you are doing: import numpy as np a = np.array([1,2,3,4]) print(a) old_a = a for x in range(0,1): new_a = old_a new_a[0] = old_a[1] print new_a new_a[1] = old_a[2] print new_a new_a[2] = old_a[3] print new_a new_a[3] = old_a[0] print(new_a) [1 2 3 4] [2 2 3 4] [2 3 3 4] [2 3 4 4] [2 3 4 2] So when you do this new_a[3] = old_a[0], position O is already "2". Below gives you what you expected. for x in range(0,1): new_a = old_a.copy() new_a[0] = old_a[1] print new_a new_a[1] = old_a[2] print new_a new_a[2] = old_a[3] print new_a new_a[3] = old_a[0] print(new_a) [1 2 3 4] [2 2 3 4] [2 3 3 4] [2 3 4 4] [2 3 4 1] The fastest way to do this is 'fancy' indexing : a = np.array([1,2,3,4]) new_a = a[np.array([1,2,3,0])] print new_a array([2, 3, 4, 1])
has comment: http://stackoverflow.com/comment/80444487
score: 0

http://stackoverflow.com/q/46768660
has comment: http://stackoverflow.com/comment/80482827
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Why doesn't for loop run through all my readlines?
accepted answer: http://stackoverflow.com/a/46768997
answer count: 4
has comment: http://stackoverflow.com/comment/80484065
possible better answer: http://stackoverflow.com/a/46768828
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/80483052
downvote count: 1
has answer: http://stackoverflow.com/a/46768997
type: Question
has answer: http://stackoverflow.com/a/46768887
has comment: http://stackoverflow.com/comment/80483406
has answer: http://stackoverflow.com/a/46768975
has comment: http://stackoverflow.com/comment/80482851
has comment: http://stackoverflow.com/comment/80482630
has body: Trying to get it to run through more than 3 lines of text but the two I have now don't even work properly. The textfile is 74,85,65,56 97,67,83,96 Here is the code I've been working on file = open('grades.txt','r') for x in file: read = file.readline() sep = read.split(",") def toNumbers(): changeNum = [eval(x) for x in sep] return changeNum def sumlist(): total = 0 sum(pls) average = sum(pls)/len(sep) print ("Your average is: ", average) def main(): sumlist() pls = toNumbers() main() Output should be Your average is: 70.0 Your average is: 85.75 What I'm getting is only this Your average is: 85.75 When I add in a third line in my textfile I get this error SyntaxError: unexpected EOF while parsing The third line is also just a row of numbers in the text file and can continue from there 74,85,65,56 97,67,83,96 10,20,30,40 Output should be Your average is: 70.0 Your average is: 85.75 Your average is: 25.0
has answer: http://stackoverflow.com/a/46768828
has comment: http://stackoverflow.com/comment/80482654
has comment: http://stackoverflow.com/comment/80483170

http://stackoverflow.com/comment/80703189
has text: Thank you for your patience and suggestions, Andrew. I've edited initial post and done my best to be clearer. Regarding Pandas, I suppose I can, though I don't know how, yet.
comment on: http://stackoverflow.com/q/46870841
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46830352
has body: ret = {'complete': True} if company_director: for field, value in company_director.items(): if value in [None, ""]: ret['complete'] = False break
has comment: http://stackoverflow.com/comment/80646108
has comment: http://stackoverflow.com/comment/80608547
upvote count: 0
has comment: http://stackoverflow.com/comment/80609630
has comment: http://stackoverflow.com/comment/80633535
answers question: http://stackoverflow.com/q/46830120
has comment: http://stackoverflow.com/comment/80610240
type: Answer
has comment: http://stackoverflow.com/comment/80608616
downvote count: 1
has comment: http://stackoverflow.com/comment/80608344
has comment: http://stackoverflow.com/comment/80646437
score: -1

c++
tags question: http://stackoverflow.com/q/46898420
tags question: http://stackoverflow.com/q/46884404
tags question: http://stackoverflow.com/q/46753162
tags question: http://stackoverflow.com/q/46813827
tags question: http://stackoverflow.com/q/46865052
tags question: http://stackoverflow.com/q/46864368
tags question: http://stackoverflow.com/q/46775869
tags question: http://stackoverflow.com/q/46878736
tags question: http://stackoverflow.com/q/46798489
type: Tag
tags question: http://stackoverflow.com/q/46896907
tags question: http://stackoverflow.com/q/46838415
tags question: http://stackoverflow.com/q/46790385
tags question: http://stackoverflow.com/q/46769933
tags question: http://stackoverflow.com/q/46901188
tags question: http://stackoverflow.com/q/46863221
tags question: http://stackoverflow.com/q/46825656
tags question: http://stackoverflow.com/q/46892857
tags question: http://stackoverflow.com/q/46780215
tags question: http://stackoverflow.com/q/46891823
tags question: http://stackoverflow.com/q/46867307
tags question: http://stackoverflow.com/q/46860743
tags question: http://stackoverflow.com/q/46771550
tags question: http://stackoverflow.com/q/46773858
tags question: http://stackoverflow.com/q/46893785
tags question: http://stackoverflow.com/q/46845656
tag name: c++
tags question: http://stackoverflow.com/q/46855221
tags question: http://stackoverflow.com/q/46846754

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

http://stackoverflow.com/comment/80683749
score: 2
comment on: http://stackoverflow.com/q/46868182
type: Comment
type: QuestionComment
has text: `warm = max(int(climate[i][3]), warm)`

http://stackoverflow.com/a/46821242
type: Answer
upvote count: 4
has body: The boto3 library does not support async calls. There is a library that supports S3 with some testing on SQS called aiobotocore. These links have more information: aiobotocore Support asyncio
downvote count: 0
answers question: http://stackoverflow.com/q/46821113
has comment: http://stackoverflow.com/comment/80590888
score: 4

http://stackoverflow.com/comment/90496774
comment on: http://stackoverflow.com/q/46831783
score: 1
type: Comment
type: QuestionComment
has text: @FrederickNord done.

http://stackoverflow.com/comment/80687628
type: Comment
has text: What is `df.index`?
comment on: http://stackoverflow.com/q/46870095
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80610837
has text: What is the process of taking a folder containing a `Django` project and "make it work" with the updated versions of `Python` and `Django` using `virtualenv`?
comment on: http://stackoverflow.com/a/46822871
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/46809135
has answer: http://stackoverflow.com/a/75981582
favorite count: 0
has answer: http://stackoverflow.com/a/46810257
answer count: 3
tagged with: python
has body: I try to run a selenium program on a Linux machine.But I got the exceptions: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 154, in __init__ keep_alive=True) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 151, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 240, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 1 How can I fix the exceptions? Thanks for helping.
tagged with: selenium-webdriver
type: UnansweredQuestion
score: 58
downvote count: 2
has comment: http://stackoverflow.com/comment/80573421
type: Question
has title: Webdriver Exception:Process unexpectedly closed with status: 1
upvote count: 60
has comment: http://stackoverflow.com/comment/80565399
has answer: http://stackoverflow.com/a/47642457

http://stackoverflow.com/comment/80922080
comment on: http://stackoverflow.com/a/46965520
has text: excellent work! full of new details! after click CSV, it is very difficult to select "save file" and 'OK' in the pop-out window, right?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80704644
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46878400
score: 0
has text: Yes there is a way. If you were to provide an [MCVE](https://stackoverflow.com/help/mcve) it would greatly increase your chances of getting a useful answer.

http://stackoverflow.com/comment/80733399
type: AnswerComment
has text: It gives me this error: sys:1: DtypeWarning: Columns (2,5,21,25,26,28,30,31,32,61,63,64,66,67,87,151,158) have mixed types. Specify dtype option on import or set low_memory=False.
comment on: http://stackoverflow.com/a/46892982
type: Comment
score: 0

http://stackoverflow.com/comment/80562778
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46807882
has text: But I would like to add, not assign. I cannot add more values than one if this happens

http://stackoverflow.com/a/46749917
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46749826
has body: An "accumulator" is a variable that holds the temporary results of a calculation that is being done using a loop. For example, to sum a list of integers, you can set the accumulator variable to zero, then use a loop to add each integer in the list to the accumulator. When the loop is finished, the accumulator's value is the sum of the list. In your problem, s1 holds the 1st, 3rd, 5th, 7th, ... letters of the alphabet, while s2 holds the 2nd, 4th, 6th, 8th, ... letters. You could build up the entire alphabet by taking the first letter in s1 followed by the first letter in s2, then adding the second letter in s1 followed by the second letter in s2, then ... So we can use an accumulator to add each of those letters, one at a time. The range(n) function gives the integers below the value of n, starting with 0. We can use those integers as indices into the s1 and s2 strings to get one character at a time. Much more can be said about range()--you should read a tutorial to learn more, since this is not a site for tutorials. Here is some code that does what you want. Note that this depends on the two input strings having the same length--an error occurs otherwise. I changed the variable names to make them more self-documenting. You should note that this code is not "Pythonic" in its use of an index. There are better ways to do this, but they do not use range(). string1 = 'acegikmoqsuwy' string2 = 'bdfhjlnprtvxz' accum = '' for index in range(len(string1)): accum += string1[index] + string2[index] print(accum) The printed result is the alphabet: abcdefghijklmnopqrstuvwxyz
downvote count: 0
upvote count: 2

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

http://stackoverflow.com/q/46796570
answer count: 1
has title: Converting text data into Json format
favorite count: 0
has comment: http://stackoverflow.com/comment/80580004
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80627203
has comment: http://stackoverflow.com/comment/80549915
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46863491
has body: I am beginner to Python. I have to convert the text data into Json Format Here is the sample text data extracted from the table structure below: Metric - Column 1 , Design Project - Column 2 , Design Target* - Column 3 , Median Property* - Column 4 Metric Design Project Design Target* Median Property* Source EUI (kBtu/ft²) 3.1 Not Available 127.9 Site EUI (kBtu/ft²) 1.0 Not Available 40.7 Source Energy Use (kBtu) 314.0 Not Available 12,793.0 Site Energy Use (kBtu) 100.0 Not Available 4,074.2 Energy Cost ($) 2,000.00 Not Available 81,484.00 Total GHG Emissions (Metric Tons CO2e) 0.0 Not Available 0.5 ENERGY STAR score (1-100) Not Available 75 50 Here is the code below: import csv import json with open('output.txt', 'r') as csvfile: # Opens file filereader = csv.reader(csvfile, delimiter=' ') i = 0 header = [] out_data = [] for row in filereader: row = [elem for elem in row if elem] if i == 0: i+=2 row[1:3] = [row[1]+" "+row[2]] # Design Project key row[2:4] = [row[2]+" "+row[3]] # Design Target key row[3:5] = [row[3]+" "+row[4]] # Median Property* header = row else: row[0:3] = [row[0]+" "+row[1]+" "+row[2]] # Metric if len(row) == 5: # check conditions for better parse row[1:2] = [row[1]] # Design Project value row[2:4] = [row[2]+" "+row[3]] # Design Target _dict = {} for elem, header_elem in zip(row, header): _dict[header_elem] = elem out_data.append(_dict) print json.dumps(out_data) Above code which is working for first two lines of the data correctly. Here is the output of the code, [{"Metric": "Source EUI (kBtu/ft²)", "Design Target*": "Not Available", "Median Property*": "127.9", "Design Project": "3.1"}, {"Metric": "Site EUI (kBtu/ft²)", "Design Target*": "Not Available", "Median Property*": "40.7", "Design Project": "1.0"}] How can I make the complete data into a json format?
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80543313
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80568797
has answer: http://stackoverflow.com/a/46863491

http://stackoverflow.com/comment/80530758
has text: OK, this is great, thank you! Now there is just a small issue left (not for my specific case, but it may become a problem when your input data is larger than memory): `asyncio.as_completed` demands a list as parameter and it does not accept generators. Any way to work around this?
score: 0
comment on: http://stackoverflow.com/a/46789472
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80676403
score: 0
has text: It's less about the question but more about the answers (but maybe i misunderstood you).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46856915

http://stackoverflow.com/comment/80555653
type: Comment
type: QuestionComment
score: 2
has text: Just use `a = int(input(....))` and `b = int(input(...))` and `f = fun(a, b)`. Don't catch *all* exceptions, catch only `ValueError` and perhaps `ZeroDivisionError`, that way you can still use CTRL-C to end your program.
comment on: http://stackoverflow.com/q/46804344

http://stackoverflow.com/a/46882904
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/46882871
type: AcceptedAnswer
downvote count: 0
has body: You need to take the dictionary out of the inner for and asign the PWY_ID table: import numpy as np data2 = open('pathways.dat', 'r', errors = 'ignore') pathways = data2.readlines() special_line_indexes = [] line_cont = [] L_PRMR = [] #Left primary dict_comp = dict() #i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) for CUI in just_compound_id: PWY_ID = [] for i,line in enumerate(pathways): if '//' in line: #fint the indexes of the lines containing // special_line_indexes = i+1 elif 'REACTION-LAYOUT -' in line: if CUI in line: PWY_ID.append(special_line_indexes) dict_comp[CUI] = PWY_ID print(PWY_ID) print (dict_comp) EDIT The reason it's because you are over writting the value of the dictionary index (CUI) every time with a value (special_line_indexes) instead of an array of values. What you need it's to create the table in the inner for (with PWY_ID(append)), adding one element on each loop, and once you have created it, when you are finished with the for loop, then you need to assign that array to the dictionary (dict_comp[CUI] = PWY_ID). You get an empty array before the inner for each time with the PWY_ID = []
answers question: http://stackoverflow.com/q/46882871
has comment: http://stackoverflow.com/comment/80731855
type: Answer
has comment: http://stackoverflow.com/comment/80730858

http://stackoverflow.com/comment/80542110
type: Comment
score: 2
comment on: http://stackoverflow.com/a/46797660
type: AnswerComment
has text: @ScottBoston, thank you! But i think one should avoid doing such cosmetic things...

http://stackoverflow.com/comment/80623538
type: Comment
type: QuestionComment
has text: Should ssh-agent be run as a system service rather than via python?
comment on: http://stackoverflow.com/q/46837914
score: 0

http://stackoverflow.com/comment/80728842
type: AnswerComment
has text: What is the right way to use it? If the input is `x_ = tf.placeholder(tf.float32, [None, p, k]) ` how should `W` and the conv1d arguments be defined?
comment on: http://stackoverflow.com/a/46887600
type: Comment
score: 0

http://stackoverflow.com/comment/80698272
comment on: http://stackoverflow.com/q/46875637
score: 0
type: Comment
type: QuestionComment
has text: Well, did whatever you tried work?

http://stackoverflow.com/comment/80587101
type: AnswerComment
score: 0
type: Comment
has text: Oh... that is a cool approach. Do the wide_to_long once and the split the column. Nice, @MaxU!
comment on: http://stackoverflow.com/a/46819769

gunicorn
tags question: http://stackoverflow.com/q/46800575
type: Tag
tags question: http://stackoverflow.com/q/46779885
tags question: http://stackoverflow.com/q/46827358
tags question: http://stackoverflow.com/q/46754316
tags question: http://stackoverflow.com/q/46816287
tags question: http://stackoverflow.com/q/46802763
tags question: http://stackoverflow.com/q/46850121
tags question: http://stackoverflow.com/q/46860447
tags question: http://stackoverflow.com/q/46858541
tags question: http://stackoverflow.com/q/46814396
tags question: http://stackoverflow.com/q/46767101
tag name: gunicorn
tags question: http://stackoverflow.com/q/46866461
tags question: http://stackoverflow.com/q/46801899

http://stackoverflow.com/comment/80711309
comment on: http://stackoverflow.com/q/46882028
has text: Welcome to Stackoverflow - please read this to learn how to ask questions: https://stackoverflow.com/help/how-to-ask
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80503841
type: Comment
comment on: http://stackoverflow.com/a/46778593
score: 0
type: AnswerComment
has text: Great thanks @coldspeed - I ended up having to group by `[site,country_code,kind,ID]`, but this is exactly what I was looking for!

http://stackoverflow.com/q/46877670
has title: How to hold a for loop waiting for a process to end?
has answer: http://stackoverflow.com/a/46877734
tagged with: python
has comment: http://stackoverflow.com/comment/80702430
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46879750
score: -1
type: Question
has comment: http://stackoverflow.com/comment/80702416
answer count: 2
possible better answer: http://stackoverflow.com/a/46877734
has answer: http://stackoverflow.com/a/46879750
has comment: http://stackoverflow.com/comment/80718130
downvote count: 1
favorite count: 0
has body: I wrote a short Python 3 script to run a batch file (Ctemp.cmd) multiple times. The script is this: for i in range (START,STOP+1,STEP): os.startfile('Ctemp.cmd') The above code runs the file at (almost) the same time. However, I would like it to wait untill the batch file has completed running and then run it again.
upvote count: 0

http://stackoverflow.com/q/46846752
has answer: http://stackoverflow.com/a/46854730
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80642063
favorite count: 0
has comment: http://stackoverflow.com/comment/80715015
tagged with: distribution
tagged with: python-3.x
has title: Confusion over `a` and `b` attributes from scipy.stats.uniform
type: Question
upvote count: 2
has body: Consider the following code: import scipy print(scipy.__version__) # gives 0.19.1 # Scipy.stats.uniform unif = scipy.stats.uniform(1, 2) print(unif.a, unif.b, unif.args) # gives a=0, b=1, args=(1,2) It seems, regardless of the value I provide for loc and scale, the uniform-function returns a=0,b=1. Compare that to e.g. randint: # Scipy.stats.randint randi = scipy.stats.randint(1, 10) print(randi.a, randi.b, randi.args) # gives a=1, b=9, args=(1,10) ...which returns what I would expect. So my question becomes: is this a bug in scipy, or have I misunderstood something? The unif.args value is set correctly though. Cheers!
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/46854730
has comment: http://stackoverflow.com/comment/80654564
tagged with: scipy
has comment: http://stackoverflow.com/comment/80641145
score: 2
possible better answer: http://stackoverflow.com/a/46855308
downvote count: 0
has answer: http://stackoverflow.com/a/46855308
has comment: http://stackoverflow.com/comment/80641787
has comment: http://stackoverflow.com/comment/80641480

http://stackoverflow.com/q/46868422
has comment: http://stackoverflow.com/comment/80684421
has body: Note:The contest is over.I just want to know other way to solve this n = int(input()) if n == 0: print('1') else: print(1&lt;&lt;(str(bin(n)).count('0') - 1)) Chef has studied 2- bit Binary Adder in his Digital Logic Design class. He is amazed by the XOR operator and he believes that a + b = a xor b, where a and b are whole numbers and xor is Bitwise XOR operator. Chef's teacher's favorite number is n. Chef's teacher is in angry mood and he gives Chef a whole number x (x &lt;= n) and asks Chef to compute n + x to test his Binary Addition understanding. Chef answers n xor x. Input A single integer n. sample input:0 sample output:1 sample input:5 sample output:2
has comment: http://stackoverflow.com/comment/80684107
downvote count: 0
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/80684370
favorite count: 0
tagged with: xor
has comment: http://stackoverflow.com/comment/80684338
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80684250
has comment: http://stackoverflow.com/comment/80684480
has title: For how many values of x will n + x = n XOR x when n and x are whole numbers and n>=x?
tagged with: python
has answer: http://stackoverflow.com/a/46868817
has comment: http://stackoverflow.com/comment/80684585
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80684145
tagged with: bit-manipulation
upvote count: 1
has comment: http://stackoverflow.com/comment/80684556
has comment: http://stackoverflow.com/comment/80687040
type: Question
accepted answer: http://stackoverflow.com/a/46868817
has comment: http://stackoverflow.com/comment/80684494

http://stackoverflow.com/comment/80732686
score: 0
type: AnswerComment
has text: If this answers your question can you please mark it as accepted for future users to review.
type: Comment
comment on: http://stackoverflow.com/a/46891924

http://stackoverflow.com/comment/80667756
type: Comment
has text: I don't know what you mean by "not interested in programming correctly". I would like to program correctly. The code runs for me. Sadly all I can get it to do is just open the image I posted. Aside from you not having my arduino and QTDesigner stuff, omitting that I would imagine it should work.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46859945

http://stackoverflow.com/comment/80548639
comment on: http://stackoverflow.com/a/46786320
score: 0
type: AnswerComment
type: Comment
has text: I am asking this because I have to keep the model 'net1' unchanged and create other models 'net2' repeatedly and compare them..

http://stackoverflow.com/comment/80605714
type: Comment
comment on: http://stackoverflow.com/a/46829197
has text: Thanks so much for the help, greatly apriciated!!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80565286
score: 0
type: AnswerComment
type: Comment
has text: @Ev.Kounis Sorry took the liberty to change some more things. I had a similar answer coming in and thought I'd just change yours instead of posting something "similar". +1
comment on: http://stackoverflow.com/a/46808684

http://stackoverflow.com/a/46816680
has body: Because multiprocessing uses pickle to serialize data to/from separate processes, this is essentially a duplicate of this question. Adapting the accepted solution from that question, your example becomes: from multiprocessing import Pool import numpy as np class MyArray(np.ndarray): def __new__(cls, input_array, info=None): obj = np.asarray(input_array).view(cls) obj.info = info return obj def __array_finalize__(self, obj): if obj is None: return self.info = getattr(obj, 'info', None) def __reduce__(self): pickled_state = super(MyArray, self).__reduce__() new_state = pickled_state[2] + (self.info,) return (pickled_state[0], pickled_state[1], new_state) def __setstate__(self, state): self.info = state[-1] super(MyArray, self).__setstate__(state[0:-1]) def sum_worker(x): return sum(x) , x.info if __name__ == '__main__': arr_list = [MyArray(np.random.rand(3), info=f'foo_{i}') for i in range(10)] with Pool() as p: p.map(sum_worker, arr_list) Note, the second answer suggests you might be able to use pathos.multiprocessing with your unadapted original code since pathos uses dill instead of pickle. This did not work when I tested it however.
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/46813375
accepted answer of: http://stackoverflow.com/q/46813375
type: AcceptedAnswer
score: 4

http://stackoverflow.com/a/46819504
type: Answer
answers question: http://stackoverflow.com/q/46819239
score: 0
has body: I would recommend using a regular expression for this. Depending on how structured (or not) your input is you might have to spend some effort on finding an expression that correctly handles all cases. My for all cases that have been mentioned so far would be: r"(?P&lt;initials&gt;\w+)\s*-?\s*(?P&lt;month&gt;\d{1,2}|JAN\w*)\s*-?\s*(?P&lt;year&gt;\d{2,4})" You can study the effect with any number of online regex evaluators. I use this one.

http://stackoverflow.com/comment/80592120
comment on: http://stackoverflow.com/q/46821927
type: QuestionComment
type: Comment
score: 0
has text: `OrderedDict` maintains the order of items added to the dict, so if they're not coming _out_ in sorted order, that means they weren't _added_ in sorted order.

snakemake
tags question: http://stackoverflow.com/q/46856698
tags question: http://stackoverflow.com/q/46855983
tag name: snakemake
type: Tag

http://stackoverflow.com/comment/80503237
type: QuestionComment
comment on: http://stackoverflow.com/q/46775912
score: 0
has text: Have you tried to run simple print statements in each thread to see what the last thread was that ran when the error happened?
type: Comment

http://stackoverflow.com/comment/80659777
has text: i want the item to be picked by acknowledging all the lists
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46856087

webargs
tags question: http://stackoverflow.com/q/46858123
type: Tag
tag name: webargs

http://stackoverflow.com/a/46829248
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46828689
type: Answer
score: 4
has body: You can employ axhline as follows: import matplotlib.pyplot as plt import pandas as pd import numpy as np # dummy data df = pd.DataFrame(np.random.random(size=(20, 1)), columns=["rain"]) # your plot setup fig,ax= plt.subplots() df.plot(kind="bar", ax=ax, color='g',figsize=(15,7)) plt.minorticks_on() ax.tick_params(axis='x',which='minor',bottom='off') ax.set_xlabel("Year") ax.set_ylabel("Precipitation") ax.set_title(("Precipitation"), fontsize=20) # use axhline mean = df["rain"].mean() ax.axhline(mean)
downvote count: 1
upvote count: 5
accepted answer of: http://stackoverflow.com/q/46828689

http://stackoverflow.com/comment/85943653
has text: It turns out that the python 3.X branch libraries were installed to a non-standard location, and that that was causing the issues, lol. Thanks, Graham! :D
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46761387
type: Comment

http://stackoverflow.com/q/46750687
tagged with: chess
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46750752
has body: I just started learning about Python classes today and I had a quick question. I'm pretty amazed how much more succinct it has made my code, but I'm trying to figure out if the following is possible for a chess problem I'm working on. (1) Can I append a list somehow from within a class method? I'm trying to figure out if there's a way to accumulate the pieces in a list each time capture is called. (2) How can I call a method from within the class to be used in another method? I would like to be able to check if a move is valid before even proceeding if the piece should try to capture another or move. class Piece(Board): def __init__(self, piece, r, c): self.piece = piece self.r = r self.c = c This is the function I would like to incorporate into the functions below to avoid the redundancy (Question 2) def valid_move(self,r,c,r_offset,c_offset): #r, c are integers for the coordinates on the board #r_offset,c_offset are the cells the piece might move to self.tgt_r, self.tgt_c = r+r_offset, c+c_offset if self.tgt_r &lt;= 7 or self.tgt_c &gt;= 0: return True return False These functions are the same for now. I'm trying to see how I can use the capture function to accumulate a list of pieces once they're taken. (Question 1) def capture(self,r,c, r_offset, c_offset): piece = self.piece self.tgt_r, self.tgt_c = r+r_offset, c+c_offset if self.tgt_r &gt; 7 or self.tgt_c &lt; 0: return None else: nb = Board(curr).copy_board() #this board is just 8x8 np.array nb[self.tgt_r,self.tgt_c], nb[r,c] = piece,'-' return nb def move(self,r,c, r_offset, c_offset): piece = self.piece self.tgt_r, self.tgt_c = r+r_offset, c+c_offset if self.tgt_r &gt; 7 or self.tgt_c &lt; 0: return None else: nb = Board(curr).copy_board() nb[self.tgt_r,self.tgt_c], nb[r,c] = piece,'-' return nb Thanks as always.
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
tagged with: class
tagged with: python
has answer: http://stackoverflow.com/a/46750752
has title: Python Classes: Appending a list & Incorporating a Method
downvote count: 1

http://stackoverflow.com/q/46859413
has comment: http://stackoverflow.com/comment/80666496
answer count: 1
has title: How can I search for files based on elements of a list?
score: 0
tagged with: glob
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/46859433
accepted answer: http://stackoverflow.com/a/46859433
has body: I have a list tile with elements like these G11451-11500 G11501-11550 G11551-11600 G11601-11650 Which I want to use to search a directory and store the files in a list. For example, this : glob.glob('*G11451-11500*.sh')gives me the intended output with a list of filenames. But I want to do this in a loop. And I am unable to proceed from here: for ix in tile: e = glob.glob('*format(ix)*')
type: Question

http://stackoverflow.com/q/46864049
tagged with: python
has comment: http://stackoverflow.com/comment/80675484
linked to: http://stackoverflow.com/q/3061
has comment: http://stackoverflow.com/comment/80675489
score: 0
possible better answer: http://stackoverflow.com/a/46864088
has comment: http://stackoverflow.com/comment/80685567
has title: Dynamically import class by name from module imported as:
accepted answer: http://stackoverflow.com/a/46864234
has answer: http://stackoverflow.com/a/46864088
has comment: http://stackoverflow.com/comment/80675533
answer count: 2
has comment: http://stackoverflow.com/comment/80685482
has comment: http://stackoverflow.com/comment/80675576
has body: I have searched high and low and can't find a proper solution. I need to dynamically create objects and store them in dictionaries using a for loop from a class that is in a different file. To avoid name space pollution I like to import my modules like so: from my_folder import my_file as mf the loop looks like this: self.my_dict = {} # create empty dictionary for F in ('One', 'Two', 'Three', ...): object = F(var1, var2) self.my_dict[F] = object on the line object = F(var1, var2) I need the F be referring to mf.One, mf.Two and so on. How do I append the value F to mf so it reads it as mf.value-of-F instead of reading it as mf.F? I know I must be missing something very obvious, just not obvious to me right now. Thanks
has comment: http://stackoverflow.com/comment/80689329
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80685539
has comment: http://stackoverflow.com/comment/80675582
has answer: http://stackoverflow.com/a/46864234
type: Question

http://stackoverflow.com/q/46758389
has comment: http://stackoverflow.com/comment/80462463
has comment: http://stackoverflow.com/comment/80462024
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46758797
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80462216
has body: I'm using SQLite and Python but i want to insert random string that is relevant for example if i wanted a certain song genre, i want song titles that arent random letters. I'd appreciate any help... def genre(): genre=('''What genre do you want 1. 2. 3. ''') choice=input(genre) '''GENERATE RANDOM SONGS BASED ON GENRE INTO PLAYLIST DATABASE''' def length(): length=input("How long do you want the playlist to last") '''INSERT DATA INTO PLAYLIST WHICH ADDS TO USER LENGTH'''
downvote count: 1
type: Question
has title: How do i insert random string into a table that is relevant to my project of a music library?
has comment: http://stackoverflow.com/comment/80462629
accepted answer: http://stackoverflow.com/a/46758797
score: 0
tagged with: sqlite
answer count: 1
favorite count: 0

http://stackoverflow.com/q/46816545
has comment: http://stackoverflow.com/comment/80627135
type: Question
linked to: http://stackoverflow.com/q/45130837
has comment: http://stackoverflow.com/comment/80581380
has title: Submit command line // submit unfilled raw_input
upvote count: 1
has comment: http://stackoverflow.com/comment/80681646
downvote count: 0
has body: I'm looking to write a program that asks for user_input on a cyclical basis, but does not halt further procedures while waiting for the user to give input. Is there a command that acts as a press of the RETURN key? Does this have to do with writing to stdin? An alternative might be to see if there is no user_input that currently exists. Imagine operating the code below, where the program is constantly running, even if the user provides no input, import os import time import termios import sys x = 0 while x &lt; 60: time.sleep(0.5) x += 1 print x user_input = raw_input(" ") if user_input == "exit": os._exit(1)
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/80580408
has comment: http://stackoverflow.com/comment/80580419
linked to: http://stackoverflow.com/q/2846653

http://stackoverflow.com/a/46960402
upvote count: 4
has body: Python doesn't really have private variables, there are two conventions: Variables prefixed with underscore (_var) are used to let you and other people know that it's intended to be private Variables prefixed with two undersores (__var) are also mangled by python interpreter and also are prefixed by class name, but they are still accessible like self._Superclass__var in your example See also the documentation. There is one more issue in your code - you are using class variables, not instance variables (this is what usually called static class variables in other languages). Check this example: class Superclass: var = 1 def getVar(self): print(self.var) my_object = Superclass() my_object2 = Superclass() my_object.getVar() # outputs 1 my_object2.getVar() # outputs 1 Superclass.var = 321 # this value is share across all instances my_object.getVar() # outputs 321 my_object2.getVar() # outputs 321 And when you are doing self.var = xxx assignments in your methods, you just hide the class-level variable and add the new instance-level variable with same name. See also the documentation: https://docs.python.org/3.6/tutorial/classes.html#class-and-instance-variables
downvote count: 0
answers question: http://stackoverflow.com/q/46853442
accepted answer of: http://stackoverflow.com/q/46853442
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80875049
type: Answer
score: 4

http://stackoverflow.com/q/46830620
linked to: http://stackoverflow.com/q/19152578
has answer: http://stackoverflow.com/a/49499661
type: Question
answer count: 1
downvote count: 0
has title: Paramiko Python: No handlers for paramiko.transport - Getting TypeError
tagged with: paramiko
favorite count: 0
has body: Alright, so i am trying to implement paramiko in my python script. The aim is to connect to another PC in the same LAN and execute the command through python. My python version: Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 I have a basic code here: import paramiko client = paramiko.SSHClient() host = '192.168.xx.xx' username = 'username' password = 'password' client.connect(host, username=username, password=password) stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print('... ' + line.strip('\n')) client.close() But then I get the following error: No handlers could be found for logger "paramiko.transport" Traceback (most recent call last): File "testbed.py", line 8, in &lt;module&gt; client.connect(host, username=username, password=password) File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 385, in connect t.start_client(timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/paramiko/transport.py", line 543, in start_client raise e TypeError: 'type' object is not iterable
tagged with: ssh
has comment: http://stackoverflow.com/comment/80610739
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80608871
tagged with: python
score: 2

http://stackoverflow.com/a/46873991
has comment: http://stackoverflow.com/comment/80695088
score: 3
has body: Use instead count function nunique and for er_ai get mean of all values by condition: cols = {'r2':'avg_r2', 'contact_id':'tickets', 'acknowledge_issues':'er_ai'} test = (data_L1.groupby(['X','Y'], as_index=False) .agg({'r2': 'mean', 'contact_id' : 'nunique', 'acknowledge_issues': lambda x: (x&gt;0).mean()}) .rename(columns=cols)) print (test) X Y tickets er_ai avg_r2 0 a c 2 0.500000 90 1 b d 3 0.666667 80
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80695134
type: Answer
answers question: http://stackoverflow.com/q/46873846
accepted answer of: http://stackoverflow.com/q/46873846
upvote count: 3

http://stackoverflow.com/comment/80517239
type: Comment
comment on: http://stackoverflow.com/a/46785346
has text: Wow! The design decision of using tensors as keys in the `feed_dict` leads to `__eq__` *not* being defined in the same way as for `numpy` for `tf.Tensors`!
type: AnswerComment
score: 0

http://stackoverflow.com/q/46820317
tagged with: python
has comment: http://stackoverflow.com/comment/80588283
answer count: 0
type: UnansweredQuestion
tagged with: regression
upvote count: 1
tagged with: linear-regression
has body: I've been working with U.S. NOAA's (National Oceanic and Atmospheric Administration) Global Mean Sea Level dataset. There are 4 satellites provide information, so, there are 4 columns and year column. Those satellites provided informations within a specific time interval. For example; satellite Posedion worked within 1992-2006, Jason-1 worked within 2003-2014 etc. Of course, there will be lots of NaN values where Jason-1 doesn't serve but Poseidon does. What I want is to plot linear line to calculate sea level rise, that's all. I want those four columns to be fit with year column. Couldn't cracked yet.. Here is my code; import numpy as np import pandas as pd from scipy import stats from sklearn import linear_model from matplotlib import pyplot as plt import pylab import matplotlib.patches as mpatches import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression Atlantic = pd.read_csv('C:\\Atlantic_Free2.csv', error_bad_lines=False) Atlantic = Atlantic[~np.isnan(Atlantic)] Poseidon = Atlantic['Poseidon'] Jason1 = Atlantic['Jason1'] Jason2 = Atlantic['Jason2'] Jason3 = Atlantic['Jason3'] plt.figure(figsize=(20,10)) colors = ["blue", "red", "green", "purple"] texts = ["Poseidon", "Jason1", "Jason2", "Jason3"] patches = [ plt.plot([],[], marker="o", ms=10, ls="", mec=None, color=colors[i], label="{:s}".format(texts[i]) )[0] for i in range(len(texts)) ] plt.legend(handles=patches, loc='upper left', ncol=1, facecolor="grey", numpoints=1 ) plt.plot(Atlantic, Poseidon , 'ro', color='blue') plt.plot(Atlantic, Jason1 , 'ro', color='red') plt.plot(Atlantic, Jason2 , 'ro', color='green') plt.plot(Atlantic, Jason3 , 'ro', color='purple') plt.ylabel('Change in mean sea level [mm]', fontsize=20) plt.xlabel('Years', fontsize=20) plt.title('Atlantic Ocean - Mean Sea Level', fontsize=20) plt.axis([1992, 2018, -25, 80]) plt.grid(True) plt.plot() plt.show() Output of the code above, added to below.
type: Question
has title: Linear Regression over time series with multiple outputs
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80588814

http://stackoverflow.com/a/46760481
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46759726
has comment: http://stackoverflow.com/comment/80466764
has comment: http://stackoverflow.com/comment/80476967
has body: hacking a game I see. Provided you are aware that what you are doing may diminish the validity of other's playtime as well as potentially committing a crime, I shall provide a solution: You would need to get a piece of "sniffing" software which allows modifications. The modifications are likely to be the addition of "Querystring" and "JSON" parsers to read the data traffic. At this point, you can begin learning how their particular system works, slowly replacing traffic with modified versions for your nefarious purposes. "TCP Sniffing" includes creating a "RAW TCP SOCKET" in whatever language and then repeatedly "READ'ing / RECV'ing" from that socket. The socket MUST be bound TO THE SPECIFIC NETWORK INTERFACE CARD (NIC). Hint: "LOCALHOST" and "127.0.0.1" are NOT the addresses of any NIC. You would then parse the data as a HTTP req/res stream, ensuring that you can read the contents of the frame correctly. You would then be looking to either modify the contents of the POST body or the GET querystring. Either, depending on how the game designers designed their network system.

http://stackoverflow.com/q/46901583
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/46901641
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/46901667
has title: How to sort a list of integers numerically while retaining value order
score: 1
linked to: http://stackoverflow.com/q/6422700
has answer: http://stackoverflow.com/a/46901637
type: Question
has comment: http://stackoverflow.com/comment/80750035
has comment: http://stackoverflow.com/comment/80750106
has body: Say I have a list [102, 97, 116, 101], and I want to rank their values numerically while retaining the value's position in the list, as in [3, 1, 4, 2]. How would I go about this?
duplicate of: http://stackoverflow.com/q/6422700
downvote count: 0

http://stackoverflow.com/a/70242211
has comment: http://stackoverflow.com/comment/134863410
has comment: http://stackoverflow.com/comment/133775015
answers question: http://stackoverflow.com/q/46775346
type: Answer
has comment: http://stackoverflow.com/comment/134864283
downvote count: 0
score: 19
has comment: http://stackoverflow.com/comment/134862973
has body: TLDR The square bracket contains the 'extra' option's information defined in setup.py that pip will use to install additional dependencies. pip install "splinter[django]" To be specific, the above line will install first the 'splinter' package, then install the extra dependencies the 'splinter' project requires with the 'django' option specified in a setup.py of 'splinter' project. Explanation pip install "splinter[django]" pip install "splinter" "Django>=2.0.6" "lxml>=4.2.4" "cssselect" As of splinter==0.16.0, with python==3.9.2, the above two commands are equivalent. Both pip install will result in the following packages given a clean virtual enviroment. The reason why the two pip install commands achieve same is because this is literally what has been run in the background based on the setup.py of the splinter package The '[django]' is the 'extra' option for the 'splinter' package. Pip will look into the setup.py of splinter package, and find what needs to be installed with the '[django]' option specified. In this case, it is these 3 packages: ["Django>=2.0.6", "lxml>=4.2.4", "cssselect"]
upvote count: 19

http://stackoverflow.com/q/46904444
answer count: 1
has title: How to connect to another different database in PostgreSQL with ORM in Odoo?
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: I have a database in PostgreSQL, and I want to use it through Odoo ORM and then implement RPC stuff. I don't know how to connect to another database (in PostgreSQL). I've googled for this and I have not found clairvoyant solutions or information. Can someone tell me about this? what steps should I follow? Thanks in advance
tagged with: python
has answer: http://stackoverflow.com/a/51503128
score: 2
tagged with: odoo
tagged with: orm
type: Question
downvote count: 0
tagged with: postgresql
tagged with: python-2.7

http://stackoverflow.com/comment/80676997
comment on: http://stackoverflow.com/q/46864740
score: 0
type: Comment
type: QuestionComment
has text: @ayhan yes, something like that, except I realised `:` might result in an expensive copy :-)

http://stackoverflow.com/comment/80538313
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46795852
type: Comment
has text: Oh. oops, that makes sense.

http://stackoverflow.com/comment/80622630
type: Comment
type: QuestionComment
has text: Please vote to close this because it would destroy my rep if it stays. I had assumed that `__tuple__()` existed, and to be honest never thought it wouldn't. After all, `__str__()` exists.
comment on: http://stackoverflow.com/q/46837449
score: 0

http://stackoverflow.com/a/52580581
downvote count: 0
upvote count: 2
has body: Well, I should probably post what I did.. It works for my purpose: # Return the network of an IP and mask def network(ip,mask): network = '' iOctets = ip.split('.') mOctets = mask.split('.') network = str( int( iOctets[0] ) &amp; int(mOctets[0] ) ) + '.' network += str( int( iOctets[1] ) &amp; int(mOctets[1] ) ) + '.' network += str( int( iOctets[2] ) &amp; int(mOctets[2] ) ) + '.' network += str( int( iOctets[3] ) &amp; int(mOctets[3] ) ) return network
answers question: http://stackoverflow.com/q/46881328
type: Answer
score: 2

http://stackoverflow.com/q/46812351
has title: Multiprocessing with python kafka consumers
score: 0
tagged with: scale
has answer: http://stackoverflow.com/a/46812799
type: UnansweredQuestion
tagged with: python
tagged with: apache-kafka
has body: I am trying to make an application in python that has 1 topic (demo-topic) and 1 partition. In this topic messages are pushed randomly I have 1 consumer (consumer1) (demo-group) that uses this messages to makes some background calculations (that take some time). Having this application on amazon i want to be able to scale it (when computation takes to long) in the way that the newly created machine will have another consumer (consumer 2) from the same group (demo-group) reading in the same topic (demo-topic) but in the way that they start splitting the load (consumer 1 takes some load and consumer 2 takes the rest but they never get the same messages) After the surge of data comes to an halt, second machine is decommissioned and consumer 1 takes all the load again. Is this even possible to do (without adding before hand more partitions). Is there a workaround?? Thank you
has answer: http://stackoverflow.com/a/46812746
tagged with: multiprocessing
type: Question
answer count: 2
tagged with: amazon-web-services

http://stackoverflow.com/q/46867709
has comment: http://stackoverflow.com/comment/80682874
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/46867849
answer count: 3
score: 3
has body: I have two string arrays each with three columns.I want to compare first two columns of both 2-d arrays(having 3 cols and 4000 rows). if they match then i need those matching values.But my code is not working.Here is a sample. array1=["1stcolumn...", "2ndColumn...", "3rdColumn..."] array2=[1stcolumn 2ndColumn 3rdColumn] if (array1[0]==array2[0] and array1[1]==array2[1]): array3.append('matches: {!r}'.format(array1)) print(array3)
possible better answer: http://stackoverflow.com/a/46867856
favorite count: 0
has answer: http://stackoverflow.com/a/46867856
has comment: http://stackoverflow.com/comment/80683013
tagged with: python
has comment: http://stackoverflow.com/comment/80683369
has title: how to compare 2 columns of a 2d array at a time with columns of another array in python
tagged with: indexing
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/46867849
upvote count: 3
linked to: http://stackoverflow.com/q/2485466
has answer: http://stackoverflow.com/a/46874290
type: Question
has comment: http://stackoverflow.com/comment/80683424

http://stackoverflow.com/q/46864986
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46865027
score: 1
has body: Apologies in advance that I couldn't create code to generate the sample data. Here is my data frame, Columns B,C,D,E have appointment dates. I am trying to count the number of dates that exist per row and append that number to Column G without disturbing Columns A and F. Do I need a function? True/False for values then count? Is there a simple way? A B C D E F G 0 1 20171021 20171021 20171021 20171021 id_123 1 2 NaN 20171021 20171021 20171021 id_234 2 3 NaN NaN 20171021 20171021 id_345 3 4 NaN NaN NaN 20171021 id_456 Desired Output A B C D E F G 0 1 20171021 20171021 20171021 20171021 id_123 4 1 2 NaN 20171021 20171021 20171021 id_234 3 2 3 NaN NaN 20171021 20171021 id_345 2 3 4 NaN NaN NaN 20171021 id_456 1
has answer: http://stackoverflow.com/a/46865027
upvote count: 1
has answer: http://stackoverflow.com/a/46865006
type: Question
has title: Give count for column values python pandas
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46865006
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/q/46819866
has comment: http://stackoverflow.com/comment/80594023
has comment: http://stackoverflow.com/comment/80594878
has answer: http://stackoverflow.com/a/46820299
score: 0
answer count: 2
has title: Django displaying data from database in template
has comment: http://stackoverflow.com/comment/80597147
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm having some trouble displaying data from my database on the template in django model: class CityInfo (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) landmark_type = models.CharField(blank=True, max_length=30) business = 'Business' student = 'Student' tourist = 'Tourist' def __str__(self): return self.name relevant view: def itemget(request): data=CityInfo.objects.all() return render(request,'CityApp/infopage.html', {'data': data}) relevant url: url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'), infopage.html: &lt;ul&gt; {% for item in data %} &lt;li&gt; &lt;h1&gt;{{ item.name }}&lt;/h1&gt; &lt;/li&gt; {% endfor %} &lt;ul&gt; The above html results in a blank list and I have no idea why.
has comment: http://stackoverflow.com/comment/80593376
has answer: http://stackoverflow.com/a/46820096
type: Question

http://stackoverflow.com/q/46857433
has title: How to print 1 in every thousand frames using opencv and python?
type: Question
has comment: http://stackoverflow.com/comment/80662671
has comment: http://stackoverflow.com/comment/80662706
has comment: http://stackoverflow.com/comment/80744269
has comment: http://stackoverflow.com/comment/80705646
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51599620
tagged with: python
tagged with: opencv
tagged with: video
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51599620
has body: I am trying to save one frame in every thousand frames of a video. Below is the code I am currently using: import cv2 import numpy as np import os # Playing video from file: cap = cv2.VideoCapture('D:/01 Projects/AMAZON CATALYST PROJECT/Surgery1.mpg') try: if not os.path.exists('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1'): os.makedirs('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1') except OSError: print ('Error: Creating directory of data_surg1') currentFrame = 0 while(True): # Capture frame-by-frame if currentFrame &gt; 0: cap.set(cv2.CAP_PROP_POS_MSEC,currentFrame) ret, frame = cap.read() # Saves image of the current frame in jpg file name = 'D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1/frame' + str(currentFrame/1000) + '.jpg' print ('Creating...' + name) cv2.imwrite(name, frame) # To stop duplicate images currentFrame += 1000 # When everything done, release the capture cap.release() cv2.destroyAllWindows() However, I am not sure if this is saving it correctly. When I look at the frames in the file explorer, the numbers are initially very high and then reduce to form a sequential frame number compared to the previous image. I am using Python 2.7 and OpenCV3.3.

http://stackoverflow.com/a/46809121
type: Answer
score: 2
upvote count: 2
has body: As @wiktor said, remove the « $ »sign which means that your the string that you’re looking for has to FINISH with a _[0-9], not just contain.
downvote count: 0
answers question: http://stackoverflow.com/q/46808219

http://stackoverflow.com/comment/80580736
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46816619
has text: @user2357112 how do I turn it into a function? I tried doing def fun(W,cov_matrix): fun = float(0.5*np.dot(np.dot(W, cov_matrix), W)) # variance of the portfolio return fun

http://stackoverflow.com/comment/80573286
score: 0
comment on: http://stackoverflow.com/q/46813015
type: Comment
type: QuestionComment
has text: I've got 1152 songs I need to add to the playlist, wouldn't scraping be kinda tedious or so?

http://stackoverflow.com/a/46760016
type: Answer
has comment: http://stackoverflow.com/comment/80465738
downvote count: 0
score: 2
has body: By using andrew_reece's example data :-) pd.concat pd.concat([df1.set_index(["first", "last_huge"]),df2.set_index(["first_small", "last_small"])['email_small']],axis=1).reset_index().dropna() Out[23]: first last_huge email_small 0 alice foo alice@xyz.com 1 bob bar bob@abc.com 2 carol baz carol@jkl.com By using your data pd.concat([df1.set_index(["first", "last_huge"]),df2.set_index(["first_small", "last_small"])['email_small']],axis=1).reset_index() Out[97]: first last_huge age_huge city_huge state_huge street_huge zip_huge \ 0 alice foo 23 Egviniw MA Jaifo Road 89899 1 bob bar 30 Manbaali LA Wetib Ridge 78788 2 carol baz 36 Ismazdan CA Ucagi View 58999 email_small 0 alice@xyz.com 1 bob@abc.com 2 carol@jkl.com Updated by using map df1['email_small']=(df1['first']+df1['last_huge']).map(df2.set_index(df2['first_small']+df2['last_small'])['email_small']) df1 Out[115]: age_huge city_huge first last_huge state_huge street_huge zip_huge \ 0 23 Egviniw alice foo MA Jaifo Road 89899 1 30 Manbaali bob bar LA Wetib Ridge 78788 2 36 Ismazdan carol baz CA Ucagi View 58999 email_small 0 alice@xyz.com 1 bob@abc.com 2 carol@jkl.com
has comment: http://stackoverflow.com/comment/80465462
has comment: http://stackoverflow.com/comment/80465969
upvote count: 2
has comment: http://stackoverflow.com/comment/80466039
has comment: http://stackoverflow.com/comment/80465693
has comment: http://stackoverflow.com/comment/80465934
has comment: http://stackoverflow.com/comment/80465438
has comment: http://stackoverflow.com/comment/80466162
answers question: http://stackoverflow.com/q/46759878

http://stackoverflow.com/q/46826705
favorite count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46826843
tagged with: ndimage
upvote count: 1
tagged with: python
has body: How to resize N-d numpy image? I don't just want to subsample it, but to interpolate / average the pixels. For example, if I start with array([[[3, 1, 3, 1], [3, 1, 3, 1], [3, 1, 3, 1], [3, 1, 3, 1]], [[3, 1, 3, 1], [3, 1, 3, 1], [3, 1, 3, 1], [3, 1, 3, 1]]], dtype=uint8) and shrink it by a factor of 2 in all dimensions, I want the output to be array([[[2, 2], [2, 2]]], dtype=uint8) Attempted solutions: A. SciPy ndimage: &gt;&gt;&gt; scipy.ndimage.interpolation.zoom(x, .5, mode='nearest') array([[[3, 1], [3, 1]]], dtype=uint8) (The optional order parameter makes no difference) B. Looping over 2**3 possible offsets: ugly, slow, works only for integer zoom factors, and needs extra steps to avoid overflows. C. OpenCV and PIL work only with 2D images.
type: AnsweredQuestion
score: 1
tagged with: scipy
type: Question
tagged with: numpy
downvote count: 0
has answer: http://stackoverflow.com/a/46826843
has title: How to resize N-d numpy image?

http://stackoverflow.com/a/77427029
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46787119
has body: You should use Client instance like this : (not even AsyncClient nor AsyncSimpleClient ) sio = socketio.Client(handle_sigint=True,reconnection=True) sio.connect('https://example.com:3001',{})

function
tags question: http://stackoverflow.com/q/46795627
tags question: http://stackoverflow.com/q/46819260
tags question: http://stackoverflow.com/q/46765859
tags question: http://stackoverflow.com/q/46891555
tags question: http://stackoverflow.com/q/46844569
tag name: function
tags question: http://stackoverflow.com/q/46837646
tags question: http://stackoverflow.com/q/46831705
tags question: http://stackoverflow.com/q/46863394
tags question: http://stackoverflow.com/q/46776769
tags question: http://stackoverflow.com/q/46809615
tags question: http://stackoverflow.com/q/46793587
tags question: http://stackoverflow.com/q/46833451
tags question: http://stackoverflow.com/q/46866295
tags question: http://stackoverflow.com/q/46801059
tags question: http://stackoverflow.com/q/46815591
tags question: http://stackoverflow.com/q/46759492
tags question: http://stackoverflow.com/q/46782017
tags question: http://stackoverflow.com/q/46761654
tags question: http://stackoverflow.com/q/46863124
tags question: http://stackoverflow.com/q/46836853
tags question: http://stackoverflow.com/q/46776462
tags question: http://stackoverflow.com/q/46873773
tags question: http://stackoverflow.com/q/46838446
tags question: http://stackoverflow.com/q/46876101
tags question: http://stackoverflow.com/q/46807716
tags question: http://stackoverflow.com/q/46871522
tags question: http://stackoverflow.com/q/46751996
tags question: http://stackoverflow.com/q/46768627
tags question: http://stackoverflow.com/q/46759999
tags question: http://stackoverflow.com/q/46760775
tags question: http://stackoverflow.com/q/46866239
tags question: http://stackoverflow.com/q/46837384
type: Tag
tags question: http://stackoverflow.com/q/46793112
tags question: http://stackoverflow.com/q/46881302
tags question: http://stackoverflow.com/q/46897852
tags question: http://stackoverflow.com/q/46867361
tags question: http://stackoverflow.com/q/46774890
tags question: http://stackoverflow.com/q/46817907
tags question: http://stackoverflow.com/q/46751718
tags question: http://stackoverflow.com/q/46851780
tags question: http://stackoverflow.com/q/46877409
tags question: http://stackoverflow.com/q/46775835
tags question: http://stackoverflow.com/q/46811558
tags question: http://stackoverflow.com/q/46863866
tags question: http://stackoverflow.com/q/46865406
tags question: http://stackoverflow.com/q/46858493
tags question: http://stackoverflow.com/q/46827674
tags question: http://stackoverflow.com/q/46897123
tags question: http://stackoverflow.com/q/46852132
tags question: http://stackoverflow.com/q/46867841
tags question: http://stackoverflow.com/q/46875395
tags question: http://stackoverflow.com/q/46875286
tags question: http://stackoverflow.com/q/46865459
tags question: http://stackoverflow.com/q/46787051
tags question: http://stackoverflow.com/q/46799978
tags question: http://stackoverflow.com/q/46876954
tags question: http://stackoverflow.com/q/46843310
tags question: http://stackoverflow.com/q/46898217
tags question: http://stackoverflow.com/q/46748976
tags question: http://stackoverflow.com/q/46858184
tags question: http://stackoverflow.com/q/46897417
tags question: http://stackoverflow.com/q/46896648
tags question: http://stackoverflow.com/q/46877099
tags question: http://stackoverflow.com/q/46848877

http://stackoverflow.com/comment/80646437
comment on: http://stackoverflow.com/a/46830352
score: 0
type: AnswerComment
type: Comment
has text: Please accept this answer or upvote it if this answer helped.

http://stackoverflow.com/a/65924551
upvote count: 3
has comment: http://stackoverflow.com/comment/137703298
has body: A more granual way could be using a custom authentication backend. By using this approach one will be able to use UserModel.objects.get without the drawback of making unnecessary joins(.select_related()) or DB lookups(.prefetch_related()) while using this manager in other segments of code. # auth_backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend UserModel = get_user_model() class RelatedModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.select_related( ... # Do your magic here ).prefetch_related( ... # Do your magic here ) get( **{UserModel.USERNAME_FIELD: username} ) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel._default_manager.select_related( ... # Do your magic here ).prefetch_related( ... # Do your magic here ).get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None Now we need to add new backend into settings file, read more about custom auth backends here. # settings.py ... AUTHENTICATION_BACKENDS = ['myproject.auth_backends.RelatedModelBackend'] ...
answers question: http://stackoverflow.com/q/46854395
downvote count: 0
type: Answer
score: 3

algorithm
tags question: http://stackoverflow.com/q/46819292
tags question: http://stackoverflow.com/q/46855520
tags question: http://stackoverflow.com/q/46874594
tag name: algorithm
tags question: http://stackoverflow.com/q/46762063
tags question: http://stackoverflow.com/q/46796266
tags question: http://stackoverflow.com/q/46784426
tags question: http://stackoverflow.com/q/46879528
tags question: http://stackoverflow.com/q/46884428
tags question: http://stackoverflow.com/q/46760031
tags question: http://stackoverflow.com/q/46771858
tags question: http://stackoverflow.com/q/46779832
tags question: http://stackoverflow.com/q/46773511
tags question: http://stackoverflow.com/q/46825980
tags question: http://stackoverflow.com/q/46790855
tags question: http://stackoverflow.com/q/46902398
tags question: http://stackoverflow.com/q/46821320
tags question: http://stackoverflow.com/q/46864921
tags question: http://stackoverflow.com/q/46880842
tags question: http://stackoverflow.com/q/46786327
tags question: http://stackoverflow.com/q/46885888
type: Tag
tags question: http://stackoverflow.com/q/46757190
tags question: http://stackoverflow.com/q/46873390
tags question: http://stackoverflow.com/q/46791897
tags question: http://stackoverflow.com/q/46754729
tags question: http://stackoverflow.com/q/46837378
tags question: http://stackoverflow.com/q/46852090
tags question: http://stackoverflow.com/q/46901128
tags question: http://stackoverflow.com/q/46776982
tags question: http://stackoverflow.com/q/46859257
tags question: http://stackoverflow.com/q/46888182
tags question: http://stackoverflow.com/q/46902318
tags question: http://stackoverflow.com/q/46821037
tags question: http://stackoverflow.com/q/46781697
tags question: http://stackoverflow.com/q/46801202

http://stackoverflow.com/comment/80664114
comment on: http://stackoverflow.com/q/46857831
type: Comment
score: 1
has text: Blender includes an interpreter, python console, and scripting window. ( https://docs.blender.org/manual/en/dev/advanced/scripting/index.html ). I highly recommend you try using Blender's internals unless you have a specific use case otherwise.
type: QuestionComment

http://stackoverflow.com/comment/80777038
type: Comment
has text: Python 2 uses UTF-16LE (narrow build) or UTF-32LE (wide build). Python 3.3 does not use UTF-8 internally. It uses (IIRC) latin1, UTF-16LE, or UTF-32LE as needed to represent the worst case code point in the string.
comment on: http://stackoverflow.com/a/46902624
score: 0
type: AnswerComment

http://stackoverflow.com/q/46769063
answer count: 2
has title: python strip doesn't work in "for-in"
has answer: http://stackoverflow.com/a/46769090
has body: case1 for str in list1: str = str.strip() case2 for i in range(0, len(list1)): list1[i] = list1[i].strip() In case1, strip doesn't work. In case2, strip works. What's the difference between 1 and 2?
tagged with: python
has comment: http://stackoverflow.com/comment/80483351
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46769090
type: Question
possible better answer: http://stackoverflow.com/a/46769277
score: 0
has answer: http://stackoverflow.com/a/46769277

http://stackoverflow.com/q/46829055
has body: How can I return a specific value if the list is out of range? This is the code I have so far: def word(num): return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][num-1] word(1) will return 'Sunday', but how can I return a default value if num is not an integer between 1-7? Thus, word(10) would return something like "Error".
possible better answer: http://stackoverflow.com/a/46829121
downvote count: 1
type: Question
score: 5
has answer: http://stackoverflow.com/a/46829097
has answer: http://stackoverflow.com/a/46829220
has title: Return specific value when list is out of range in Python
tagged with: arraylist
accepted answer: http://stackoverflow.com/a/46829097
tagged with: default
favorite count: 0
tagged with: return
has answer: http://stackoverflow.com/a/46829205
has comment: http://stackoverflow.com/comment/80606431
answer count: 5
has answer: http://stackoverflow.com/a/46829649
tagged with: range
tagged with: python
has answer: http://stackoverflow.com/a/46829121
upvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/comment/80537884
score: 0
comment on: http://stackoverflow.com/q/46795552
has text: Please make your example self-contained. I don't know what result you expect and on top of that can't run it so I can't tell you what's wrong.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46837914
answer count: 1
has comment: http://stackoverflow.com/comment/80627877
favorite count: 0
tagged with: linux
has answer: http://stackoverflow.com/a/46852612
accepted answer: http://stackoverflow.com/a/46852612
tagged with: python
score: 2
has title: How to start ssh-agent permanently with python?
type: AnsweredQuestion
upvote count: 3
downvote count: 1
has body: I am looking for the equivalent of eval $(ssh-agent) for python, that will start ssh-agent and will stay running after the script finish to run. I didn't find anything useful with Google.
type: Question
tagged with: bsd
tagged with: ssh-agent
has comment: http://stackoverflow.com/comment/80623538
has comment: http://stackoverflow.com/comment/80623569

http://stackoverflow.com/q/46829568
has answer: http://stackoverflow.com/a/46832480
favorite count: 0
has comment: http://stackoverflow.com/comment/80607240
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to remove the outer (parent) layer of a JSON file so that I can process it, however I have no idea how. As you will see by the code below, the outer 2 most layers are 2 dictionaries, however, python says the 2nd dictionary ("item") is just a string when I call its type. Am I incorrect in how I interpret the structure? sample_object6 = { "items": { "item": [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, { "id": "1003", "type": "Blueberry" }, { "id": "1004", "type": "Devil's Food" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5007", "type": "Powdered Sugar" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] }, { "id": "0002", "type": "donut", "name": "Raised", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] }, { "id": "0003", "type": "donut", "name": "Old Fashioned", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" } ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] }, { "id": "0004", "type": "bar", "name": "Bar", "ppu": 0.75, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, ] }, "topping": [ { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ], "fillings": { "filling": [ { "id": "7001", "name": "None", "addcost": 0 }, { "id": "7002", "name": "Custard", "addcost": 0.25 }, { "id": "7003", "name": "Whipped Cream", "addcost": 0.25 } ] } }, { "id": "0005…
tagged with: python
has comment: http://stackoverflow.com/comment/80606645
tagged with: http://stackoverflow.com/tag/json
has title: How to Remove Outer Layer of JSON in Python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80612039
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/a/46824689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80609486
answers question: http://stackoverflow.com/q/46822235
accepted answer of: http://stackoverflow.com/q/46822235
type: Answer
has comment: http://stackoverflow.com/comment/80596962
score: 0
has body: Take a look at the pygame.Rect class and its collision detection methods. Give your objects rects as attributes which you get by calling the .get_rect() method of the images/surfaces. Update the coordinates of these rects each frame and in your main loop call player.rect.colliderect(enemy.rect) to check if the two rects collide. import pygame import random pygame.init() BLACK = pygame.Color('black') display = pygame.display.set_mode((600, 300)) # Create a rect with the dimensions of the screen at coords (0, 0). display_rect = display.get_rect() clock = pygame.time.Clock() # SNAKE_IMAGE = pygame.image.load('SnakePart.png').convert_alpha() # APPLE_IMAGE = pygame.image.load('Apple.png').convert_alpha() # Replacement images. SNAKE_IMAGE = pygame.Surface((30, 30)) SNAKE_IMAGE.fill((30, 150, 0)) APPLE_IMAGE = pygame.Surface((30, 30)) APPLE_IMAGE.fill((150, 30, 0)) class Player: def __init__(self): self.x = display_rect.w // 2 self.y = display_rect.h - 30 - 5 self.image = SNAKE_IMAGE # Create a rect with the size of the image at coords (0, 0). self.rect = self.image.get_rect() # Set the topleft coords of the rect. self.rect.x = self.x self.rect.y = self.y self.x_change = 0 def update(self): """Move the player.""" self.x += self.x_change # Always update the rect, because it's # needed for the collision detection. self.rect.x = self.x def draw(self, display): display.blit(self.image, self.rect) class Enemy: def __init__(self): self.x = random.randint(0, display_rect.w - 30) self.y = 1 self.image = APPLE_IMAGE # You can also pass the coords directly to `get_rect`. self.rect = self.image.get_rect(topleft=(self.x, self.y)) self.speed = 10 def change_x(self): self.x = random.randint(0, display_rect.w - self.rect.w) self.rect.x = self.x def change_y(self): self.y += self.speed self.rect.y = self.y def draw(self, display): display.blit(self.image, self.rect) def reset(self): """Reset self.y position.""" self.y = -30 player = Player() enemy = Enemy() dodged = 0 done = False while n…

http://stackoverflow.com/a/46869677
downvote count: 0
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46869662
answers question: http://stackoverflow.com/q/46869662
score: 4
has body: You were very close! def Combine(A, B): if len(A) &gt; 0: return str(A[0]) + str(B) + Combine(A[1:], B) # &lt;-- fix 1 else: return '' # &lt;-- fix 2 in order to call recursively with the rest of A you should call A[1:] you took care of the case that len(A) &gt; 0 but forgot to take care of the case that A ran out of characters (the else) Running A = 'YELLOW' B = 'BA' print(Combine(A, B)) OUTPUT YBAEBALBALBAOBAWBA
type: AcceptedAnswer

http://stackoverflow.com/q/46836319
has body: I have set an environment variable of PYTHONPATH, (system)Path, (user)Path to C:\Users\amwil\Junk. Inside the 'Junk' dir there is a python file hello.py containing one line of code print('hello hello') In PowerShell if I run python hello.py and 'no such file or directory' is returned. In ipython, from the same location, I can import hello. I also tested def hello(): print('hello hello') return (with similar results - Python is recognizing the path but not the system) python C:\Users\amwil\Junk\hello.py works Error message: can't open file 'hello.py': [Errno 2] No such file or directory Any ideas as to what is going on? EDIT: To clarify, I am trying to run a python file from an arbitrary directory (not the working directory). Running python from command line works, as does running python hello.py when in the correct working directory (i.e. Junk). It would be best to have, say, C:\Users\other as the working directory, and be able to run python hello.py to the command line (where hello is contained in C:\Users\Junk).
has comment: http://stackoverflow.com/comment/80620554
has comment: http://stackoverflow.com/comment/80626743
tagged with: environment-variables
has title: Running a Python script in Powershell with Environment Variables set
has comment: http://stackoverflow.com/comment/80620309
downvote count: 0
has comment: http://stackoverflow.com/comment/80620396
has comment: http://stackoverflow.com/comment/80620608
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80620618
tagged with: python
has comment: http://stackoverflow.com/comment/80620430
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/80620359
has comment: http://stackoverflow.com/comment/80620465
upvote count: 1
type: Question
tagged with: powershell

http://stackoverflow.com/q/46827323
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46847470
score: 1
has answer: http://stackoverflow.com/a/46884542
type: Question
possible better answer: http://stackoverflow.com/a/46884542
downvote count: 0
tagged with: raster
accepted answer: http://stackoverflow.com/a/46847470
answer count: 3
tagged with: matrix
has body: I got this working code snippet: import numpy as np from matplotlib import pyplot as plt in_raster = np.random.randn(36, 3, 2151) matrix = np.reshape(in_raster, [(np.shape(in_raster)[0] * np.shape(in_raster)[1]), np.shape(in_raster)[2]]) # reshaping the matrix to prepare loop out_raster = np.empty([np.shape(in_raster)[0]/3, np.shape(in_raster)[1]/3, np.shape(in_raster)[2]]) # creating empty output matrix i = 0 j = 0 while i &lt;= len(in_raster)-9 or j &lt; len(out_raster): if i % 9 == 0: avg_in_raster = np.nanmean(matrix[i:i+9, :], axis=0) out_raster[j] = avg_in_raster i += 9 j += 1 out_raster = np.reshape(out_raster, [np.shape(out_raster)[0], np.shape(in_raster)[1]/3, np.shape(in_raster)[2]]) # plot example low = 0 high = 50 for row in range(0, 3): for col in range(np.shape(in_raster)[1]): plt.plot(range(low,high), (in_raster[row, col, low:high])) plt.plot(range(low,high), (out_raster[0,0,low:high]), 'k') plt.show() The program averages (aggregates) 3x3 slices of the input matrix (a raster image) and sets up a new one maintainig the dimensionality of the original matrix. Now I got the feeling that there must be an easier way to achieve this. Does somebody have an idea how to obtain the same result in a more pythonic way? Thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/46885301
upvote count: 1
has title: How to average slices of a 3D Matrix maintaining its shape
tagged with: python

http://stackoverflow.com/q/46881868
tagged with: cartesian-product
tagged with: python
tagged with: delimiter
downvote count: 1
type: Question
tagged with: python-itertools
score: -1
has title: Calculate Cartasian product Itertools.product without comma(Delimiter)
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/46881938
favorite count: 0
tagged with: python-3.x
has body: Hello i just keep wondering how do we calculate cartesian product(intertools.product(*somelist)) BUT without printing the Comma ? I WANT IT TO PRINT SOMETHING LIKE THIS! So, if the first input is of the form: A, B, .. X and the second is of the form: 1, 2, .. n the output would be of the form: ["A 1", "A 2", .. "An", "B 1", "B 2", .. "Bn", .. "X 1", "X 2", .. "Xn"] (where the ".." indicates there can be more elements in between). Here is a more specific case: For inputs: blue, electric, floating and: cheese, eel we would get: ["blue cheese", "electric cheese", "floating cheese", "blue eel",........... HOWEVER WHEN I DO listA=[] #Creating a list listB=[]#Creating a second list listC=[] input_listA=input( "Enter second comma separated list of int: " ) listA.append(input_listA) input_listB = input( "Enter first comma separated list of strings: " ) listB.append(input_listB) listC.append(listB) listC.append(listA) for i in itertools.product(*listA,*listB): print(i) it give this output: INPUT: Enter second comma separated list of int: A, B, C Enter first comma separated list of strings: 1, 2, 3 ('A', '1') ('A', ',') ('A', ' ') ('A', '2') ('A', ',') ('A', ' ') ('A', '3') (',', '1') (',', ',') (',', ' ') (',', '2') (',', ',') (',', ' ') (',', '3') (' ', '1') (' ', ',') (' ', ' ') (' ', '2') (' ', ',') (' ', ' ') (' ', '3') ('B', '1') ('B', ',') ('B', ' ') HOW CAN I DO IT PRINT THEM IN THE RIGHT FORM OF "A 1", "A 2", .. "An" HOW TO REMOVE "," AND " "
type: UnansweredQuestion

arrays
tags question: http://stackoverflow.com/q/46858715
tags question: http://stackoverflow.com/q/46856314
tags question: http://stackoverflow.com/q/46836480
tags question: http://stackoverflow.com/q/46796117
tags question: http://stackoverflow.com/q/46840226
tags question: http://stackoverflow.com/q/46887157
type: Tag
tags question: http://stackoverflow.com/q/46793112
tags question: http://stackoverflow.com/q/46894349
tags question: http://stackoverflow.com/q/46812804
tags question: http://stackoverflow.com/q/46843686
tags question: http://stackoverflow.com/q/46866730
tags question: http://stackoverflow.com/q/46878400
tags question: http://stackoverflow.com/q/46847329
tags question: http://stackoverflow.com/q/46781143
tags question: http://stackoverflow.com/q/46857766
tags question: http://stackoverflow.com/q/46856979
tags question: http://stackoverflow.com/q/46833593
tags question: http://stackoverflow.com/q/46881755
tags question: http://stackoverflow.com/q/46866105
tags question: http://stackoverflow.com/q/46839909
tags question: http://stackoverflow.com/q/46771858
tags question: http://stackoverflow.com/q/46893369
tags question: http://stackoverflow.com/q/46875236
tags question: http://stackoverflow.com/q/46748917
tags question: http://stackoverflow.com/q/46895891
tags question: http://stackoverflow.com/q/46826184
tags question: http://stackoverflow.com/q/46801280
tags question: http://stackoverflow.com/q/46774792
tags question: http://stackoverflow.com/q/46852741
tags question: http://stackoverflow.com/q/46786868
tags question: http://stackoverflow.com/q/46760717
tags question: http://stackoverflow.com/q/46791664
tags question: http://stackoverflow.com/q/46830270
tags question: http://stackoverflow.com/q/46897380
tags question: http://stackoverflow.com/q/46892857
tags question: http://stackoverflow.com/q/46856221
tags question: http://stackoverflow.com/q/46821320
tags question: http://stackoverflow.com/q/46865130
tags question: http://stackoverflow.com/q/46795836
tags question: http://stackoverflow.com/q/46878153
tags question: http://stackoverflow.com/q/46801175
tags question: http://stackoverflow.com/q/46859304
tags question: http://stackoverflow.com/q/46864077
tags question: http://stackoverflow.com/q/46757860
tags question: http://stackoverflow.com/q/46774106
tags question: http://stackoverflow.com/q/46796005
tags question: http://stackoverflow.com/q/46885888
tags question: http://stackoverflow.com/q/46860970
tags question: http://stackoverflow.com/q/46762011
tags question: http://stackoverflow.com/q/46819433
tag name: arrays
tags question: http://stackoverflow.com/q/46885031
tags question: http://stackoverflow.com/q/46802122
tags question: http://stackoverflow.com/q/46808533
tags question: http://stackoverflow.com/q/46761745
tags question: http://stackoverflow.com/q/46867215
tags question: http://stackoverflow.com/q/46799741
tags question: http://stackoverflow.com/q/46832955
tags question: http://stackoverflow.com/q/46861171
tags question: http://stackoverflow.com/q/46888976
tags question: http://stackoverflow.com/q/46750647
tags question: http://stackoverflow.com/q/46809027
tags question: http://stackoverflow.com/q/46776982
tags question: http://stackoverflow.com/q/46868855
tags question: http://stackoverflow.com/q/46817819
tags question: http://stackoverflow.com/q/46792780
tags question: http://stackoverflow.com/q/46775913
tags question: http://stackoverflow.com/q/46859609
tags question: http://stackoverflow.com/q/46761892
tags question: http://stackoverflow.com/q/46810539
tags question: http://stackoverflow.com/q/46889408
tags question: http://stackoverflow.com/q/46766469
tags question: http://stackoverflow.com/q/46870026
tags question: http://stackoverflow.com/q/46862256
tags question: http://stackoverflow.com/q/46799456
tags question: http://stackoverflow.com/q/46888891
tags question: http://stackoverflow.com/q/46822640
tags question: http://stackoverflow.com/q/46867709
tags question: http://stackoverflow.com/q/46860457

http://stackoverflow.com/comment/80532997
comment on: http://stackoverflow.com/q/46790702
has text: I have added the error message.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80746772
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46899816
score: 1
has text: Is there currently content in `webapp.urls` that Django can understand? Also why the extra set of parentheses?

http://stackoverflow.com/q/46900642
favorite count: 0
upvote count: 0
has title: I wants to add a new column based on dates in my csv file using python or pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80748309
type: Question
downvote count: 2
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/46900766
has answer: http://stackoverflow.com/a/46900766
tagged with: python
has body: I need to add a new column called national holidays to my current csv file based on this picnational holidays that i want to add could anyone offer me some helpcurrent csv file i have

http://stackoverflow.com/a/46793923
score: 1
has body: Solution with decorator: I think you can use this decorator to add user in celery task from functools import wraps def append_user(func): @wraps(func) def __wrapper__(*args, **kwargs): user_login = kwargs.pop('user_login') CuserMiddleware.set_user(user_login) return func(*args, **kwargs) return __wrapper__ And apply it to task this way @task @append_user def celery_job(): pass Also for my celery task I use this decorator (to turn off all async jobs in settings) def async_task(func): from django.conf import settings ALL_TASKS_IS_ASYNC = getattr(settings, 'ALL_TASKS_IS_ASYNC', True) @wraps(func) def __wrapper__(*args, **kwargs): async = kwargs.pop('async', ALL_TASKS_IS_ASYNC) if async: return func.delay(*args, **kwargs) else: return func(*args, **kwargs) return __wrapper__ And celery_job = async_task(celery_job) in __init__.py file You can use the same idea to append user_login to all tasks def async_task(func): from django.conf import settings ALL_TASKS_IS_ASYNC = getattr(settings, 'ALL_TASKS_IS_ASYNC', True) @wraps(func) def __wrapper__(*args, **kwargs): kwargs['user_login'] = CuserMiddleware.get_user().username async = kwargs.pop('async', ALL_TASKS_IS_ASYNC) if async: return func.delay(*args, **kwargs) else: return func(*args, **kwargs) return __wrapper__ Edit: I think this decorator may optimize refactoring: def task_with_user_info(func): @wraps(func) def __wrapper__(*args, **kwargs): user = CuserMiddleware.get_user() kwargs['user_login'] = user.username return func(*args, **kwargs) if getattr(func, 'delay', None): __wrapper__.delay = task_with_user_info(func.delay) return __wrapper__ @task_with_user_info @task @append_user def celery_job(): pass After this changes you should able to use celery_job as usual.
accepted answer of: http://stackoverflow.com/q/46792488
has comment: http://stackoverflow.com/comment/80538410
answers question: http://stackoverflow.com/q/46792488
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80537531
has comment: http://stackoverflow.com/comment/80535414
has comment: http://stackoverflow.com/comment/80538747
has comment: http://stackoverflow.com/comment/80536133
type: Answer
has comment: http://stackoverflow.com/comment/80541083
has comment: http://stackoverflow.com/comment/80537168
has comment: http://stackoverflow.com/comment/80536971
downvote count: 0
has comment: http://stackoverflow.com/comment/80538154

http://stackoverflow.com/a/46852166
downvote count: 0
score: 3
type: Answer
has body: You can just use slicing. result = some_list[k:]
has comment: http://stackoverflow.com/comment/80651719
upvote count: 3
has comment: http://stackoverflow.com/comment/80651700
answers question: http://stackoverflow.com/q/46852156
has comment: http://stackoverflow.com/comment/80651754
accepted answer of: http://stackoverflow.com/q/46852156
type: AcceptedAnswer

http://stackoverflow.com/comment/80539354
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46796126
has text: Generally the issue on x86 is that the x87 registers are 80 bit, so, as long as the compiler doesn't spill them, you get higher precision than what would be "correct" for 64-bit double precision arithmetic. Try to use `-ffloat-store` and see if x86 and x86_64 give the same results.

http://stackoverflow.com/comment/80805903
has text: that searchsorted is exactly what I was looking for. Vectorised solution at the end is very clever too. Thanks heaps!
type: Comment
comment on: http://stackoverflow.com/a/46904322
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80687999
score: 0
has text: How did you defined the `@app.route` and what url are you using to do the post?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46870307

http://stackoverflow.com/a/46874925
upvote count: 12
answers question: http://stackoverflow.com/q/46861158
score: 12
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46861158
downvote count: 0
has comment: http://stackoverflow.com/comment/80701052
has body: The equivalent of Stata's regress ..., robust in statsmodels is OLS(...).fit(cov_type='HC1') The options for the robust sandwich covariance matrices are here http://www.statsmodels.org/devel/generated/statsmodels.regression.linear_model.RegressionResults.get_robustcov_results.html, but the use is through the fit keywords. There is an incomplete FAQ answer for differences in robust standard errors between Stata and statsmodels. https://github.com/statsmodels/statsmodels/issues/1923 statsmodel.robust and RLM refer to outlier robust estimation. This is an M-estimator and the covariance has the original Huber sandwich form. Here is the main page for statsmodels.robust http://www.statsmodels.org/devel/rlm.html and the documentation for RLM http://www.statsmodels.org/devel/generated/statsmodels.robust.robust_linear_model.RLM.html
type: Answer

http://stackoverflow.com/comment/80503224
comment on: http://stackoverflow.com/q/46773858
type: Comment
type: QuestionComment
has text: @Pi but I have already mentioned it here https://gist.github.com/pgsin/2816cf5b69cd3c9b6b4ccc55ac99c02f
score: 0

http://stackoverflow.com/comment/80672411
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46862450
score: 2
has text: Shouldn't your output be: `{'first': [], 'second': [[2, 3], [7, 6]]}` ?

amazon-s3
tags question: http://stackoverflow.com/q/46814197
tags question: http://stackoverflow.com/q/46827441
type: Tag
tags question: http://stackoverflow.com/q/46819590
tags question: http://stackoverflow.com/q/46799070
tags question: http://stackoverflow.com/q/46834779
tags question: http://stackoverflow.com/q/46853123
tags question: http://stackoverflow.com/q/46892085
tags question: http://stackoverflow.com/q/46896785
tags question: http://stackoverflow.com/q/46874385
tag name: amazon-s3
tags question: http://stackoverflow.com/q/46858874
tags question: http://stackoverflow.com/q/46857179
tags question: http://stackoverflow.com/q/46779745
tags question: http://stackoverflow.com/q/46890838

http://stackoverflow.com/q/46802319
has comment: http://stackoverflow.com/comment/80551739
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80551796
tagged with: python
has title: yield returns None in python?
has body: I have 2 python classes in two files. file: LdapConnection, class: LdapClass(), method : getMachines(self) @defer.inlineCallbacks def getMachines(self): c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) overrides = {self.basedn: (self.serverip, 389)} client = yield c.connect(self.basedn, overrides=overrides) yield client.bind(self.binddn, self.bindpw) o = ldapsyntax.LDAPEntry(client, self.basedn) results = yield o.search(filterText=self.query) for entry in results: for i in entry.get('name'): self.machineList.append(i) yield self.machineList print self.machineList return above print statements print all entires in the machineList file:Twisted, class:Caching, method:loadSettings(self) @defer.inlineCallbacks def loadSettings(self): returned = yield LdapClass().getMachines() print returned in the above class my print prints None. What Im doing wrong here?
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46803512
linked to: http://stackoverflow.com/q/10695456
has comment: http://stackoverflow.com/comment/80552318
has answer: http://stackoverflow.com/a/46821036
answer count: 2
linked to: http://stackoverflow.com/q/46801724
tagged with: twisted
has comment: http://stackoverflow.com/comment/80564193
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/80685990
score: 0
comment on: http://stackoverflow.com/a/46869297
type: Comment
type: AnswerComment
has text: I tried adding this to my code and it did not produce an output

http://stackoverflow.com/comment/80544967
has text: Excellent. Thanks buddy.
comment on: http://stackoverflow.com/a/46798884
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80706110
type: Comment
comment on: http://stackoverflow.com/a/46878741
has text: thank you for the explanation. I knew that the problem somewhere in decoding bytes when printing, but I didn't know what is exactly wrong. Your explanation is quite clear. Spasibo!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80612771
has text: Yup... one could use `a == (not(b))` if one really wanted... but... Anyway - might be useful to link to [operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence)...
comment on: http://stackoverflow.com/a/46832640
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46841929
answers question: http://stackoverflow.com/q/46841896
downvote count: 0
has body: It's probably not a reflection of Python per se but of the math it captures. Usually the coefficients on x is a matrix which has a convention of being an uppercase variable. That this is a 1-dimensional example you're seeing obscures this convention, higher dimensions would be more telling.
upvote count: 6
type: AcceptedAnswer
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/46841896

http://stackoverflow.com/q/46749393
has answer: http://stackoverflow.com/a/46749460
has title: Pygame couldnt load picture
has answer: http://stackoverflow.com/a/46754258
score: 0
has comment: http://stackoverflow.com/comment/80444990
has body: I'm making a game and when i try to load the picture it says "Cannot find reference 'load' in 'image.py'" That's my code: import pygame pygame.init() display_width = 800 display_height = 600 black = (0, 0, 0,) white = (255, 255, 255) red = (255, 0, 0) gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Boat Race') clock = pygame.time.Clock() carImg = pygame.image.load('boat.png') crashed = False while not crashed: for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True pygame.display.update() clock.tick(30) pygame.quit() quit()
type: UnansweredQuestion
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/80767739
comment on: http://stackoverflow.com/a/46809413
type: Comment
has text: Following your advice, I now implemented my pipeline in C++ and now have following problem: https://stackoverflow.com/questions/46910328/how-to-use-dlibs-lda Would be great to get a hint!
score: 0
type: AnswerComment

http://stackoverflow.com/q/46874861
score: 0
has body: I am new to Python just for my own interest. I am taking the introductory course from eDX. I would like to understand why when I run the following code, the reverse function will reverse both the reverse_fours list and the original all_fours all_fours = fours + more_fours reverse_fours = all_fours print("All ",all_fours) print("Reverse ",reverse_fours) reverse_fours.reverse() print("All ",all_fours) print("Reverse ",reverse_fours)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80696664
linked to: http://stackoverflow.com/q/19951816
answer count: 0
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has title: About reverse operation
has comment: http://stackoverflow.com/comment/80696641

http://stackoverflow.com/q/46854496
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/62362555
linked to: http://stackoverflow.com/q/889333
tagged with: python
score: 11
tagged with: http://stackoverflow.com/tag/jpeg
has answer: http://stackoverflow.com/a/60011153
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/53470932
tagged with: image
type: Question
has body: I wrote a python script to detect broken images and count them, The problem in my script is it detects all the images and does not detect broken images. How to fix this. I refered : How to check if a file is a valid image file? for my code My code import os from os import listdir from PIL import Image count=0 for filename in os.listdir('/Users/ajinkyabobade/Desktop/2'): if filename.endswith('.JPG'): try: img=Image.open('/Users/ajinkyabobade/Desktop/2'+filename) img.verify() except(IOError,SyntaxError)as e: print('Bad file : '+filename) count=count+1 print(count)
has answer: http://stackoverflow.com/a/76068255
downvote count: 0
has title: Python Script to detect broken images
tagged with: python-3.6
has answer: http://stackoverflow.com/a/46854605
favorite count: 0
upvote count: 11
linked to: http://stackoverflow.com/q/6996603
answer count: 5

http://stackoverflow.com/comment/80537964
has text: i know it hasn't, but is there some workaround but it's just not intended to be used, or is it absolutely impossible?
comment on: http://stackoverflow.com/q/46795627
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46826843
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Reshape to split each axes into one more axis each of length 2, giving us a 6D array and then get the mean along those latter ones (axes : 1,3,5) - m,n,r = a.shape out = a.reshape(m//2,2,n//2,2,r//2,2).mean((1,3,5)) Extending to n-dim array, it would be - def shrink(a, S=2): # S : shrink factor new_shp = np.vstack((np.array(a.shape)//S,[S]*a.ndim)).ravel('F') return a.reshape(new_shp).mean(tuple(1+2*np.arange(a.ndim))) Sample run - In [407]: a Out[407]: array([[[1, 5, 8, 2], [5, 6, 4, 0], [8, 5, 5, 5], [1, 0, 0, 0]], [[0, 0, 7, 6], [3, 5, 4, 3], [4, 5, 1, 3], [6, 7, 4, 0]]]) In [408]: a[:2,:2,:2].mean() Out[408]: 3.125 In [409]: a[:2,:2,2:4].mean() Out[409]: 4.25 In [410]: a[:2,2:4,:2].mean() Out[410]: 4.5 In [411]: a[:2,2:4,2:4].mean() Out[411]: 2.25 In [412]: shrink(a, S=2) Out[412]: array([[[ 3.125, 4.25 ], [ 4.5 , 2.25 ]]])
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46826705
answers question: http://stackoverflow.com/q/46826705

http://stackoverflow.com/q/46757190
score: 1
has comment: http://stackoverflow.com/comment/80460225
has comment: http://stackoverflow.com/comment/80466325
upvote count: 1
has answer: http://stackoverflow.com/a/46757426
accepted answer: http://stackoverflow.com/a/46757426
favorite count: 0
has answer: http://stackoverflow.com/a/46757291
answer count: 3
has title: Algorithm to convert a 2d binary list to decimal numbers in Python
tagged with: python
has body: I ran into this performance issue when I tried to convert a huge 2D list of binary data to decimal numbers. Given a list: biglist = [ [[1,0],[0,0],[1,1]], [[0,0],[1,1],[1,0]], #... #easily go to thousands of rows ] In each row, I want combine all first element of each column and convert it into a decimal number: E.g. In row 0, I want int('101',2) i.e. 5 In row 1, I want int('011',2) i.e. 3 My final goal is to create a dictionary that counts what integer appears how many times. Considering the given data in the example above, the final result should be a dictionary with {key:value} pair like {a_int : appearance_count} like this: {{5:1},{3:1}} Now my solution is this: result = {} for k in biglist: num = int("".join(str(row[0]) for row in k), 2) #count if num not in result: result[num] = 1 else: result[num] += 1 This loop is slow for a list of thousands of rows, is there a better solution?
downvote count: 0
has comment: http://stackoverflow.com/comment/80459795
has answer: http://stackoverflow.com/a/46757674
has comment: http://stackoverflow.com/comment/80459727
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46757291
tagged with: list
tagged with: algorithm

http://stackoverflow.com/comment/80615004
has text: `df1['Path'].apply(lambda x : datetime.fromtimestamp(os.path.getmtime(x)))` ??
score: 0
comment on: http://stackoverflow.com/q/46833670
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46833344
has answer: http://stackoverflow.com/a/46833456
downvote count: 1
type: Question
tagged with: jython
upvote count: 0
score: -1
tagged with: jes
accepted answer: http://stackoverflow.com/a/46833456
answer count: 1
has comment: http://stackoverflow.com/comment/80614356
has comment: http://stackoverflow.com/comment/80615506
favorite count: 0
has body: I keep encountering a runtime error resulting from a nested If then statement not working properly. Not very experienced with JES, so thus why I am reaching out for help. Basically, (see sourcecode below) my newX (is used w. function randrange to generate new xy coords) and newY if over 599 or under, then set that var back to 0. Well, I am seeing getPixel(picture,x,y): y (= -22) is less than 0 or bigger than the height (= 599) The error value is: Inappropriate argument value (of correct type). An error occurred attempting to pass an argument to a function. Please check line 39 of E:\dOX\HW\INF 120\e_Project5.py from random import * def main( ): #draw pic = makeEmptyPicture(600, 600, white) show(pic) #for the 4 boxes boxCount = 0 #while statement to draw while boxCount &lt; 4: addRectFilled(pic, randrange(0,576), randrange(0,576), 25, 25, red) addArcFilled(pic, randrange(0,576), randrange(0,576), 10, 10, 0, 360, blue) boxCount = boxCount + 1 repaint(pic) newX = 0 newY = 0 oldX = 0 oldY = 0 robotcount = 0 finished = 0 safe = 0 triggered = 0 while robotcount &lt; 750 or finished != 1 or safe != 1 or triggered != 1: oldX = newX oldY = newY newX = newX + randrange(-25, 26) newY = newY + randrange(-25, 26) if newX &gt; 599 or newX &lt; 0: newX = 0 elif newY &gt; 599 or newY &lt; 0: newY = 0 px = getPixel(pic, newX, newY) color = getColor(px) if color == red: triggered = 1 printNow("trig") elif color == blue: safe = 1 printNow("safe") elif robotcount == 750: finished = 1 printNow("Fin") addLine(pic, oldX, oldY, newX, newY, black) robotcount = robotcount + 1
tagged with: python
type: AnsweredQuestion
has title: JES, nested if statement not working correctly

overloading
tags question: http://stackoverflow.com/q/46885618
type: Tag
tags question: http://stackoverflow.com/q/46780070
tag name: overloading

http://stackoverflow.com/comment/80572708
type: QuestionComment
has text: `strings.splitlines()` will never return a different result
comment on: http://stackoverflow.com/q/46812722
score: 1
type: Comment

http://stackoverflow.com/comment/84331367
has text: Hey guys. The bug wasn't in your code, it was in a Windows task scheduler setup. Technically this should probably be moved to ServerFault.com since it isn't code-related. Also - @MauriceMeyer create an answer so Alexander can mark it accepted. Happy coding :)
comment on: http://stackoverflow.com/q/46886257
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46902318
has body: I was trying to find a fastest way to figure out the number of days in a month among the following three functions. def f1(): t=time.time() for month in range(1,13): for year in range(10001): leap_year=(year%4==0 and year%100!=0) or year%400==0 n=[29,31,28,31,30,31,30,31,31,30,31,30,31][month-2*leap_year*(month==2)] return time.time()-t1 def f2(): t=time.time() for month in range(1,13): for year in range(10001): leap_year=(year%4==0 and year%100!=0) or year%400==0 n=[31,28,31,30,31,30,31,31,30,31,30,31][month-1]+leap_year*(month==2) return time.time()-t def f3(): t=time.time() for month in range(1,13): for year in range(10001): leap_year=(year%4==0 and year%100!=0) or year%400==0 n={1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}[month]+leap_year*(month==2) return time.time()-t print(sum(f1() for i in range(100))) print(sum(f2() for i in range(100))) print(sum(f3() for i in range(100))) I was expecting the algorithm with dictionary would have the fastest speed. However, I got this: 3.7855005264282227 3.625513792037964 9.0009183883667 Obviously, I was wrong. Can someone explain why the dict algorithm has the least speed? It should take the least amount of time,O(1), and the list algorithms should take O(n), which is contradictory to the results I got. I am very new to programming. Thanks!
has comment: http://stackoverflow.com/comment/80751438
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/80751484
tagged with: python-3.x
type: Question
tagged with: python
has title: Speed of algorithms
has comment: http://stackoverflow.com/comment/80751421
answer count: 1
downvote count: 1
tagged with: algorithm
upvote count: 0
has answer: http://stackoverflow.com/a/46902513
type: UnansweredQuestion

http://stackoverflow.com/comment/80842718
type: AnswerComment
comment on: http://stackoverflow.com/a/46887721
type: Comment
has text: I installed them with pip. they must be newest. mac is 10.12.6, python is 3.6
score: 0

http://stackoverflow.com/comment/80618613
comment on: http://stackoverflow.com/a/46835471
score: 0
type: AnswerComment
has text: `deepcopy` is unnecessary. A shallow copy is sufficient. The easiest way to make a shallow copy of a dictionary is to pass it to `dict` (as in `copy_of_d = dict(d)`). Also making the copy after modification mutates the contents of `MylistOfdict` which may be an unwanted side effect. To avoid this the copy should be made at the top of the inner loop.
type: Comment

http://stackoverflow.com/a/46762389
type: Answer
answers question: http://stackoverflow.com/q/46762195
has body: Your line of thinking was correct. You haven't used min max as variable names, which is great too. If u r using python 3, replace the input keyword with raw_input in the below code. Hope it worked! :) minn=5000; maxx=0; while True: reply = input("Enter text, (type [stop] to quit): ") if int(reply) &lt; int(minn): minn = int(reply) if int(reply) &gt; int(maxx): maxx = int(reply) if reply == 'stop': break print("Min is " + str(minn)) print("Max is " + str(maxx))
score: 0

http://stackoverflow.com/comment/80694025
comment on: http://stackoverflow.com/q/46856379
type: Comment
type: QuestionComment
has text: I'd like to introduce you to [Bobby Tables](http://bobby-tables.com/)...
score: 2

http://stackoverflow.com/comment/80477011
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46765881
has text: where is the description of the problem
score: 0

http://stackoverflow.com/comment/80568272
score: 0
has text: I used the unofficial windows libraries. might this be the problem ?
type: QuestionComment
comment on: http://stackoverflow.com/q/46806265
type: Comment

http://stackoverflow.com/comment/80921164
has text: @JoranBeasleybut **what IP address do you give for connection** ..can you send me a simple code ? Also, **what are the seetings for bridged adapter** there is NO option for port forwarding in bridged adapter setting on virtual box ???
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46898941
score: 0

http://stackoverflow.com/comment/80709049
type: AnswerComment
comment on: http://stackoverflow.com/a/46880682
type: Comment
has text: Incorrect. There is the ‘move‘ method for moving a canvas object in the x and/or y direction, and the ‘coords‘ method to give it a new set of coordinates.
score: 2

http://stackoverflow.com/a/46873036
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46768571
type: Answer
has body: This problem was related to the version below Theano.0.10, Once it is updated this problem is solved. In case someone is facing the same problem.
answers question: http://stackoverflow.com/q/46768571
score: 0

http://stackoverflow.com/comment/80669631
type: Comment
type: QuestionComment
score: 4
has text: max is comparing your strings in lexical order not length of string
comment on: http://stackoverflow.com/q/46861134

http://stackoverflow.com/q/46846923
type: Question
has body: I'm trying to override attributes in my Django application and for some reason I cannot override some attributes of the LoginView. I've tried to do that both as my own class based view and directly on the urlconfig, passing the attributes as arguments to the as_view function, nothing worked. To be more specific, i'm trying to override the template_name but it seems like Django ignores my argument and still trying to look to 'registration/login.html', even though i've passed another path of my own HTML template in another directory. What am I doing wrong? Here is my code, or how I tried to use it: url(r'^accounts/logout/$', auth_views.LogoutView.as_view(template_name='accounts/login.html')), or class SigninView(LoginView): template_name = 'login.html' def get(request): form = LoginForm return render(request, self.template_name, {'form':form}) I've already tried to change the name (or the path) of my template name, both as the as_view function or on my created class based view, but Django looks always for this specific path - '/registration/login.html' - basically to the origin path. Therefore I assumed that Django doesn't recognise for some reason my overriding and looks for the original attributes as it's set in the LoginView. The error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://localhost:8000/accounts/login/ Django Version: 1.11.6 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Request Method: GET Request URL: http://localhost:8000/accounts/login/... Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/Roi/Desktop/Programming/mysite/home/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/templates/registration/login.html (Sour…
answer count: 1
has title: Django LoginView doesn't override attributes
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80641383
has answer: http://stackoverflow.com/a/67716191
type: UnansweredQuestion
score: 7
upvote count: 7

http://stackoverflow.com/comment/80657682
comment on: http://stackoverflow.com/q/46855071
type: Comment
type: QuestionComment
score: 2
has text: you have a space after every `u` ... that is a syntax error ...

http://stackoverflow.com/comment/80734079
score: 0
type: Comment
type: QuestionComment
has text: what does `"cscript DoSomething.vbs"` when run from the console? does it exit?
comment on: http://stackoverflow.com/q/46893428

http://stackoverflow.com/a/48236411
has comment: http://stackoverflow.com/comment/85336583
type: Answer
downvote count: 6
answers question: http://stackoverflow.com/q/46902357
has comment: http://stackoverflow.com/comment/87822116
upvote count: 18
score: 12
has body: Use the below command to solve your issue, pip install mysql-python apt-get install python3-mysqldb libmysqlclient-dev python-dev Works on Debian

http://stackoverflow.com/a/46812612
has comment: http://stackoverflow.com/comment/80572630
type: Answer
has body: What you need seems like hashing, which standard Python classes set and dictionary use. However, the object list you need to store, is not hashable, therefore not directly available for using in these containers. Hash tables gives O(1) complexity for accessing, which is what you need for checking regularly. But there are some difficulties presented by the data type you need to hash, here how can you overcome this. 1-) You can convert the list to a tuple, then store in a set or dictionary if you also want to assign some values to the key. This requires the O(n) conversion to tuple. Please note that you can't make changes to a tuple, you should completely replace it (which is why it is hashable, and list is not). all_states = set() state = tuple([0, 0, 0, 0, 0, 0, 0, 0, 0]) all_states.add(state) 2-) If you want to stick to lists, I guess making a wrapper class, then hashing should work, cannot vouch for this method to be a suggested Pythonic way of doing this. class State: def __init__(self, contents): self.contents = contents one_state = State([1, 2, 3]) hash(one_state) # Now it is hashable, just for checking. # If you can add it to a set, it is hashable. all_states.add(state)
has comment: http://stackoverflow.com/comment/80572532
answers question: http://stackoverflow.com/q/46812081
score: 0

http://stackoverflow.com/comment/80502629
type: Comment
has text: make sure you are not missing `,` after temperature
comment on: http://stackoverflow.com/a/46777561
type: AnswerComment
score: 0

http://stackoverflow.com/a/46881660
has body: Try removing the to_position from the list before re-inserting it, then perform the reorder.
answers question: http://stackoverflow.com/q/46867148
type: Answer
score: 0

http://stackoverflow.com/a/46841079
upvote count: 5
has comment: http://stackoverflow.com/comment/80631385
downvote count: 0
answers question: http://stackoverflow.com/q/46840752
score: 5
type: Answer
has body: If I'm understanding your project requirements correctly, you probably want to avoid str.replace() altogether and go with something like this, which is just a more explicit variation of @Ajax1234's answer: string = input('Enter a string: ') collector = [] for char in string: if char == 'e': char = 'x' elif char == ' ': char = '*' collector.append(char) new_string = ''.join(collector) Side note: you don't need the loop variable i to iterate over a string. You can just iterate directly over the characters in the string as shown above. A standard-library option would be to use str.translate(): &gt;&gt;&gt; table = str.maketrans(' e', '*x') &gt;&gt;&gt; 'hello world'.translate(table) 'hxllo*world'

http://stackoverflow.com/comment/80471945
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46763121
has text: `img_source` and `edited_image` are the same image, just as you defined them to be with the statement `edited_image = image_source`. Therefore, when you change `edited_image`, you are also changing `image_source`.

http://stackoverflow.com/a/47368463
answers question: http://stackoverflow.com/q/46899409
type: AcceptedAnswer
downvote count: 0
has body: I think the issue is not with whoosh but in the way you are parsing your input file. If you are inconsistent in reading data from the input file, you will get the lists id, body, Score in different sizes causing this line to fail: writer.add_document(id_details=id[x],body_details=body[x],Score_details=Score[x]) Since you are only comparing to the limit of list id : range(len(id)) Try to improve your parsing of the file or at least compare your x to the limit of the shortest list between id, body, Score
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46899409
has comment: http://stackoverflow.com/comment/81718086

http://stackoverflow.com/comment/80625283
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46825678
score: 0
has text: Thank you Shikha! that fixed it. Im more of a visual learner so seeing how something is suppose to be done helps more than information overflow. I see above spaces is used more than indentation, i will read up more on when to use indentions rather spaces. When you said top menu selected, format -> dedent region. What were you referring to? At first i thought you meant in Sublime text IDE because i mentioned i was using that, but i dont see a Format option at the top. But i do have Python selected as the main syntax.

operators
tags question: http://stackoverflow.com/q/46782825
tags question: http://stackoverflow.com/q/46863049
tag name: operators
tags question: http://stackoverflow.com/q/46758683
type: Tag

http://stackoverflow.com/comment/80623124
type: Comment
has text: With "cannot specify the size of the data" I think I'm referring to what you mentioned in a comment of the main question: "The major trade-off you are making is one of space". Regarding 2) I would just note that we should compare dict vs array + sort, which is why dict is slower but not several orders of magnitude slower. 3) I used vectorized in my application, I just wanted to have a simple(ish) MWE.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46835592

http://stackoverflow.com/comment/80626390
type: AnswerComment
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ sir, may i eat your brain so i may steal your powers? this is awesome!!
comment on: http://stackoverflow.com/a/46839088
score: 0

http://stackoverflow.com/comment/80563894
type: QuestionComment
has text: This works fine with me
score: 1
comment on: http://stackoverflow.com/q/46806711
type: Comment

http://stackoverflow.com/comment/80544396
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46798641
has text: Are you asking how to write a regex that matches the conditions you set?

http://stackoverflow.com/q/46859115
type: Question
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/80875070
has comment: http://stackoverflow.com/comment/80713284
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has body: recently I am learning how to convert a Bayer image to an RGB image. I know there are several ways to do it: bilinear interpolation; freeman's improvement of bilinear interpolation; constant hue based interpolation; gradient based Interpolation; etc ... I learned the above from a paper named "Demosaicking methods for Bayer color arrays". But when I try to implement the constant hue based interpolation approach, I encountered an issue. According to the paper, the result of that approach should be better than the result from simple bilinear interpolation. Unfortunately, I got the opposite result. Here is the result from my program: I don't have enough reputation to put a image, here is a link to the result image >> result image My program is following: import cv2 as cv def hue_constant_interpolation(_mosaic): _mosaic = cv.normalize(_mosaic.astype('double'), None, 0.0, 1.0, cv.NORM_MINMAX) # split the image into three channel b, g, r = cv.split(_mosaic) # set the value which is useless to 0 b = fill_with_zero_b(b) g = fill_with_zero_g(g) r = fill_with_zero_r(r) # do the linear interpolation for green channel g = bilinear_interpolation_g(g) # using the estimated green channel to calculate # the red and blue channels, hue has been interpolated g = cv.copyMakeBorder(g, 1, 1, 1, 1, cv.BORDER_REFLECT) b = hue_constant_channel_b(b, g) r = hue_constant_channel_r(r, g) return cv.merge((b, g, r)) def hue_constant_channel_r(estimating, interpolated): estimating = cv.copyMakeBorder(estimating, 1, 1, 1, 1, cv.BORDER_REFLECT) e_row_num = len(estimating) for row in range(1, e_row_num - 1): e_col_num = len(estimating[row]) interpolated_row_median = np.median(interpolated[row]) for col in range(1, e_col_num - 1): if row % 2 != 0 and col % 2 == 0: if estimating[row][col] == 0: g1 = interpolated[row][col - 1] g2 = interpolated[row][col + 1] estimating[row][col] = 0.5 * interpolated[row][col] * ( estimating[row][col - 1] / (g1 if g1 != 0 else interpolated_row_median) + estimating[row][co…
has comment: http://stackoverflow.com/comment/80872107
has title: constant hue based interpolation opencv python
has comment: http://stackoverflow.com/comment/80683720
answer count: 0
tagged with: image-processing

http://stackoverflow.com/q/46755640
favorite count: 0
possible better answer: http://stackoverflow.com/a/46755876
has answer: http://stackoverflow.com/a/46755876
type: Question
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/46755809
has title: Spawning multiple processes with Python
has body: Earlier I tried to use the threading module in python to create multiple threads. Then I learned about the GIL and how it does not allow taking advantage of multiple CPU cores on a single machine. So now I'm trying to do multiprocessing (I don't strictly need seperate threads). Here is a sample code I wrote to see if distinct processes are being created. But as can be seen in the output below, I'm getting the same process ID everytime. So multiple processes are not being created. What am I missing? import multiprocessing as mp import os def pri(): print(os.getpid()) if __name__=='__main__': # Checking number of CPU cores print(mp.cpu_count()) processes=[mp.Process(target=pri()) for x in range(1,4)] for p in processes: p.start() for p in processes: p.join() Output: 4 12554 12554 12554
has comment: http://stackoverflow.com/comment/80456735
downvote count: 1
tagged with: multiprocessing
upvote count: 5
accepted answer: http://stackoverflow.com/a/46755809
linked to: http://stackoverflow.com/q/1294382
tagged with: python-multiprocessing
answer count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/80499171
type: Comment
type: QuestionComment
has text: Maybe we are missing code here but none of your parameter are assigned beforehand, also what is your goal ? your question seems vague to me.
comment on: http://stackoverflow.com/q/46776769
score: 0

http://stackoverflow.com/a/46775533
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46775342
has comment: http://stackoverflow.com/comment/80657081
upvote count: 3
has body: You should not use self as a variable name as it is used to specify if something is an attribute of the instance of the class. You do not need to use global in classes either as class attributes are used in most cases when dealing with variables that are needed through the class. Judging by the code you have shown I think you are trying to do something like this: from tkinter import * class start(): def __init__(self, root): self.master = root self.master.title('__init__') self.master.geometry('300x300') Canvas(self.master, bg='black').pack() root = Tk() start(root) root.mainloop() However I believe you are struggling with the OOP method of programing and I would suggest to not use OOP to start with if this is the case. Maybe take a few tutorials on youtube or hit up Codecadamy. In response to your comments: In my Opinion using init properly is a bad idea. I use it as a regular def. I doesn't matter if I use self global, unless the function/class variable is called self. I respect the proper use of init, but I just find the whole thing with, init and self.master I just don't get any of it! Lack of understanding a thing does not mean said thing is bad. The use of self.master is there to provide a class attribute that ties back to the root Tk() variable. This allows any method within the class to interact with the instance of Tk(). I can't speak to other programing languages but the use of self is a very important in OOP for python. It may not be 100% required to reserve self for referencing to either the instance of the object or the class attribute but it is the accepted and known use of self and really should not be changed/overwritten.
has comment: http://stackoverflow.com/comment/80539588
type: Answer
has comment: http://stackoverflow.com/comment/80540405
has comment: http://stackoverflow.com/comment/80496768
has comment: http://stackoverflow.com/comment/80539820
has comment: http://stackoverflow.com/comment/80594758
has comment: http://stackoverflow.com/comment/80498641
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80496699
has comment: http://stackoverflow.com/comment/80498189
has comment: http://stackoverflow.com/comment/80594657
has comment: http://stackoverflow.com/comment/80539551
accepted answer of: http://stackoverflow.com/q/46775342

http://stackoverflow.com/comment/80579490
type: Comment
score: 0
type: QuestionComment
has text: Use a recipe [like this one](https://seasonofcode.com/posts/python-multiprocessing-and-exceptions.html) to wrap your worker function bodies in try/except blocks to capture exceptions in the workers that may not be getting propagated to the main process. I can't think of any reason they *wouldn't* cause an exception in the main process, but that would be my next debugging step. Just confirm you don't have hidden errors in your workers.
comment on: http://stackoverflow.com/q/46813568

http://stackoverflow.com/comment/80541523
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46797267
score: 1
has text: You need to provide more details. If by "extra commas" you mean that certain rows have more "columns" than others, a csv parser can still handle that, but `pandas` won't be able to put that into a data-frame, since it expects trict, tabular data. However, if the column you are interested in is always X columns from the right, then it should be relatively easy to extract this with the `csv` module.

http://stackoverflow.com/q/46876880
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/46877133
accepted answer: http://stackoverflow.com/a/46877133
type: AnsweredQuestion
tagged with: syntax
tagged with: pyqt5
downvote count: 1
type: Question
has title: Correct way to convert old SIGNAL and SLOT to new style?
tagged with: pyqt4
score: 4
tagged with: signals-slots
answer count: 1
has body: I'm currently trying to convert an old python program from Python 2 to Python 3, and update from PyQt4 to PyQt5. The application uses the old style signal and slots that are not supported under PyQt5. I have figured out most of what needs to be done, but below are a few lines that I can't seem to get working: self.emit(SIGNAL('currentChanged'), row, col) self.emit(SIGNAL("activated(const QString &amp;)"), self.currentText()) self.connect(self,SIGNAL("currentChanged(const QString&amp;)"), self.currentChanged) The top two lines, I have no idea where to start since they don't seem to be attached to anything. The last example I'm not quite sure what to do with (const QString &amp;). I'm not entirely sure how to approach these, and I'm still learning python, but any help would be appreciated. EDIT: The documentation doesn't really seem to go into depth on these cases, at least in a way that I understand.
favorite count: 0

http://stackoverflow.com/comment/126061357
comment on: http://stackoverflow.com/q/46770201
type: Comment
type: QuestionComment
has text: I liked your statement which is so so hilarious - "Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint."
score: 0

http://stackoverflow.com/comment/80570328
score: 0
type: AnswerComment
has text: Sorry, not good with Elasticsearch queries. All I changed was the ordering of your code. The hit results should still exist
type: Comment
comment on: http://stackoverflow.com/a/46811195

http://stackoverflow.com/q/46836267
score: 0
has body: I'm pretty new with python and sql and i'm so confused right now with a query problem, some help will be appreciated. What i've: I've a function who looks for coincidences of text input on MySQL table. PD: I'm loading the DB conection on another file with MySQLdb Code: #!/usr/bin/python # -*- coding: utf-8 -*- from Config.DBConfig import * class SomeClass: def Search(self): Fruit = 'App' cur.execute("SELECT reference,name FROM fruits WHERE name LIKE '%%%s%%'" % (Fruit)) row = cur.fetchall() print row Test = SomeClass() Test.Search() And it returns the correct output: 001 , Apples are red 002 , apples 004 , Green APPLES But now i want to do the same with 2 or more keywords on the same text input field and it must return the fruits ( reference and name ) who has those partial keywords on the fruit name ( both keywords ), for example: input = 'App re' output: 001 , Apples are red 004 , Green Apples I can't figure how i can concatenate those input keywords with SQL LIKEs or maybe i'm looking for the wrong method ( almost for sure ). Need some help or guidance or tip plz Thx to everybody. EDIT: #!/usr/bin/python # -*- coding: utf-8 -*- from Config.DBConfig import * class SomeClass: def Search(self): Fruit = 'App re' word1, word2 = Fruit.split() cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%') UNION SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word1, word2)) row = cur.fetchall() print row It's not exactly what i need ( i only want those results who has the 2 words ) but i'm approaching to the desired result. EDIT 2: Finally achieved what i wanted ( probably in a bad way, but it works ): #!/usr/bin/python # -*- coding: utf-8 -*- from Config.DBConfig import * class SomeClass: def Search(self): Fruit = input_some_text if len(Fruit.split()) == 1: cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (Fruit)) row = cur.fetchall() for result in row: print result if len(Fruit.split()) == 2: word1, word2 = Fruit.…
tagged with: mysql
type: UnansweredQuestion
tagged with: python-2.7
has title: Python MySQLdb query to search multiple partial keywords
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/80620319
has comment: http://stackoverflow.com/comment/80622521
tagged with: python
has comment: http://stackoverflow.com/comment/80620539

http://stackoverflow.com/a/46791488
has comment: http://stackoverflow.com/comment/80529821
type: Answer
has body: You have to perform an aggregation on the GroupedData and collect the results before you can iterate over them e.g. count items per group: res = df.groupby(field).count().collect()
score: 2
has comment: http://stackoverflow.com/comment/80622046
has comment: http://stackoverflow.com/comment/80540941
upvote count: 2
answers question: http://stackoverflow.com/q/46791254
has comment: http://stackoverflow.com/comment/80624130
has comment: http://stackoverflow.com/comment/80535822
has comment: http://stackoverflow.com/comment/80624009
has comment: http://stackoverflow.com/comment/80540560
downvote count: 0
has comment: http://stackoverflow.com/comment/80621841

http://stackoverflow.com/comment/80600242
has text: I got rid of it for now. It doesn’t matter right now.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46826290
type: Comment

http://stackoverflow.com/a/65986794
score: 0
has body: You're assigning selection before the user has the chance to change the selected option. Putting it in a function that calls when a 'save' button is pressed would likely be the simplest fix. You could also use a recursion loop to update it in real time but it's not a clean solution. I'm assuming you've already included root.mainloop() in your actual script.
answers question: http://stackoverflow.com/q/46831855
type: Answer

http://stackoverflow.com/comment/80466064
score: 0
type: AnswerComment
has text: Can you execute `pip install Django` and let me know what you see? I just want to make sure it's the same error as the one you posted above.
comment on: http://stackoverflow.com/a/46759965
type: Comment

http://stackoverflow.com/comment/134891701
score: 0
comment on: http://stackoverflow.com/a/72965011
type: Comment
has text: Does this take 1000 samples from each group?
type: AnswerComment

http://stackoverflow.com/comment/80446272
type: QuestionComment
comment on: http://stackoverflow.com/q/46750017
has text: Compare [np.dot()](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dot.html#numpy.dot) with [np.ndarray.dot()](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.dot.html).
score: 0
type: Comment

http://stackoverflow.com/comment/80718559
has text: it depends of your idea of **is it better**
score: 1
comment on: http://stackoverflow.com/q/46885591
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80571544
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46807209
score: 0
has text: I have the same error when doing this (that being said, I should definitely be importing the modules like this). Note however that import error I get does not concern an external module, but my own pipeline "spanner_backup", which I put in the folder "pipelines".

http://stackoverflow.com/comment/80666965
type: AnswerComment
comment on: http://stackoverflow.com/a/46843285
score: 0
type: Comment
has text: Hi, thanks, but I need to pass these into the other model, the create_print is okay as it is, what I don't know or understand is how to pass those on the very same method, I guess values.update isn't the way to go.

http://stackoverflow.com/a/46808623
upvote count: 3
has body: One approach (linear-time operations on #nnz only): from scipy.sparse import find, csr_matrix import numpy as np # Create the data (Taken from DavidG's answer! Thanks!) data = np.array([-1, 0, -1, 0, -1, 1, 1, -1, 0, -1, 0, 0]).reshape(2, 6) a = csr_matrix((data), dtype=np.int8) nnz_inds = a.nonzero() keep = np.where(a.data == 1)[0] n_keep = len(keep) b = csr_matrix((np.ones(n_keep), (nnz_inds[0][keep], nnz_inds[1][keep])), shape=a.shape) # CHECK print('a') print(a.todense()) print('b') print(b.todense()) Output: a [[-1 0 -1 0 -1 1] [ 1 -1 0 -1 0 0]] b [[ 0. 0. 0. 0. 0. 1.] [ 1. 0. 0. 0. 0. 0.]] The basic idea is simple: look up all positions where nonzeroes are (exploiting sparsity) filter above to get all positions where 1's are create a new matrix from scratch using the prepared positions &amp; data (exploiting sparsity)
accepted answer of: http://stackoverflow.com/q/46806690
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46806690
type: Answer
score: 3

http://stackoverflow.com/comment/80744018
type: QuestionComment
comment on: http://stackoverflow.com/q/46882932
has text: I think I got the idea. I included skimage, but the warning log is still showing numpy, matplotlib and loads of other modules in 90 kb, and I'd have to include all those. My exe is already at 150 MB with skimage only, so the file would be huge and the process long. Thanks anyway.
score: 0
type: Comment

http://stackoverflow.com/comment/81104449
comment on: http://stackoverflow.com/a/46878739
type: Comment
has text: @ekhumoro. Thanks! I tried your patch again, I still get an error (see the question for details). Do you think you can fix it?
score: 0
type: AnswerComment

http://stackoverflow.com/q/46895463
accepted answer: http://stackoverflow.com/a/46895644
has comment: http://stackoverflow.com/comment/80738261
tagged with: python
has comment: http://stackoverflow.com/comment/80738006
type: AnsweredQuestion
tagged with: list
type: Question
tagged with: expression
has body: I have a list that has the data types of a dataframe. I would like to change the values in the list based on the existing values. list = [dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64')] I want a new list whose values are "Double" for values "dtype('float64')" and "Long" for anything else. I tried this expression but doesn't work. listnew = ["Double" if x == "dtype('float64')" else "Long" for x in list]
tagged with: replace
score: 0
has answer: http://stackoverflow.com/a/46895644
answer count: 1
has title: change values in a list based on its existing values

http://stackoverflow.com/q/46816874
has comment: http://stackoverflow.com/comment/80625197
tagged with: graph
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/46857426
downvote count: 1
has body: I have a large set of vertices/nodes that represent a set of graphs. Note that there could be many independent graphs within this complete set. The goal is to find the min number of vertices across all these graphs that correspond to the largest total sum of weights across all the edges captured by those selected vertices. I have the adjacency matrix in pandas and I am using networkx. Below is a sample dataframe with the three columns where Number_Of_Trips is the weight. I could provide a weight of node = 10*trips in order to merge the two metrics together. I.e. maximizing # of Trips - 10*NumberOfNodes Number_Of_Trips dropoff_gh7 pickup_gh7 0 304 9tbqhsx 9tbqj4g 1 271 9tbqj4f 9tbqhsx 2 263 9tbqt4s 9tbqhsx 3 258 9tbqdye 9tbqdsr 4 256 9tbqhgh 9tbqjfv 5 236 9tbqhsw 9tbqj4g 6 233 9tbqt4g 9tbqv03 7 229 9tbqhsx 9tbqj4c 8 218 9tbqy3f 9tbqt4s 9 213 9tbq5v4 9tbqh41 10 210 9tbqhgh 9tbqhsw 11 192 9tbqhgh 9tbqje4 12 186 9tbqy3f 9tbqt4g 13 184 9tbqhgh 9tbqj4z 14 183 9tbqe3d 9tbqe9e 15 170 9tbq3xn 9tbq39w 16 167 9tbq5bw 9tbqht6 17 163 9tbqhsx 9tbqh0x 18 162 9tbqdk1 9tbq7p2 19 160 9tbqsch 9tbqt4s x = nx.from_pandas_dataframe(df,"dropoff_gh7","pickup_gh7","Number_Of_Trips") graphs = list(nx.connected_component_subgraphs(x))
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/80597089
possible better answer: http://stackoverflow.com/a/46857426
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80615342
has title: How to find the min set of vertices in multiple potentially independent UNdirected Graphs that captures the largest total cost
has comment: http://stackoverflow.com/comment/80619744
type: AnsweredQuestion
tagged with: undirected-graph
has answer: http://stackoverflow.com/a/47041235
has comment: http://stackoverflow.com/comment/80597100
accepted answer: http://stackoverflow.com/a/47041235
has comment: http://stackoverflow.com/comment/80620654
has comment: http://stackoverflow.com/comment/80613771
tagged with: networkx
has comment: http://stackoverflow.com/comment/80586906
type: Question
has comment: http://stackoverflow.com/comment/80661796
has comment: http://stackoverflow.com/comment/80616926
has comment: http://stackoverflow.com/comment/80661033
has comment: http://stackoverflow.com/comment/80582133
has comment: http://stackoverflow.com/comment/80625368

http://stackoverflow.com/q/46866105
downvote count: 3
linked to: http://stackoverflow.com/q/1720421
has comment: http://stackoverflow.com/comment/80679709
type: Question
accepted answer: http://stackoverflow.com/a/46866145
duplicate of: http://stackoverflow.com/q/1720421
has comment: http://stackoverflow.com/comment/80679901
has body: I have 2 lists, for example: [1, 2, 3] and [4, 5, 6] How do I merge them into 1 new list?: [1, 2, 3, 4, 5, 6] not [[1, 2, 3], [4, 5, 6]]
answer count: 2
possible better answer: http://stackoverflow.com/a/46866140
has comment: http://stackoverflow.com/comment/80679707
has title: How do I merge lists in python?
tagged with: arrays
has answer: http://stackoverflow.com/a/46866140
favorite count: 0
has comment: http://stackoverflow.com/comment/80679642
has comment: http://stackoverflow.com/comment/80679758
upvote count: 61
has comment: http://stackoverflow.com/comment/80679742
has answer: http://stackoverflow.com/a/46866145
tagged with: python
type: AnsweredQuestion
score: 58

http://stackoverflow.com/a/46867899
type: Answer
has body: Another recursive solution using generators: def flatten(s): if not isinstance(s, list): yield s else: for i in s: for b in flatten(i): yield b print(list(flatten([[3,65,[3, [[5, 6, [2, 6, [4]]]]],[88,44,[9, 4, 56]],[6,2,21]]]))) Output: [3, 65, 3, 5, 6, 2, 6, 4, 88, 44, 9, 4, 56, 6, 2, 21]
answers question: http://stackoverflow.com/q/46867704
score: 0

http://stackoverflow.com/q/46881755
tagged with: arrays
type: UnansweredQuestion
tagged with: python
has body: I want to create a new array (or list) for every iteration. Here is my code: import numpy as np data2 = open('pathways.dat', 'r', errors = 'ignore') pathways = data2.readlines() special_line_indexes = [] PWY_ID = [] line_cont = [] L_PRMR = [] #Left primary #i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate) for CUI in just_compound_id: for i,line in enumerate(pathways): if '//' in line: #fint the indexes of the lines containing // special_line_indexes = i+1 elif 'REACTION-LAYOUT -' in line: if CUI in line: PWY_ID.append(special_line_indexes) Specifically I want to create a different array PWY_ID for a different iteration of CUI (the first foor loop). What I end up is instead a long array with all the output. Maybe it would be more efficient to use a dictionary, but I am not sure how to implement it in a for loop...
type: Question
has answer: http://stackoverflow.com/a/46881874
has title: Python create new array for different iteration of a for loop
score: 0
tagged with: for-loop
answer count: 1

http://stackoverflow.com/comment/80594727
comment on: http://stackoverflow.com/q/46787345
score: 0
type: Comment
type: QuestionComment
has text: By "work" I meant debugging work, not coding. Programming isn't just about writing code. Basically the philosophy of SO on troubleshooting questions is: if your problem isn't condensed down to a few lines of code and a clear "Here's what I expected this code to do" and "here's what happened," then your question 1) isn't valuable to later readers and 2) implies your time is more valuable than the answerer's - both of which attract downvotes.

http://stackoverflow.com/comment/81676553
score: 1
comment on: http://stackoverflow.com/a/47336045
type: AnswerComment
has text: I assumed the bounty was opened after accepting that answer. The intent of the bounty was to get an alternative answer which doesn't use subprocess and is able to do the same thing using a normal pytest test case. So better or not this is one of the ways you would do it using a pure python script instead of subprocessing setup.py
type: Comment

http://stackoverflow.com/a/46862860
has body: Hello! The solution depends on your purposes. Use comprehensions if you want to construct a list of json arrays: data_items = [json.loads(item.json_field) for item in model_query] ... or generator of json array: data_items = (json.loads(item.json_field) for item in model_query) If you want to have a single array of json objects try this: data_items = [] for item in model_query: data_items.extend(json.loads(item.json_field)) Then you can use data_items as a template context. A little tip: You can utilize JSONField at ORM level if you use PostgreSQL or MySQL. Consider this approach if you plan to make any filter queries on this field. As additional benefit JSON encoding/decoding will be out of box.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46862581

http://stackoverflow.com/q/46881407
answer count: 4
has title: how to list all keywords used by a robotframework test suite
downvote count: 0
has answer: http://stackoverflow.com/a/52586765
favorite count: 0
type: Question
score: 5
has body: If a robotframework project has keywords that spreads out in several folders (e.g., in resource and library files), is there a utility to list all user-defined keywords along with the lower level keywords invoked ? This utility is similar to how the 'cflow' utility parses all c source files and produce a database file.
tagged with: python
has answer: http://stackoverflow.com/a/46889332
has answer: http://stackoverflow.com/a/46881699
tagged with: robotframework
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46882345

http://stackoverflow.com/a/46883884
upvote count: 1
has comment: http://stackoverflow.com/comment/80715321
downvote count: 0
answers question: http://stackoverflow.com/q/46883495
has body: In your app urls.py your saying that: http://127.0.0.1:8000/ should call votes.views.index not http://127.0.0.1:8000/votes/, so you need to change it to: from django.conf.urls import url from . import views urlpatterns = [ url(r'^votes/$', views.index, name='index'), ]
type: Answer
has comment: http://stackoverflow.com/comment/80715188
score: 1

http://stackoverflow.com/q/46874238
type: AnsweredQuestion
has body: I'm pretty new to python as a whole so apologies, but i'm tasked with building a standalone power function for exponents upto 4. So far i have; def power(x,n): if(n==1): return x if(n==2): return square(x) if(n==3): return cube(x) if(n==4): return hypercube(x) with the square, cube and hypercube functions being; def square(x): return x*x def cube(x): return x*x*x def hypercube(x): return x*x*x*x I'm trying to replace the square, cube and hypercube functions with calls to the power function itself, but i'm having trouble understanding recursive call. I tried the following thinking you just have to call from within directly to the end result. I'm struggling just being able to visualise this def power(x,n): if(n==1): return x if(n==2): return power(x^) if(n==3): return power(x^n) if(n==4): return power(x^n)
has title: Building own recursive power function
answer count: 1
accepted answer: http://stackoverflow.com/a/46874271
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/46874271
type: Question
tagged with: recursion

http://stackoverflow.com/comment/80684727
type: Comment
has text: hi Bear, I tried it, it still gives me the same exception.
comment on: http://stackoverflow.com/a/46868715
score: 0
type: AnswerComment

http://stackoverflow.com/a/46782415
upvote count: 2
has comment: http://stackoverflow.com/comment/80550352
has comment: http://stackoverflow.com/comment/80551181
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46762708
downvote count: 0
has body: The length of your links list never reaches 0 so it will continue to run the while loop until the connection times out. Your for loop works because it is iterating over a range, so it will exit once the range maximum is reached. You never explained why you're using a while loop, but if you want it to exit after a certain number of iterations, you need to use a counter. counter = 0 # this will exit on the 5th iteration while counter &lt; 5: print counter # do something counter += 1 # increment the counter after each iteration The preceding will print 0 1 2 3 4
accepted answer of: http://stackoverflow.com/q/46762708
type: Answer
score: 2

pygobject
type: Tag
tags question: http://stackoverflow.com/q/46774755
tags question: http://stackoverflow.com/q/46776451
tags question: http://stackoverflow.com/q/46760398
tag name: pygobject

http://stackoverflow.com/a/46897964
accepted answer of: http://stackoverflow.com/q/46897929
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46897929
type: AcceptedAnswer
has body: It is difference between max and diff - max aggregate values (return aggregate Series) and diff not - return same size Series. So is possible append output to new column: df['shifted'] = df.groupby(['one', 'two'])['three'].shift() Theoretically is possible use agg, but it return error in pandas 0.20.3: df1 = df.groupby(['one', 'two'])['three'].agg(['max', lambda x: x.shift()]) print (df1) ValueError: Function does not reduce One possible solution is transform if need max with diff: g = df.groupby(['one', 'two'])['three'] df['max'] = g.transform('max') df['shifted'] = g.shift() print (df) one three two max shifted 0 a 1 c 3 NaN 1 a 2 c 3 1.0 2 a 3 c 3 2.0 3 b 4 c 4 NaN 4 b 5 d 6 NaN 5 b 6 d 6 5.0
downvote count: 0

http://stackoverflow.com/a/46884576
upvote count: 1
has body: You could use lookarounds and a list comprehension: import re strings = ['TotalAmt', 'ProgramServicesAmt', 'Desc'] rx = re.compile(r'(?&lt;=[a-z])(?=[A-Z])') nstrings = [rx.sub(' ', string) for string in strings] print(nstrings) # ['Total Amt', 'Program Services Amt', 'Desc'] Here, the expression (?&lt;=[a-z])(?=[A-Z]) ensures there's a lowercase letter behind and an UPPERCASE letter ahead. This position is replaced by a space and put in a comprehension. See a demo on regex101.com.
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/46884402
answers question: http://stackoverflow.com/q/46884402

http://stackoverflow.com/a/46887772
answers question: http://stackoverflow.com/q/46887753
type: Answer
accepted answer of: http://stackoverflow.com/q/46887753
score: 15
upvote count: 15
has body: You need to run your easy_install command with sudo privileges if you want to write to /Library Try running the following command: sudo easy_install pip and then enter your password
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46832263
tagged with: dictionary
type: AnsweredQuestion
tagged with: if-statement
score: 1
has title: Getting duplicate values while appending cleaned data to dictionary
accepted answer: http://stackoverflow.com/a/46832388
type: Question
answer count: 2
tagged with: for-loop
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/46832547
has answer: http://stackoverflow.com/a/46832547
has body: I have a txt file and I need to extract some values and organize as dictionary. Here is the needed format! {State: Town} for example {'Alabama': 'Auburn', Alabama: 'Florence'....'Wyoming': 'Laramie'} Here is my code: with open('my.txt') as file: output = [] current_state = "" region = "" for line in file: if (len(line.split("[edit]")) == 2): current_state = line.split("[edit]")[0] else: region = line.split(" (")[0] if (region != ""): output.append([current_state, region]) return output However, my code doesn't do what I want it to do. It feels as I'm storing previously extracted "region" value and appending it to the next state. So there is something wrong with the logic and I'm not sure what exactly. [['Alabama', 'Auburn'], ['Alabama', 'Florence'], ['Alabama', 'Jacksonville'], ['Alabama', 'Livingston'], ['Alabama', 'Montevallo'], ['Alabama', 'Troy'], ['Alabama', 'Tuscaloosa'], ['Alabama', 'Tuskegee'], ['Alaska', 'Tuskegee'], ['Alaska', 'Fairbanks'], ['Arizona', 'Fairbanks'], ['Arizona', 'Flagstaff'], ['Arizona', 'Tempe'], ['Arizona', 'Tucson'],...] As you can see I'm getting 'Fairbanks' 2 times, first it is appended to Alaska, which is correct and second it is getting appended to Arizona, which is not correct. I have this happening to all of my states. ... ['Alaska', 'Fairbanks'], ['Arizona', 'Fairbanks'], ... ['Wisconsin', 'Whitewater'], ['Wyoming', 'Whitewater'], ['Wyoming', 'Laramie']]
has answer: http://stackoverflow.com/a/46832388
has comment: http://stackoverflow.com/comment/80612053
upvote count: 1
tagged with: python

http://stackoverflow.com/q/46830943
tagged with: list
upvote count: 1
linked to: http://stackoverflow.com/q/526331
has comment: http://stackoverflow.com/comment/80609627
tagged with: graph
has answer: http://stackoverflow.com/a/46832018
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80609453
has comment: http://stackoverflow.com/comment/80610805
has comment: http://stackoverflow.com/comment/80610504
downvote count: 0
has comment: http://stackoverflow.com/comment/80610435
has comment: http://stackoverflow.com/comment/80609262
has body: I'm trying to identify bubble structures in a directed graph (orientation is left to right). I start walking the graph from a possible start node, for example the green node. Then I add one node to all paths, adding copies of paths when paths diverge again, like this: first iteration: [[3],[7]] Second iteration: [[3,4],[3,5],[7,8],[7,9]] After every iteration I want to check whether any paths intersect and save them as confirmed bubbles. Currently I'm using a nested for-loop to compare every path to one another but the amount of paths can get very large and thus the script can get very slow. The order of the path matters. Any suggestions on how to improve the speed of comparing a path to another path in a list of paths? def ExtendPaths(paths, outEdges): newPaths = [] for path in paths: nextNodes = GetNextSegment(path[len(path) - 1], outEdges) if len(nextNodes) == 0: j=5 else: for node in nextNodes: newPath = list(path) newPath.append(node) newPaths.append(newPath) return newPaths def ComparePaths(paths, putativeBubbleStartSegment): length = len(paths) for path1 in paths: for path2 in paths: if path2 != path1: if len(set(path1).intersection(path2)) &gt; 0: #Bubble confirmed Where GetNextSegment simply returns a list of nodes connected to the node given to the function (in this case, the last node of the path). outEdges is a dictionary with: node:[out,going,edges]. In ComparePaths() a bubble is confirmed when the length of the .intersection() of 2 paths is greater than 0. A bubble is a graph structure where 2 paths diverge (from the green node, for example) and finally come together again. In this example, the bubble would go from 2 to 11 with all nodes between them. I'm not asking for a complete bubble-finding algorithm, just for ideas on how to compare all paths to all other paths quickly.
score: 1
has comment: http://stackoverflow.com/comment/80612575
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80609383
has comment: http://stackoverflow.com/comment/80610473
tagged with: python
answer count: 1
has title: Fastest way for finding a common element between two lists in a list of lists

http://stackoverflow.com/a/46846119
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46845132
downvote count: 0
answers question: http://stackoverflow.com/q/46845132
has comment: http://stackoverflow.com/comment/100664782
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/100660463
has body: To bind one property to another you should use the setter event: self.bind(_MyProperty=self._Child.setter('_MyProperty'))
has comment: http://stackoverflow.com/comment/100661271
has comment: http://stackoverflow.com/comment/100653024

state
tag name: state
tags question: http://stackoverflow.com/q/46794306
type: Tag

http://stackoverflow.com/q/46762655
upvote count: 0
answer count: 1
has title: How to combine two strings to describe a property of tree.insert?
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/46765327
has body: I'm creating a gui with tKinter, working with python for the first time. Part of my gui is a treeview, the nodes in the treeview have images attached. I made a function to add new nodes to the treeview. I want to add an image to the new node based on the mother of the node. In this case The variable 'curItem' returns the mother as a string, "test" in this case. I want to combine the string "photo_" and "test" and use this in the 'tree.insert' code. But for this to work I have to convert the string to something else, but I dont know to what and how to do this. This is probably a very basic question, but I have been unable to find an answer so far. Part of the relevant code: photo_test = PhotoImage(file="resources/test.png") def add(): curItem = tree.selection()[0] #returns "test" img = "photo_" + curItem tree.insert(curItem, 'end', text='new', image=img) #doesn't work tree.insert(curItem, 'end', text='new', image=photo_test) #works
tagged with: tkinter
tagged with: treeview
downvote count: 1
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/46765327
type: Question

http://stackoverflow.com/q/46814687
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/46814896
has comment: http://stackoverflow.com/comment/80577128
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80577008
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/46814896
has comment: http://stackoverflow.com/comment/80577323
favorite count: 0
type: Question
tagged with: python
has body: I have a data frame with empty cells like this: Col1 Col2 Col3 Col4 Col5 A B C G E R P J C K T I want to create an extra column with the number of empty cells in each row, so the expected output is like this: ID Col1 Col2 Col3 Col4 Col5 No_Of_Empty 1 A B C 2 2 G 3 3 E R P 2 4 J 3 5 C K T 3 Here is what I tried: df['No_Of_Des'] = df.iloc[:,1::].apply(lambda x: sum(x==' '), axis = 1) The output I am getting is not likethe expected one, I am not sure what is wrong here?
has title: Counting number of empty cells in pandas data frame on the row level and create a column accordingly

http://stackoverflow.com/a/46765274
has body: Try this: from bs4 import BeautifulSoup import requests res = requests.get("https://www.sec.gov/cgi-bin/browse-edgar?CIK=orcl").text soup = BeautifulSoup(res,'lxml') for item in soup.find_all(class_="mailerAddress")[:2]: print(item.text) Result: 500 ORACLE PARKWAY MAIL STOP 5 OP 7
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46759563
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80615303
score: 1
has text: What do you mean by magic access? What you've done seems really reasonable, if you wanted to do all of these in one go then bundle the methods into a file, and have a single method to call that then calls out to the other methods.
comment on: http://stackoverflow.com/q/46833780
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80745830
type: Comment
type: QuestionComment
has text: Its very difficult to say anything from your current code. However, the error says that rgb is not defined in your code. I guess you are trying to use a local variable of another function in a different place with this for loop.
comment on: http://stackoverflow.com/q/46899190
score: 0

http://stackoverflow.com/comment/80470281
comment on: http://stackoverflow.com/a/46762500
has text: Specifically, be careful not to overwrite your variables with different meanings. You have `user_pattern` as both their pattern string and you use that name for each letter in the pattern (similar for `simon_pattern`).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46867009
accepted answer: http://stackoverflow.com/a/46867064
has title: How to Create dataframe from existing CSV file in Python
possible better answer: http://stackoverflow.com/a/54636587
type: Question
has comment: http://stackoverflow.com/comment/80681733
tagged with: dataframe
has body: I am trying to create dataframe object from an existing CSV file in python but I am facing problems. I tried to import CSV file into python but I do not know whether I succeeded or not. &gt;&gt;&gt; import os &gt;&gt;&gt; userhome = os.path.expanduser('~') &gt;&gt;&gt; csvfile= userhome + r'\Desktop\train.csv' &gt;&gt;&gt; with open(csvfile, "r") as f: After I wrote these statements it did not do anything. So the First problem - Did I import CSV file to python? And if I did not how do I import? After that how can I display data from CSV file in python? I installed pandas Python IDE 3.6.3 Shell
score: 0
answer count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80681842
has comment: http://stackoverflow.com/comment/80681511
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54636587
has answer: http://stackoverflow.com/a/46867064

prepend
tags question: http://stackoverflow.com/q/46848079
tag name: prepend
type: Tag

http://stackoverflow.com/q/46892830
has comment: http://stackoverflow.com/comment/80732949
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80733414
tagged with: python
has comment: http://stackoverflow.com/comment/80733192
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/46893372
type: UnansweredQuestion
has body: I'm trying to install 'pymorph' on mac os x with 'PIP': sudo pip install pymorph I'm getting the following error: NameError: name 'execfile' is not defined Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-9hjd5tfm/pymorph/ I have read that using a python version different from 2.7 could lead to this kind of problem. Yet, I'm using the 2.7 version: python --version Python 2.7.13 Any ideas to solve this issue ? Thank you in advance
has comment: http://stackoverflow.com/comment/80733293
tagged with: pip
has title: unable to install pymorph
score: 2
has comment: http://stackoverflow.com/comment/80733465
has comment: http://stackoverflow.com/comment/80732840
type: Question
has comment: http://stackoverflow.com/comment/80733387

http://stackoverflow.com/a/46815616
type: Answer
has body: I like @JonClements itertools count-based solution (+1) but I don't think defaultdict is necessary: from itertools import count text = 'he is hdajs asdas da he is not asd as da s i am a da daas you am a' words = text.split() bigrams = zip(words, words[1:]) seen = dict() result = [(next(seen.setdefault(bigram, count(1))), bigram) for bigram in bigrams] print(*result, sep='\n') OUTPUT (1, ('he', 'is')) (1, ('is', 'hdajs')) (1, ('hdajs', 'asdas')) (1, ('asdas', 'da')) (1, ('da', 'he')) (2, ('he', 'is')) (1, ('is', 'not')) (1, ('not', 'asd')) (1, ('asd', 'as')) (1, ('as', 'da')) (1, ('da', 's')) (1, ('s', 'i')) (1, ('i', 'am')) (1, ('am', 'a')) (1, ('a', 'da')) (1, ('da', 'daas')) (1, ('daas', 'you')) (1, ('you', 'am')) (2, ('am', 'a'))
answers question: http://stackoverflow.com/q/46813982
score: 0

http://stackoverflow.com/comment/80466598
type: QuestionComment
has text: You're looking for argsort functionality.
type: Comment
comment on: http://stackoverflow.com/q/46760626
score: 0

http://stackoverflow.com/a/46756260
has body: You can try openCV probably will be good module to achieve your goal. If you want help then i would love to help you out with the code. :) Here is the link for more info
has comment: http://stackoverflow.com/comment/80458180
has comment: http://stackoverflow.com/comment/80500342
type: Answer
has comment: http://stackoverflow.com/comment/80458279
has comment: http://stackoverflow.com/comment/80458255
answers question: http://stackoverflow.com/q/46755445
downvote count: 0
has comment: http://stackoverflow.com/comment/80457952
score: 1
has comment: http://stackoverflow.com/comment/80458009
upvote count: 1

http://stackoverflow.com/a/54738933
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/46764711
has body: This answer is probably too late, but I found that cv2.circle only can accept centre coordinates precision up to float32. If the coordinates are in float64, it will throw this error. Simple solution is always converting centre coordinates to numpy.float32.
downvote count: 0
score: 10

http://stackoverflow.com/comment/80479291
type: QuestionComment
comment on: http://stackoverflow.com/q/46766936
score: 0
has text: Fairly descriptive error message: try: `file.write(child.tag+";"+str(child.attrib))`
type: Comment

http://stackoverflow.com/comment/117610672
score: 0
has text: u can also consider add_loss... https://stackoverflow.com/a/62402699/10375049
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46858016

http://stackoverflow.com/comment/80445976
type: QuestionComment
comment on: http://stackoverflow.com/q/46749969
type: Comment
score: 2
has text: Whatever other problems you may have, please read https://stackoverflow.com/q/1132941/3001761

http://stackoverflow.com/a/46802085
has body: While it may be against some people's style to have an inheritance hierarchy of abstract classes, I think your current code is fine. You don't need to change anything if you don't want to. Pylint is giving you a warning, since you're doing something that in some situations might be an error, but in others may be OK. If you expected B to be a concrete class, inheriting an abstract method from A without overriding it would be a problem. But if you expect B to be abstract just like A, then it's find for it to not override the abstract method it inherited. So you can either just ignore the warning from Pylint, or suppress the warning by putting a comment # pylint: disable=W0223 in your file. Depending on exactly where the comment is put, I believe it can either disable the warning for the just one specific class or for the whole module.
score: 0
answers question: http://stackoverflow.com/q/46801226
type: Answer

http://stackoverflow.com/q/46798192
linked to: http://stackoverflow.com/q/17676036
score: -1
has comment: http://stackoverflow.com/comment/80543576
tagged with: proxy
has title: Chrome Authentication Alert webdriver
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: google-chrome
has answer: http://stackoverflow.com/a/46798872
tagged with: selenium
has body: I have an application that generates a new browser tab when I click on a link. In the new tab I get the Chrome authentication alert. I've tried using the below code: wd.switch_to_window(wd.window_handles[1]) a = switch_to_alert() a.send_keys('username' + Keys.TAB + 'password') but I get the no alert error msg I have also tried using the ActionChain to send the keys but the alert does not receive the send_keys Are there any alternatives? fyi I cannot use https://username@password format as this tab is generated when I click on a link Traceback
downvote count: 1
tagged with: webdriver
type: Question
upvote count: 0

http://stackoverflow.com/q/46762929
has comment: http://stackoverflow.com/comment/80471163
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46762961
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80471094
has answer: http://stackoverflow.com/a/46763132
type: Question
has body: I have a list, a, defined as the following: a = ['3', 'A', '+', 'Q', '2', '/', '*'] I have a dictionary, d, defined as the following: d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13} I want to apply the dictionary to the elements of the list that are in the dictionary, including 3, A, Q, and 2, while leaving the operations in the same locations and in the same string format. I've tried to use list comprehension, but that tried to apply it to the operations as well. My desired output would be as follows: a = [3, 1, '+', 12, 2, '/', '*'] Any help would be appreciated.
has title: Python - Apply dictionary to list while leaving other elements

http://stackoverflow.com/a/50250155
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/46751140
has body: sudo pip install librosa==0.4.2 worked for me. There was warning yet works fine on Raspberry pi3 (OS:raspbian-jessie)
upvote count: 3
type: Answer

http://stackoverflow.com/comment/80488257
type: Comment
type: QuestionComment
has text: You could collect all those variables in a `dict`.
score: 3
comment on: http://stackoverflow.com/q/46771388

http://stackoverflow.com/q/46780709
has comment: http://stackoverflow.com/comment/80507601
answer count: 0
has comment: http://stackoverflow.com/comment/80507644
tagged with: negate
has comment: http://stackoverflow.com/comment/80507561
type: Question
tagged with: ternary
has body: I've been trying to convert balanced ternary numbers through the negate function in python def convert_to_balanced_ternary(n): if n == 0: return '0' negative = n &lt; 0 bt = '' while n &gt; 0: r = n % 3 if r == 0: bt = '0' + bt n = n // 3 elif r == 1: if negative: bt = '-' + bt else: bt = '+' + bt n = n // 3 else: if negative: bt = '+' + bt else: bt = '-' + bt n = (n + 1) // 3 return bt def negate(n): temp = n.replace('-', '+') or n.replace('+', '-') or n.replace('0', '0') return temp And I can get the '-' to convert to '+' but '+' won't convert to '-'. '0' seems to pass through just fine. negate('+-0') '++0'
duplicate of: http://stackoverflow.com/q/28775049
score: 0
linked to: http://stackoverflow.com/q/28775049
has title: How to use negate function with balanced ternary numbers?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/46993660
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46759218
score: 4
type: Answer
has body: OK, so the answer was pretty straight forward. I just needed to jsonify my dataframe. Then it is basically just a string that can be saved in a hidden div. import dash from dash.dependencies import Input, Output, Event import dash_html_components as html import dash_core_components as dcc from datetime import datetime import numpy as np import pandas as pd app = dash.Dash(__name__) def compute_expensive_data(): t=datetime.now() d = {'time' : pd.Series(np.array([t.minute, t.second]), index=['minute', 'second'])} dat = pd.DataFrame(d).to_json() return dat dat = compute_expensive_data() print(dat) app.layout = html.Div([ html.H3('Original Time: Minute = ' + str(pd.read_json(dat)['time']['minute']) + ': Second = ' + str(pd.read_json(dat)['time']['second'])), html.Div(id='title-line-children'), dcc.RadioItems( id='time-dropdown', options=[ {'label': 'Minute', 'value': 'minute'}, {'label': 'Second', 'value': 'second'}, ], value='minute' ), # Hidden div inside the app that stores the intermediate value html.Div(id='intermediate-value', style={'display': 'none'}, children = dat), dcc.Interval( id='interval-component', interval=20*1000 # 20 seconds in milliseconds ) ]) @app.callback( Output('title-line-children', 'children'), [Input('time-dropdown', 'value'), Input('intermediate-value', 'children')]) def render(value,dat1): if value == 'minute': printStr = str(pd.read_json(dat1)['time']['minute']) outStr = 'Minute = ' + printStr elif value == 'second': printStr = str(pd.read_json(dat1)['time']['second']) outStr = 'Second = ' + printStr return outStr @app.callback(Output('intermediate-value', 'children'), events=[Event('interval-component', 'interval')]) def update_global_var(): return compute_expensive_data() if __name__ == '__main__': app.run_server(debug=True)
has comment: http://stackoverflow.com/comment/103513369
answers question: http://stackoverflow.com/q/46759218
upvote count: 4

http://stackoverflow.com/q/46903935
has comment: http://stackoverflow.com/comment/80754532
type: UnansweredQuestion
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/80755602
has body: I am using GOOGLE S2 Library to create geofence. I have created rectangle by using latitude and longitude as coordinate in java but I am not able to create polygon by using latitude and longitude coordinate. Could you please help me on this. This is code for rectangular geofence in java: Double lo_latDegrees = 51.6934844; Double lo_lngDegrees = -63.568821; //12.960045, 77.640189 Double hi_latDegrees = 51.844379; Double hi_lngDegrees = -63.169301; System.out.println("creating a rectangle"); S2LatLngRect s2latlongRect = new S2LatLngRect(S2LatLng.fromDegrees(lo_latDegrees, lo_lngDegrees), S2LatLng.fromDegrees(hi_latDegrees, hi_lngDegrees)); And for polygon I have tried something like that: private static final String RECTANGLE1 = "10:11, 11:11, 12:11, 12:10, 11:10, 10:10;"; S2Polygon region = Utilities.makePolygon(RECTANGLE1); System.out.println("creating region"); Help me on this. Thanks in advance !!!!!
answer count: 0
tagged with: java
type: Question
tagged with: javascript
score: 0
has title: How to create Polygon using Lat Long as coordinate using Google S2 Library in JAVA

http://stackoverflow.com/q/46754388
tagged with: python-3.4
score: 0
answer count: 1
tagged with: tkinter-entry
type: UnansweredQuestion
tagged with: python
has body: from tkinter import * root = Tk() fN = StringVar() sN = StringVar() age = StringVar() yG = StringVar() Label(root, text="First Name").grid(row=0, sticky=W, padx=4) fName = Entry(root, width=50, textvariable=fN ).grid(row=0, column=1, sticky=E, pady=4) Label(root, text="Surname").grid(row=1, sticky=W, padx=4) sName = Entry(root, width=50, textvariable=sN).grid(row=1, column=1, sticky=E, pady=4) Label(root, text="Age").grid(row=2, sticky=W, padx=4) age = Entry(root, width=50, textvariable=age).grid(row=2, column=1, sticky=E, pady=4) Label(root, text="Year Group").grid(row=3, sticky=W, padx=4) yearGruop = Entry(root, width=50, textvariable=yG).grid(row=3, column=1, sticky=E, pady=4) fName_1 = fN.get() returning the value of the StringVar 'fN' and storing it def print_(): print (fName_1) not printing the contents of the first name entry box ## Button(root, text="Create account", command=print_).grid(row=4, column=1) root.mainloop()
tagged with: tkinter
has title: im using .get() to return the value of the entry box named 'fName' and then print it on the click of the button... but its not working
type: Question
has answer: http://stackoverflow.com/a/46754525

http://stackoverflow.com/a/46780299
answers question: http://stackoverflow.com/q/46780221
has comment: http://stackoverflow.com/comment/80558608
has body: Try flattening fields before calling join. my_fields = ','.join([x for f in fields for x in f])
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/80509294
type: Answer
has comment: http://stackoverflow.com/comment/80510041
has comment: http://stackoverflow.com/comment/80509283
has comment: http://stackoverflow.com/comment/80538632
has comment: http://stackoverflow.com/comment/80510084
has comment: http://stackoverflow.com/comment/80523855
accepted answer of: http://stackoverflow.com/q/46780221

http://stackoverflow.com/q/46790905
tagged with: pandas
has comment: http://stackoverflow.com/comment/80528787
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80528351
favorite count: 0
has comment: http://stackoverflow.com/comment/80528875
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80528492
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80528160
score: 1
has title: Repeatedly Change Index in DataFrames In Pandas
has comment: http://stackoverflow.com/comment/80528709
type: Question
has answer: http://stackoverflow.com/a/46790962
has comment: http://stackoverflow.com/comment/80528342
has body: I have 3 dataframes: df1 : ip name df2 : name country df3: country city I have to match them by IP. What is correct way to do this? We match them df1 and df2 and then match result of df1 and df2 with df3 with index change. I think that ist not correct way.

http://stackoverflow.com/q/46841438
upvote count: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/46843747
type: UnansweredQuestion
downvote count: 1
score: -1
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/80630880
has comment: http://stackoverflow.com/comment/80631216
has body: I am working on a project that is going to use tkinter. I was wondering if there was any way to display a different set of widgets based on a radio button selection and it update as soon as it is clicked
favorite count: 0
has title: Display different widgets based on radio button selection
answer count: 1
tagged with: python

http://stackoverflow.com/comment/80509178
comment on: http://stackoverflow.com/q/46781420
has text: @ComplicatedPhenomenon if you have an item in the list and you call `remove` with that item - this code will remove it. I'm not sure I understand what you're asking...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46856649
answer count: 2
has title: List of lists Python. Multiple controls
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/80661826
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80661142
tagged with: list
has body: I have a list of lists. Each element of the list is made in this way [id1, id2, timex, value]. Given two external numbers ex and lx (ex &lt; lx), I want to: 1. Check each element of the list, and see if timex &lt; ex. If I find an element in which timex &lt; ex, then I can end everything. 2. If I don't find it, then I want to make another check, starting for the first element of the list, and see if I can find an element in which ex &lt; timex &lt; lx. 3. If I don't find what said in point 2, I want to make another control and check whether there is an element with timex > lx. What I did is this. But I want to know if there is a better way to do it. f1 = 0 f2 = 0 found = False # 1 count = 0 while (found == False) and (count &lt; len(Listx)): if Listx[count][2] &lt;= ex: print "Found - 1" f1 = Listx[count][0] f2 = Listx[count][1] Listx[count][2] = Listx[count][2] + dx found = True count = count + 1 # 2 count = 0 while (found == False) and (count &lt; len(Listx)): if (Listx[count][2] &gt; ex) and (Listx[count][2] &lt;= lx): print "Found - 2" Listx[count][2] = Listx[count][2] + ex f1 = Listx[count][0] f2 = Listx[count][1] found = True count = count + 1 #3 count = 0 while (found == False) and (count &lt; len(Listx)): if (Listx[count][1] &lt; lx): f1 = Listx[count][0] f2 = Listx[count][1] found = True count = count + 1
has answer: http://stackoverflow.com/a/46856960
linked to: http://stackoverflow.com/q/28035236
type: Question
has answer: http://stackoverflow.com/a/46857146
score: 0

http://stackoverflow.com/comment/80493600
comment on: http://stackoverflow.com/q/46773798
score: 0
has text: Twitter does not allow such parsing. Use twitter api to get whatever you want
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46856809
has body: I'm getting wrong encoded characters when I send utf8 encoded characters from pandas to mysql with latin-1 encoding. This is a sample value I'm getting in mysql: BiquÃ­ni This is my code: df.breakdown_name = df.breakdown_name.str.encode('latin-1') send_data(DB_ENGINE, MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_PORT, MYSQL_DB, MYSQL_TABLE, df) def send_data(db, db_user, db_password, db_host, db_port, db_name, db_table, df): """ Return data 1 """ # print db # print db_user # print db_password # print db_host # print db_port # print db_name # print query[0:20] SQL_ENGINE = '{db}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}?charset={encoding}'.format( db=db, db_user=db_user, db_password=db_password, db_host=db_host, db_port=db_port, db_name=db_name, encoding='latin1', ) engine = create_engine(SQL_ENGINE) df.to_sql(name=db_table,con=engine,schema='xxx',if_exists='append', index=False, chunksize=50)
has comment: http://stackoverflow.com/comment/80661258
tagged with: python
has answer: http://stackoverflow.com/a/46857370
type: AnsweredQuestion
tagged with: mysql
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/80661231
has comment: http://stackoverflow.com/comment/80661288
accepted answer: http://stackoverflow.com/a/46857370
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/80663075
answer count: 1
has title: Wrong encoded characters when I send utf8 encoded characters from pandas to mysql with latin-1 encoding
has comment: http://stackoverflow.com/comment/80661352

http://stackoverflow.com/a/46831277
answers question: http://stackoverflow.com/q/46831150
score: 2
accepted answer of: http://stackoverflow.com/q/46831150
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The problem is that key, details and ctype contain multiple lines and whitespace in the middle of the strings. You need to split those on newline and strip each item. Something like: for piece in key.split('\n'): print(piece.strip()) and repeat for details and ctype.
type: Answer

http://stackoverflow.com/comment/80578487
score: 0
type: Comment
has text: Rather than describing your code, can you please give a representative example? Please see how to create a [Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve).
type: QuestionComment
comment on: http://stackoverflow.com/q/46815591

http://stackoverflow.com/comment/80685373
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46869064
has text: @cᴏʟᴅsᴘᴇᴇᴅ haha , overlook , Let me verify with op

http://stackoverflow.com/comment/80472341
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46751635
has text: Possible duplicate of [When running a pygame script as root, no sound is output?](https://stackoverflow.com/questions/15405082/when-running-a-pygame-script-as-root-no-sound-is-output)
type: Comment

http://stackoverflow.com/q/46807354
favorite count: 0
has answer: http://stackoverflow.com/a/46807741
tagged with: python
tagged with: merge
score: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34989341
accepted answer: http://stackoverflow.com/a/46807741
type: Question
upvote count: 4
has body: I have a pandas df with 2 columns A and B. What I need is a new merged column 'result', in which A is preferred to B. I really thought it would be easy but still no solution. How would you guys do that? Thanks for your help. A B result go for go go go go go for for for for
tagged with: pandas
has title: Merge 2 columns with priority
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/80709861
type: Comment
comment on: http://stackoverflow.com/a/46881308
has text: This code will fail since you still have `Monkeys` in sentence 1 and `monkey` in the list. `Monkey` needs to be make lowercase.
type: AnswerComment
score: 0

http://stackoverflow.com/q/46822195
has comment: http://stackoverflow.com/comment/80591943
has body: I've opened a webpage in Selenium, I have access it its url and I would like to save it to a .url file. The file will save and if you open it in vim it displays all the contents of the HTML page (using the first implementation below). That said, when I try and open a dialogue box appears with the error "The target "" of this Internet Shortcut is not valid." Is there any way of easily approaching this in Python? Implementation 1: r = requests.get(url, allow_redirects=True) open('google.url', 'wb').write(r.content) Implementation 2: urllib.request.urlretrieve(url, "google.url")
tagged with: selenium
type: Question
tagged with: selenium-firefoxdriver
score: 0
duplicate of: http://stackoverflow.com/q/13332192
has title: How to save webpage to *.url file using Python
has answer: http://stackoverflow.com/a/46823878
answer count: 1
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/13332192
tagged with: selenium-webdriver

http://stackoverflow.com/q/46759206
has answer: http://stackoverflow.com/a/46759417
has answer: http://stackoverflow.com/a/46759443
score: 0
answer count: 2
has body: I hope this question makes sense, I have been literally trying to figure this out for two complete days. I am trying to create a very small script, which I can then convert into a Flask web app, for comparing SPECint processor scores. A bit of background: From specint.org, I can download csv files containing benchmark information about processors and servers they have benchmarked. The idea of my app is to do the following: Ask users for the benchmark they need (cint or rint), the server model, and the processor they're interested in. This must be done twice, for server 1 and server 2 so I can compare them. I need to check that the information they are entering is correct, i.e. if someone enters as processor name XYZ it should raise an error and prompt for entering a valid query. For this, I'm planning to dump a version of the whole database into my own database, so I can perform the check before actually downloading the csv file from the server. If the information entered is valid, I would dynamically generate the correct url for downloading and reading the csv file containing the benchmark score information, directly from SPECint's server. Once I have downloaded and processed the information for both servers, I would apply some simple math and return the results saying something like this: "Server 1 is 10% faster/slower than server 2", or something like that. As you probably imagine, this will require a lot of duplicated code, so it seems it's the perfect use-case for a class. I have been performing some tests, and the results are promising. However, my issue is that I have not been able to figure out how to capture the user inputs, test the inputs, download the corresponding csv file, and pass the user inputs all on a per-instance fashion, without having to duplicate code somewhere. I have been searching and searching, and it seems a @classmethod is what I need, but I'm not sure since the use of it still seems quite esoteric to me (I'm a newbie) (ref: Example of C…
tagged with: python
tagged with: python-3.x
has title: Input, test, and output per instance in Python
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/32721580

http://stackoverflow.com/comment/80500631
score: 0
type: Comment
has text: According to this error, it seems `JudgeList1` did not exist before you passed it to the function. Do take a look at your code, it seems unrelated to this function :-)
comment on: http://stackoverflow.com/a/46777171
type: AnswerComment

http://stackoverflow.com/comment/80635151
score: 0
type: AnswerComment
type: Comment
has text: "it still doesn't updates the json file" , something gets written to the file right? Could you paste the content which is getting written?
comment on: http://stackoverflow.com/a/46843735

http://stackoverflow.com/a/51219787
has comment: http://stackoverflow.com/comment/109838414
type: Answer
has body: try PIL from PIL import Image def gen_frame(path): im = Image.open(path) alpha = im.getchannel('A') # Convert the image into P mode but only use 255 colors in the palette out of 256 im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255) # Set all pixel values below 128 to 255 , and the rest to 0 mask = Image.eval(alpha, lambda a: 255 if a &lt;=128 else 0) # Paste the color of index 255 and use alpha as a mask im.paste(255, mask) # The transparency index is 255 im.info['transparency'] = 255 return im im1 = gen_frame('frame1.png') im2 = gen_frame('frame2.png') im1.save('GIF.gif', save_all=True, append_images=[im2], loop=5, duration=200)
has comment: http://stackoverflow.com/comment/89852032
has comment: http://stackoverflow.com/comment/105606371
upvote count: 13
score: 13
has comment: http://stackoverflow.com/comment/98198727
accepted answer of: http://stackoverflow.com/q/46850318
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46850318

http://stackoverflow.com/comment/101370425
comment on: http://stackoverflow.com/a/46752630
score: 0
type: AnswerComment
type: Comment
has text: Why does this solve the issue? You shouldn't need administrator access to perform this installation. This is handled by the application, not the OS. For example, you don't need administrator access to install a Firefox extension, which is similar to a library of new features.

http://stackoverflow.com/comment/80530716
type: AnswerComment
type: Comment
has text: Good deal. I have found several user-interface elements that the guys around me (programming in labview) have that I don't, so that is the partial root of some of the elements in there. If you come up with a better background pic, add it and do a pull request! There is no reason that the user shouldn't be able to specify the background that they want.
comment on: http://stackoverflow.com/a/46791089
score: 1

http://stackoverflow.com/comment/80752471
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46901612
type: AnswerComment
has text: It works when I write rules in function, but when I ask user like `char = input("What character do you want to put?") rules = input("Put your rule") inst = lsystems.applyRules(char, [rules]) print(inst)` It looks like it is not working. How users are supposed to put rules through Python Shell?

http://stackoverflow.com/a/46895426
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80755084
answers question: http://stackoverflow.com/q/46895043
type: Answer
has body: Which version of Selenium/Geckodriver/Browser are you using? Anyway, do you set the executable_path: driver = webdriver.Firefox(executable_path=r'pathTo/geckodriver') ? EDIT If you are using: Selenium version = 3.6.0 Geckodriver version = 0.19.0 Firefox version = 52.4.0 Your problem is Firefox. From GeckoDriver releases, is recommended Firefox 55.0 (and greater).
has comment: http://stackoverflow.com/comment/80761261
score: 1

http://stackoverflow.com/a/61241216
type: Answer
has body: This site lists some libraries and ideas that can be used for OCR in python. According to it and to my knowledge, besides Tesseract, the other possibilty would be Cuneiform.
has comment: http://stackoverflow.com/comment/108387576
upvote count: 1
answers question: http://stackoverflow.com/q/46881346
downvote count: 0
score: 1

http://stackoverflow.com/comment/80791167
type: AnswerComment
has text: getting following error, can you please advice on what this error means. print(nm+':', " ".join(x for k in keys for x in by_key[k])) TypeError: sequence item 0: expected str instance, tuple found
type: Comment
comment on: http://stackoverflow.com/a/46903488
score: 0

http://stackoverflow.com/comment/80693746
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46872678
has text: I think your second example doesn't give `108`...
score: 0

http://stackoverflow.com/q/46770088
tagged with: multilabel-classification
score: 7
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/46770439
has body: I am a newbie to machine learning. I have been struggling with a problem for a few weeks now and I hope someone can help here: I have a data set with one continuous variable and the rest are categorical. I managed to encode the categorical variables and would like to build a multi output classifier. Here is my data set: Snapshot of my data set I have these features : A, B I would like to predict : C,D,E,F, G The data set looks like this: A,B,C,D,E,F,G I spent days on the documentation on multi-output classifiers on the scikitlearn and here but none of the documentation seems clear to me. Can anyone please point me in the right direction to find some sample code on how to create the classifier and predict with some sample data? Thank you in advance P.S: I am not using TensorFlow and would appreciate your help for sklearn.
downvote count: 0
tagged with: data-science
has title: multioutput classifier/learning 5 target variables
answer count: 1
tagged with: scikit-learn
favorite count: 0
linked to: http://stackoverflow.com/q/28334091
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/q/46796663
has comment: http://stackoverflow.com/comment/80570128
tagged with: replace
tagged with: search
has comment: http://stackoverflow.com/comment/80570564
has comment: http://stackoverflow.com/comment/80568841
has comment: http://stackoverflow.com/comment/80574124
has comment: http://stackoverflow.com/comment/80559850
has comment: http://stackoverflow.com/comment/80562513
has body: I sequence headers in one file (e.g., 'file1.fasta') that need to change to the corresponding headers from another file (e.g., 'file2.fasta'). Notes: 1) Even though file1.fasta has some sequences reverse complemented from file2.fasta, I want to leave the sequences unmodified. 2) The file1.fasta sequences came from different sources, which means the headers display various formats; I'm targeting just a couple formats for modification. Here is example of file2.fasta headers: &gt;OFAS009268-RA-EXON07 |design:coreoidea-v1,designer:forthman,probes-locus:OFAS009268-RA-EXON07,probes-probe:,probes-source:Clavigralla_tomentosicollis_gi_512427643_gb_GAJX01006991.1 CATTGCAGCAACTAACAGAGTTGATATATTAGATCCAGCCCTTCTCCGATCAGGCAGGCTAGACAGAAAAATTGAATTTCCTCATCCAAATGAAGATGCCCGTGCTCGAATTATGCAAAT &gt;OFAS016134-RA-EXON02 |design:coreoidea-v1,designer:forthman,probes-locus:OFAS016134-RA-EXON02,probes-probe:,probes-source:Anasa_tristis_comp3229_c0_seq1 AGGGCTTGTGATTCCCTTGAGCACATCGCAAGCCTCTGTTCTAGACAAAACATTCCACATTTGGTCAATAATGCTTTTGGTTTGCAAAGTGCACGTCTCATGCATTTAATTCAAGAGGCT Example of all the various header formats in file1.fasta (those targeted for modification are the first two headers): &gt;Clavigralla_tomentosicollis_gi_512427643_gb_GAJX01006991.1_103_rc CATTGCAGCAACTAACAGAGTTGATATATTAGATCCAGCCCTTCTCCGATCAGGCAGGCTAGACAGAAAAATTGAATTTCCTCATCCAAATGAAGATGCCCGTGCTCGAATTATGCAAAT &gt;Anasa_tristis_comp3229_c0_seq1_0_rc AGGGCTTGTGATTCCCTTGAGCACATCGCAAGCCTCTGTTCTAGACAAAACATTCCACATTTGGTCAATAATGCTTTTGGTTTGCAAAGTGCACGTCTCATGCATTTAATTCAAGAGGCT &gt;ENSOFAS009761_p2 |design:coreoidea-v1,designer:forthman,probes-locus:ENSOFAS009761,probes-probe:2,probes-source:Anoplocnemis_curvipes_contig5129 TTAAGAATCTCGAGAAAACCCCTCAGGATGATGAATTACTTGAAATATATGCTCTCTATAAACAAGCAACTGTAGGAGACTGTGACACAAGTAAGCCTGGGATGTTTGATTTCAAAGGGA1 &gt;uce-3225_p7 |design:hemiptera-v1,designer:faircloth,probes-locus:uce-3225,probes-probe:7,probes-source:halhal1,probes-global-chromo:Scaffold629,probes-global-start:410155,probes-global-end:4102…
has comment: http://stackoverflow.com/comment/80573794
has comment: http://stackoverflow.com/comment/80569756
has comment: http://stackoverflow.com/comment/80570436
type: Question
has comment: http://stackoverflow.com/comment/80570219
has answer: http://stackoverflow.com/a/46814162
tagged with: python
has title: Replacing text in one file with text from another file
answer count: 1
has comment: http://stackoverflow.com/comment/80569305
score: 0
has comment: http://stackoverflow.com/comment/80574036
has comment: http://stackoverflow.com/comment/80540271
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80545997

http://stackoverflow.com/comment/80593472
score: 0
has text: it seems to python dictionary not a list
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46822985

http://stackoverflow.com/q/46750552
score: 1
has body: I have a table with multiple rows, each of which has an 'edit' button. On clicking this button, the user should redirect to a form with his details already prefilled. Now, I have defined data attributes inside the 'edit' button's definition: edit Using JQuery, I'm deriving the value of the 'email' data attribute and passing it in a POST request to /add-edit-user, which is also mapped to the page which has my form: $( ".edit-user" ).click(function() { var url = base_url + '/add-edit-user/'; var data = { 'email': $(this).data('email'), 'csrfmiddlewaretoken': csrftoken, }; // $.post(url, data); $.post(url, data).done(function(result) { console.log(result); }).fail(function(error) { console.log(error); }); }); The /add-edit-user URL maps to the following view where I'm trying to define my form object and pass on as a context variable to my template file: def add_edit_users(request): form = AddUpdateForm(request.POST or None) data = {'form': form} return render(request, 'add_edit_users.html', data) Now, my assumption was that if the user clicks on the 'edit' button, I'd set the 'email' parameter in a data attribute and pass it on in my POST request to /add-edit-user URL, after which I'll render my form template with the form object as a context variable which will display the form with email field already prefilled. However, on clicking of the edit link, the page is not redirected to the form page, but I do get the entire form page's HTML in my response. How can I redirect the flow to my form's template so that my input fields are prefilled from the POST variables?
upvote count: 1
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/80448787
has answer: http://stackoverflow.com/a/46751584
accepted answer: http://stackoverflow.com/a/46751584
tagged with: python-2.7
answer count: 1
downvote count: 0
tagged with: jquery
favorite count: 0
has comment: http://stackoverflow.com/comment/80448445
tagged with: django
tagged with: python
has title: Django: Returning a template with POST parameters
has comment: http://stackoverflow.com/comment/80449029
type: AnsweredQuestion

http://stackoverflow.com/a/46876711
has body: With difflib.unified_diff() function: import difflib, itertools s1 = "catwalksonterrace9_ontheweekend_at7am" s2 = "catwalksonterrace$no_ontheweekend_at.*" result = [] for i in itertools.islice(difflib.unified_diff(s1, s2, lineterm=''), 2, None): if i.startswith('@@'): # diff control line result.append(['','']) elif i.startswith('-'): # line unique to sequence 1 result[-1][0] += i[1:] elif i.startswith('+'): # line unique to sequence 2 result[-1][1] += i[1:] print(result) The output: [['9', '$no'], ['7am', '.*']] Each sublist in the resulting result list contains a pair of "old" and "new" value (i.e. [&lt;old&gt;, &lt;new&gt;])
answers question: http://stackoverflow.com/q/46876043
score: 0
type: Answer

http://stackoverflow.com/a/46798756
has body: Assuming import numpy a = numpy.array([[0, 1, 2, 3, 1], [0, 2, 2, 1, 0], [0, 4, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 4, 5]]) then b = a == a[0,:] # compares first row with all others using broadcasting # b: array([[ True, True, True, True, True], # [ True, False, True, False, False], # [ True, False, True, True, False], # [ True, True, True, True, False], # [ True, True, True, False, False]], dtype=bool) using all along the rows acts as a row-wise and operation (thanks Divakar!): c = b.all(axis=0) # c: array([ True, False, True, False, False], dtype=bool) which you can use for boolean indexing a[:, ~c] Out: array([[1, 3, 1], [2, 1, 0], [4, 3, 4], [1, 3, 4], [1, 4, 5]]) As an ugly oneliner: a[:, ~(a == a[0,:]).all(0)]
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80544577
answers question: http://stackoverflow.com/q/46798156
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/80544433

http://stackoverflow.com/comment/80703169
has text: Thank you for your help, but in Python 3 raises the TypeError error: 'zip' object is not a sub script. Can you tell me how to fix this code?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46797395
type: Comment

python-asyncio
tags question: http://stackoverflow.com/q/46895592
tags question: http://stackoverflow.com/q/46865451
tags question: http://stackoverflow.com/q/46757264
tags question: http://stackoverflow.com/q/46890646
tags question: http://stackoverflow.com/q/46789093
tags question: http://stackoverflow.com/q/46867308
tags question: http://stackoverflow.com/q/46791869
tags question: http://stackoverflow.com/q/46785931
tags question: http://stackoverflow.com/q/46785274
tags question: http://stackoverflow.com/q/46827007
tags question: http://stackoverflow.com/q/46772403
tags question: http://stackoverflow.com/q/46805399
tags question: http://stackoverflow.com/q/46827888
tags question: http://stackoverflow.com/q/46778936
tags question: http://stackoverflow.com/q/46806174
tags question: http://stackoverflow.com/q/46815141
tag name: python-asyncio
type: Tag

http://stackoverflow.com/comment/80587670
type: Comment
comment on: http://stackoverflow.com/q/46820068
score: 2
has text: `pd.concat([df1, df2], 1)`
type: QuestionComment

http://stackoverflow.com/comment/80458367
type: QuestionComment
comment on: http://stackoverflow.com/q/46756237
type: Comment
score: 2
has text: But returning a string is what serialisation **is**. If you just want a queryset, why pass it to a serialiser at all?

http://stackoverflow.com/q/46796886
possible better answer: http://stackoverflow.com/a/46796961
downvote count: 0
tagged with: pandas
score: 2
accepted answer: http://stackoverflow.com/a/46797005
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46797024
tagged with: python
tagged with: merge
has body: I have two pandas dataframes that I would like to merge/join together For example: #required packages import os import pandas as pd import numpy as np import datetime as dt # create sample time series dates1 = pd.date_range('1/1/2000', periods=4, freq='10min') dates2 = dates1 column_names = ['A','B','C'] df1 = pd.DataFrame(np.random.randn(4, 3), index=dates1, columns=column_names) df2 = pd.DataFrame(np.random.randn(4, 3), index=dates2, columns=column_names) df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=('_x', '_y')) From here I would like to merge the two datasets in the following manner(Note the order of columns): A_x A_y B_x B_y C_x C_y 2000-01-01 00:00:00 2000-01-01 00:00:00 -0.572616 -0.867554 -0.382594 1.866238 -0.756318 0.564087 2000-01-01 00:10:00 2000-01-01 00:10:00 -0.814776 -0.458378 1.011491 0.196498 -0.523433 -0.296989 2000-01-01 00:20:00 2000-01-01 00:20:00 -0.617766 0.081141 1.405145 -1.183592 0.400720 -0.872507 2000-01-01 00:30:00 2000-01-01 00:30:00 1.083721 0.137422 -1.013840 -1.610531 -1.258841 0.142301 I would like to preserve both dataframe indexes by either creating a multi-index dataframe or creating a column for the second index. Would it be easier to use merge_ordered instead of merge or join? Any help is appreciated.
has title: Merge two pandas dataframes with timeseries index
tagged with: join
has answer: http://stackoverflow.com/a/46796961
answer count: 3
has answer: http://stackoverflow.com/a/46797005

http://stackoverflow.com/a/46826733
upvote count: 0
accepted answer of: http://stackoverflow.com/q/46826539
answers question: http://stackoverflow.com/q/46826539
type: AcceptedAnswer
score: -1
has comment: http://stackoverflow.com/comment/80605470
has body: You can use a regular expression to remove quotes: import re alist = ["py'VV'1.File.md", "py'VV'3.Database.md", "py'Pass'Projects.md", "py'VX'2.Input.md"] pattern = r'\'(.*?)\'' blist = [re.sub(pattern, lambda x : x.group(1), s) for s in alist] print(blist)
downvote count: 1
type: Answer

http://stackoverflow.com/q/46848323
tagged with: scrapy
has answer: http://stackoverflow.com/a/46848585
upvote count: 5
has comment: http://stackoverflow.com/comment/80644207
has answer: http://stackoverflow.com/a/46950753
answer count: 6
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80643942
score: 5
has answer: http://stackoverflow.com/a/46904608
tagged with: python
has comment: http://stackoverflow.com/comment/80719371
has body: I want to get the max historical price data with scrapy from yahoo finance. Here is url of fb(facebook) max historical price data. https://query1.finance.yahoo.com/v7/finance/download/FNMA?period1=221115600&amp;period2=1508472000&amp;interval=1d&amp;events=history&amp;crumb=1qRuQKELxmM In order to write a stock price web crawler ,two problems i can't solve. 1.How to get the argument period1 ? You can get it by hand in the web page,just to click max. How to get the argument with python codes? Different stock has the different period1 value. 2.How to create the argument crumb=1qRuQKELxmM automatically ,different stocks with different crumb value? Here is my stock max historical data with scrapy framework. import scrapy class TestSpider(scrapy.Spider): name = "quotes" allowed_domains = ["finance.yahoo.com"] def __init__(self, *args, **kw): self.timeout = 10 def start_requests(self): stockName = get-it and ommit the codes for stock in stockName: period1 = how to fill it crumb = how to fill it per_stock_max_data = "https://query1.finance.yahoo.com/v7/finance\ download/"+stock+"?period1="+period1+"&amp;period2=1508472000&amp;\ interval=1d&amp;events=history&amp;"+"crumb="crumb yield scrapy.Request(per_stock_max_data,callback=self.parse) def parse(self, response): content = response.body target = response.url #do something How to fill the blank above in my web scrawler framework?
tagged with: yahoo-finance
has title: How to get the max historical price data from yahoo finance?
linked to: http://stackoverflow.com/q/19330327
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51599366
has answer: http://stackoverflow.com/a/46894740
has answer: http://stackoverflow.com/a/75291701

http://stackoverflow.com/q/46861214
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/46861240
has comment: http://stackoverflow.com/comment/80670958
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/80670757
favorite count: 0
has comment: http://stackoverflow.com/comment/80670543
has body: The same question holds for column names such as 'C.1'... Is there a short cut like df.A for column names 'B 1' and 'C 1' other than df['B 1'] and df['C.1'] ?
has comment: http://stackoverflow.com/comment/80670977
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46861240
type: AnsweredQuestion
score: 1
has title: Pandas df 'A' and 'B 1' are column name. How do I reference 'B 1' like df.A ?

http://stackoverflow.com/q/46862842
answer count: 1
tagged with: ssl
favorite count: 0
has title: Python search via google module gives SSL: CERTIFICATE_VERIFY_FAILED Error
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: i'm using Python 3 on Mac OSX. python3 -version gives: Python 3.6.3 I installed the certifi package already. python 3 -m pip install certifi gives back: Requirement already satisfied: certifi in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages When run this Code: from google import search for url in search('Hallo', tld='com', lang='en', num=1, stop=1): print(url) It results in: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 814, in __init__ self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1068, in do_handshake self._sslobj.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 689, in d…
score: 2
has comment: http://stackoverflow.com/comment/80754977
type: Question
has answer: http://stackoverflow.com/a/56549510
downvote count: 0

http://stackoverflow.com/q/46873846
has answer: http://stackoverflow.com/a/46873991
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80694739
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46873991
score: 1
favorite count: 0
has title: How to implement a (more complex) R plyr chain in python?
type: Question
tagged with: pandas
has body: I've been trying to implement the following plyr chain in python: # Data data_L1 X Y r2 contact_id acknowledge_issues a c 100 xyzx 0 b d 100 fsdjkfl 0 a c 80 ejrkl 20 b d 60 fdsdl 40 b d 80 gsdkf 20 # Transformation test &lt;- ddply(data_L1, .(X,Y), summarize, avg_r2 = mean(r2), tickets = length(unique(contact_id)), er_ai =length(acknowledge_issues[which(acknowledge_issues&gt;0)])/length(acknowledge_issues) ) # Output test X Y avg_r2 tickets er_ai a c 90 2 0.5 b d 80 3 0.6667 However I only came this far in python: test = data_L1.groupby(['X','Y']).agg({'r2': 'mean', 'contact_id' : 'count'}) I can't figure out how to create the variables er_ai in Python. Do you have suggestions for solutions in pandas or other libraries?
has comment: http://stackoverflow.com/comment/80694792
tagged with: python
has comment: http://stackoverflow.com/comment/80694900
upvote count: 2

http://stackoverflow.com/a/46797769
answers question: http://stackoverflow.com/q/46796574
downvote count: 0
score: 2
has body: query can be very picky in terms of syntax. The short answer here is that any column name that you couldn't reference in "attribute style" (name_of_dataframe.column_name), you also can't reference in query. In this case, df.Location ID would be invalid. As an alternative, just use boolean filtering: df[df['Location ID'] == 129]
upvote count: 2
type: Answer

http://stackoverflow.com/q/46763148
favorite count: 0
has title: How to create secrets using Kubernetes Python client?
has body: I have been trying to play around with creating secrets for Kubernetes cluster using the python client. I keep getting an error that says Traceback (most recent call last): File "create_secrets.py", line 19, in &lt;module&gt; api_response = v1.create_namespaced_secret(namespace, body) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/apis/core_v1_api.py", line 7271, in create_namespaced_secret (data) = self.create_namespaced_secret_with_http_info(namespace, body, **kwargs) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/apis/core_v1_api.py", line 7361, in create_namespaced_secret_with_http_info collection_formats=collection_formats) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/api_client.py", line 335, in call_api _preload_content, _request_timeout) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/api_client.py", line 148, in __call_api _request_timeout=_request_timeout) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/api_client.py", line 393, in request body=body) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/rest.py", line 287, in POST body=body) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/rest.py", line 240, in request raise ApiException(http_resp=r) kubernetes.client.rest.ApiException: (400) Reason: Bad Request HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json', 'Date': 'Mon, 16 Oct 2017 04:17:35 GMT', 'Content-Length': '234'}) HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"none in version \"v1\" cannot be handled as a Secret: no kind \"none\" is registered for version \"v1\"","reason":"BadRequest","code":400} This is my code that I am trying to execute to create a secret. from __future__ import print_function import time import kubernetes.client from pprint import pprint from kubernetes import client, config config.load_kube_config() v1 = client.CoreV1Api() namespace = 'kube-sys…
tagged with: kubernetes
tagged with: python
accepted answer: http://stackoverflow.com/a/46765771
type: Question
tagged with: kubernetes-python-client
type: AnsweredQuestion
tagged with: openapi
tagged with: http://stackoverflow.com/tag/json
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/46765771
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/80575628
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46814037
has text: I think you need `cumcount()` but sample data needed

http://stackoverflow.com/comment/80573333
has text: `(?P<request>GET(?=\s))|\/v1\/(?P<resource>[^?\s]*)|from=(?P<from>[^&\s]*)|to=(?P<to>[^&\s]*)`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46812957
type: QuestionComment

http://stackoverflow.com/comment/80459183
comment on: http://stackoverflow.com/q/46756034
score: 0
type: Comment
type: QuestionComment
has text: Maybe have a third module that imports from the other two.

http://stackoverflow.com/a/46823775
has body: I think the way you are passing your argument is wrong, try passing it in the same pattern as its in csv. Like ["1/10/2011"], it should work. Good luck :)
type: Answer
answers question: http://stackoverflow.com/q/46823445
score: 0

http://stackoverflow.com/comment/80727827
comment on: http://stackoverflow.com/q/46890325
has text: Btw, I am still amazed how sub-optimal the python package repo remains after all this years. Wasn't this supposed to be replace by something called warehouse a year ago or so?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80590847
has text: Hi @Rawing, I was referring to a pop up such as the following image: https://learn.microsoft.com/en-us/windows/uwp/files/images/picker-multifile-600px.png
type: QuestionComment
comment on: http://stackoverflow.com/q/46803803
score: 0
type: Comment

http://stackoverflow.com/comment/80468026
comment on: http://stackoverflow.com/a/46760826
type: AnswerComment
score: 0
has text: Thanks that worked, I should have been more specific I want to add 11 is that even possible? So like 100,111,122,133,144,155,etc. I removes the i*input to i+input and it only goes up by one. And would it be possible to add to the end of that to so like 100987,111987,122987,133987,144987 155987. My original thought was to try and whip something up in crunch.
type: Comment

http://stackoverflow.com/a/64841685
upvote count: 13
type: Answer
has comment: http://stackoverflow.com/comment/122128575
downvote count: 0
score: 13
answers question: http://stackoverflow.com/q/46890972
has body: The accepted answer does not make changes the index name. If you only want to alter the order of rows you should use dataframe.reindex(arraylike). Notice that the index has changed.

http://stackoverflow.com/a/46857333
score: -1
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/46857132
has body: Your code works fine. Result of the integration is non-convergent integral. You could print it in more beautiful form (in jupyter) with following code import sympy as sp sp.init_printing(wrap_line=False, no_global=True) a = sp.Symbol('a') Ωm = 0.31 Ωr = 9*(10**(-5)) ΩΛ = 0.69 Ω0 = Ωm + Ωr + ΩΛ I = sp.integrate(((Ωm*a**(-1)) + (Ωr*a**(-2)) + (ΩΛ*a**(2)) + (1-Ω0))**(-0.5),a) I results ￼

http://stackoverflow.com/comment/80613052
type: Comment
type: QuestionComment
score: 0
has text: Also: several people have written answers to the effect that you should properly indent your code. If your original code was properly indented, please updated the question. That isn't an edit someone else can really make for you
comment on: http://stackoverflow.com/q/46832120

http://stackoverflow.com/comment/80584340
type: AnswerComment
comment on: http://stackoverflow.com/a/46818167
score: 0
type: Comment
has text: Yup, turns out I was accidentally using python2. I'm using atom text editor to code it, and a package so I can run the code by pressing f5. I thought that was running it using python 3, but its using python 2 so that's my answer. Thank you

http://stackoverflow.com/comment/80737314
score: 0
type: AnswerComment
has text: After a bunch of snooping around with importlib, I came to the conclusion that this is the best way I could approach this even if it's not the most convenient since it does not account for package modules.
type: Comment
comment on: http://stackoverflow.com/a/46852679

dst
tags question: http://stackoverflow.com/q/46834202
tag name: dst
type: Tag

http://stackoverflow.com/q/46880764
type: Question
has answer: http://stackoverflow.com/a/46880791
has title: UnboundLocalError: local variable 'truebomb' referenced before assignment
score: 0
answer count: 2
has body: I have some code where I am getting the error: UnboundLocalError: local variable 'truebomb' referenced before assignment. In my code i have a variable b. Each time the code runs through, I add 1 to b.b is originally 1, and according to my code it will satisfy the equation. import random b=1 game=True while game: if b==1: bomb=random.randint(1,9) if bomb== '8': truebomb=True if truebomb: game=False b=b+1 quit()
tagged with: python
has answer: http://stackoverflow.com/a/46880793
type: UnansweredQuestion

http://stackoverflow.com/q/46847803
linked to: http://stackoverflow.com/q/419163
score: 6
type: Question
has body: I'm a Python beginner, and have made a few basic scripts. My latest challenge is to take a very large csv file (10gb+) and split it into a number of smaller files, based on the value of a particular variable in each row. For example, the file may look like this: Category,Title,Sales "Books","Harry Potter",1441556 "Books","Lord of the Rings",14251154 "Series", "Breaking Bad",6246234 "Books","The Alchemist",12562166 "Movie","Inception",1573437 And I would want to split the file into separate files: Books.csv, Series.csv, Movie.csv In reality there will be hundreds of categories, and they will not be sorted. In this case they are in the first column but in future they may not be. I've found a few solutions online but nothing in Python. There is a really simple AWK command that can do this in one line, but I cannot get access to AWK in work. I've written the following code which works, but I think it is probably very inefficient. Can anybody suggest how to speed it up? import csv #Creates empty set - this will be used to store the values that have already been used filelist = set() #Opens the large csv file in "read" mode with open('//directory/largefile', 'r') as csvfile: #Read the first row of the large file and store the whole row as a string (headerstring) read_rows = csv.reader(csvfile) headerrow = next(read_rows) headerstring=','.join(headerrow) for row in read_rows: #Store the whole row as a string (rowstring) rowstring=','.join(row) #Defines filename as the first entry in the row - This could be made dynamic so that the user inputs a column name to use filename = (row[0]) #This basically makes sure it is not looking at the header row. if filename != "Category": #If the filename is not in the filelist set, add it to the list and create new csv file with header row. if filename not in filelist: filelist.add(filename) with open('//directory/subfiles/' +str(filename)+'.csv','a') as f: f.write(headerstring) f.write("\n") f.write(rowstring) f.write("\n") f.close() #If…
has title: Splitting csv file based on a particular column using Python
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/71012346
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/58267676
tagged with: python
has answer: http://stackoverflow.com/a/46848269
upvote count: 6
has comment: http://stackoverflow.com/comment/80643339

http://stackoverflow.com/a/46773859
has comment: http://stackoverflow.com/comment/80518754
has comment: http://stackoverflow.com/comment/80519668
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/46770697
has body: As you mentioned send_keys("TEST") are not working, there are a couple of alternatives to send a character sequence to respective fields as mentioned below : Use Keys.NUMPAD3 [simulating send_keys("3")]: login.send_keys(Keys.NUMPAD3) Use JavascriptExecutor with getElementById : self.driver.execute_script("document.getElementById('login_email').value='12345'") Use JavascriptExecutor with getElementsById : self.driver.execute_script("document.getElementsById('login_password')[0].value='password'") Now comming to your specific issue, as you mentioned I tried to use clear() or click() before sendkeys but nothing works correctly, so we will take help of javascript to click() on the text area to clear the predefined text and then use send_keys to populate the text field as follows: self.driver.execute_script("document.getElementById('manage_description').click()") self.driver.find_element_by_id('manage_description').send_keys("TEST") Update : As you mentioned sometimes it works sometimes not, so I would suggest the following: Induce ExplicitWait for textarea to be clickable. Use javascript to send the text within the textarea too. Your code will look like: my_string = "TEST"; elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "manage_description"))) self.driver.execute_script("document.getElementById('manage_description').click()") self.driver.execute_script("arguments[0].setAttribute('value', '" + my_string +"')", elem);
answers question: http://stackoverflow.com/q/46770697
has comment: http://stackoverflow.com/comment/80515049
has comment: http://stackoverflow.com/comment/80515994

http://stackoverflow.com/comment/80568921
has text: If you are inspecting the table by opening it in SQL Server Management Studio (SSMS) then it may be deceiving you. SSMS does not display line breaks in a standard Grid View. You can use `CONVERT(VARBINARY, address1)` to see if the value contains `0D0A` (for VARCHAR) or `0D000A00` (for NVARCHAR) to verify that the CR_LF line breaks really are there.
comment on: http://stackoverflow.com/q/46801333
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/46808438
linked to: http://stackoverflow.com/q/3996904
has title: TypeError: randint() takes 3 positional arguments but 4 were given
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80564179
tagged with: random
has comment: http://stackoverflow.com/comment/80564307
score: 1
has body: I am writing a rock, paper and scissors bot for a school project. I keep getting the error in the title (TypeError: randint() takes 3 positional arguments but 4 were given) and I don't know why. My code is below. if userInput : 'rock' choice = random.randint(1,2,3) if choice == 1: await client.send_message(message.channel, embed=RockEmbed) elif choice == 2: await client.send_message(message.channel, embed=PaperEmbed) elif choice == 3: await client.send_message(message.channel, embed=ScissorsEmbed) if userInput : 'scissors' choice2 = random.randint(1,2,3) if choice2 == 1: await client.send_message(message.channel, embed=RockEmbed) elif choice2 == 2: await client.send_message(message.channel, embed=PaperEmbed) elif choice2 == 3: await client.send_message(message.channel, embed=ScissorsEmbed) if userInput : 'paper' choice3 = random.randint(1,2,3) if choice3 == 1: await client.send_message(message.channel, embed=RockEmbed) elif choice3 == 2: await client.send_message(message.channel, embed=PaperEmbed) elif choice3 == 3: await client.send_message(message.channel, embed=ScissorsEmbed) I've said random.randint(1,2,3), which is clearly 3 arguments, not 4. I'm, pretty sure my syntax is correct, but not 100%.
answer count: 3
has comment: http://stackoverflow.com/comment/80564280
has answer: http://stackoverflow.com/a/46860138
duplicate of: http://stackoverflow.com/q/3996904
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80564239
possible better answer: http://stackoverflow.com/a/66883544
has comment: http://stackoverflow.com/comment/80563875
has answer: http://stackoverflow.com/a/66883544
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74045495
accepted answer: http://stackoverflow.com/a/46860138
duplicate of: http://stackoverflow.com/q/306400
downvote count: 3
duplicate of: http://stackoverflow.com/q/23944657

http://stackoverflow.com/a/46851907
accepted answer of: http://stackoverflow.com/q/46849831
answers question: http://stackoverflow.com/q/46849831
downvote count: 0
score: 1
has body: @tw-uxtli51nus in the comments is basically correct. We can accomplish what you want by wrapping logical conditions with () and using '|' in place of 'or'. So np.where would look like: df['new_col'] = np.where( ( (df['Exit_Page'].str[:10]=='/store/cat') | (df['Exit_Page'].str[:10]=='/store/pro') ) ,df['Exit_Page'] ,df['Exit_Page'].str[:10]) trying to make it more readable since this stuff is ugly to look at. We can make our lives easier by instead trying a technique similar to what the docs suggest using np.isin(): https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html but I don't have the correct version of numpy to write out a real example, unfortunately.
has comment: http://stackoverflow.com/comment/80652208
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80651834
type: Answer
has comment: http://stackoverflow.com/comment/80651376

http://stackoverflow.com/q/46896024
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46896100
score: 1
has title: Calculate due date in django
linked to: http://stackoverflow.com/q/12649659
type: Question
upvote count: 2
has body: I am creating a "library" website using django. Once a user has issued a book and I want to calculate a due date for it which will 3 months after the issue/present date. How do I do it?
has answer: http://stackoverflow.com/a/46896058
accepted answer: http://stackoverflow.com/a/46896058
answer count: 3
has answer: http://stackoverflow.com/a/46896100
tagged with: datetime
downvote count: 1
has comment: http://stackoverflow.com/comment/80739100
favorite count: 0
has answer: http://stackoverflow.com/a/46896208
tagged with: django
tagged with: python

http://stackoverflow.com/a/46793815
type: AcceptedAnswer
type: Answer
score: 34
answers question: http://stackoverflow.com/q/46793448
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46793448
has body: You can pass in the series' index &amp; values to x &amp; y respectively in sns.barplot. With that the plotting code becomes: sns.barplot(head.index, head.values) I am trying to plot the top 5 category names in X calling category.head(5) will return the first five values from the series category, which may be different than the top 5 based on the number of times each category appears. If you want the 5 most frequent categories, it is necessary to sort the series first &amp; then call head(5). Like this: category = df.category_name_column.value_counts() head = category.sort_values(ascending=False).head(5)
upvote count: 34

http://stackoverflow.com/comment/80546662
comment on: http://stackoverflow.com/q/46799619
score: 0
type: Comment
type: QuestionComment
has text: Don't (try to) use so many global variables. Take the lists to copy as arguments, and return the copies in a tuple (or another list).

http://stackoverflow.com/comment/80598649
type: QuestionComment
comment on: http://stackoverflow.com/q/46825434
score: 0
has text: Ohk its hard to understand what you are trying to convey. Do you want to replace the existing values of certain columns with new values?
type: Comment

http://stackoverflow.com/comment/80534058
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46793573
has text: Currently it looks like no, you'll have to either port 4suite-xml to Python 3.6, or replace its functionality with another package.

http://stackoverflow.com/a/46811270
has comment: http://stackoverflow.com/comment/80574073
type: Answer
has body: Stated, you have a list of replacement instructions in a CSV : 1 A B 2 B C .... If you have a string "AB" and apply search/replace in sequence, your string ends-up being "CC", not "BC". You have two ways to workaround : do all the searches and then all the replaces. It's quite tricky to implement as you have to cut your input string into pieces modify your instructions to introduce key that are not present in the input string: 1 A DISTINGUISH_A 2 B DISTINGUISH_B .... .... 11 DISTINGUISH_A B 12 DISTINGUISH_B C Way 2 is interesting because the main loop does not change : sequence of search and replace. And, preparing modified instructions can be automated too.
answers question: http://stackoverflow.com/q/46810038
has comment: http://stackoverflow.com/comment/80581974
score: 0

http://stackoverflow.com/a/46904751
type: Answer
has body: Assuming you have a file in your current dir, you can get it absolute path (starting at root) with abspath: path = os.path.abspath(filename) Thes the magic word is os.path.split that splits a pathname into the last component and the head (everything in front of it). So to get the absolute path of what comes before d just iterate the components: def findinit(path, comp): while (len(path) &gt; 1): t = os.path.split(path) if t[1] == comp: return t[0] path = t[0] return None You can control that findinit('/a/b/c/d/e/f/x.xml') gives as expected /a/b/c Alternatively if you want to use the pathlib module, you can search the parts for a specific component: def findinit(path, comp): p = pathlib.PurePath(path) i = p.parts.index(comp) if i != -1: return pathlib.PurePath(*p.parts[:i]) return None
score: 0
answers question: http://stackoverflow.com/q/46904428

http://stackoverflow.com/q/46764538
accepted answer: http://stackoverflow.com/a/46764593
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46764593
has body: I'm running Python 2.7 in my Ubuntu 16.0. I have created a folder Scripts &amp; put 2 files, config.py &amp; init.py , inside that folder. Also I have added in updated .bashrc pythonpath using following statement export PYTHONPATH=$PYTHONPATH:path to my script folder But while I'm ruining from Scripts import test I'm getting error message ImportError: No module named 'Scripts' Can you please suggest me the solution?
type: Question
has title: Python Error:No module Name Scripts
score: 0
answer count: 1

http://stackoverflow.com/comment/80718129
type: Comment
comment on: http://stackoverflow.com/q/46882789
score: 0
type: QuestionComment
has text: @Sraw done, comment has been added.

http://stackoverflow.com/q/46831783
has comment: http://stackoverflow.com/comment/80658244
score: 8
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has body: I have a simple integration test in Django that spawns a single Celery worker to run a job, which writes a record to the database. The Django thread also writes a record to the database. Because it's a test, I use the default in-memory sqlite3 database. There are no transactions being used. I often get this error: django.db.utils.OperationalError: database table is locked which according to the Django docs is due to one connection timing out while waiting for another to finish. It's "more concurrency than sqlite can handle in default configuration". This seems strange given that it's two records in two threads. Nevertheless, the same docs say to increase the timeout option to force connections to wait longer. Ok, I change my database settings to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS': {'timeout': 10000000}, } } This has no effect. The error still appears and it clearly has not waited 1e7 seconds or 1e7 milliseconds or 1e7 microseconds before doing so. Is there an additional setting I'm missing? I have tried both Python 3.5 and Python 3.6 and both Django 1.11 and Django 2.0.
upvote count: 8
has title: Django sqlite3 timeout has no effect
type: Question
has answer: http://stackoverflow.com/a/51769065
tagged with: sqlite
has comment: http://stackoverflow.com/comment/80659822
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90454421
has comment: http://stackoverflow.com/comment/87250584
has comment: http://stackoverflow.com/comment/80660019
has comment: http://stackoverflow.com/comment/90496774

http://stackoverflow.com/comment/80702500
score: 0
type: Comment
type: QuestionComment
has text: Yes, I would like to list all the distinct values from category, and let the user filter, whether it's one value or "n" values
comment on: http://stackoverflow.com/q/46877593

http://stackoverflow.com/q/46805903
tagged with: django
tagged with: python
score: 2
upvote count: 2
has title: Using Redshift's native 'AT TIMEZONE' through django query?
type: Question
has answer: http://stackoverflow.com/a/46806158
has body: So I have this query which goes like query = MyModel.objects.filter(some_filter).filter(eventTime__date__gte=start_date).filter(eventTime__date__lte=end_date).... The redshift table I am connecting to has eventTime as UTC. It offers me to query in native SQL like select eventtime AT TIME ZONE 'MST' from mymodel limit 1; How can I use that AT TIME ZONE 'MST' in django query format?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: amazon-redshift
type: UnansweredQuestion

http://stackoverflow.com/q/46782075
has answer: http://stackoverflow.com/a/46782201
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/46782489
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: dataframe
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46782489
has title: cannot re-use pandas generator object
answer count: 2
has body: I have the scenario as below (running tests for performance bench marking): def read_sql_query(query, chunk_size, cnxn): try: df = pd.read_sql_query(query, cnxn, index_col=['product_key'], chunksize=100000) return df except Exception as e: print(e) def return_chunks_in_df(df, start_date, end_date): try: sub_df = pd.DataFrame() for chunks in df: sub_df = pd.concat([sub_df, chunks.loc[(chunks['trans_date'] &gt; start_date) &amp; (chunks['trans_date'] &lt; end_date)]], ignore_index=True) print(sub_df.info()) return sub_df except Exception as e: print(e) query = r"select * from sales_rollup where product_key in (select product_key from temp limit 10000)" start_time = timeit.default_timer() df = read_sql_query(query, 100000, cnxn) print(df) print('time to chunk:' + str(timeit.default_timer() - start_time)) #scenario 1 start_time = timeit.default_timer() sub_df1 = return_chunks_in_df(df, '2015-01-01', '2016-01-01') print('scenario1:' + str(timeit.default_timer() - start_time)) #scenario 2 start_time = timeit.default_timer() sub_df2 = return_chunks_in_df(df, '2016-01-01', '2016-12-31') print('scenario2:' + str(timeit.default_timer() - start_time)) The issue I am having is in scenario 2 where the dataframe always returns 0 rows even though there is data for the filtered date range. I tried looping through the df() but the below loop never runs: for chunks in df: print(chunks.info()) I am only able to get the result set for scenario 2 if I recreate the df again as below just before execution: df = read_sql_query(query, 100000, cnxn) The core issue being the first to execute scenario always returns values the second does not. Does the df object expire somehow after first execution? Any help/pointers highly appreciated.
tagged with: pandas
has comment: http://stackoverflow.com/comment/80510663
possible better answer: http://stackoverflow.com/a/46782201

http://stackoverflow.com/comment/80615480
type: AnswerComment
type: Comment
score: 1
has text: Speaking of hyperparameter optimization, there's an approach I think you should take a look at - https://stackoverflow.com/q/41860817/712995
comment on: http://stackoverflow.com/a/46832956

http://stackoverflow.com/comment/80633286
type: QuestionComment
comment on: http://stackoverflow.com/q/46842732
score: 0
has text: Could you post your code through editing this question?
type: Comment

http://stackoverflow.com/q/46791897
score: -6
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80530572
tagged with: python
has body: Suppose I have the following list: &gt;&gt;&gt; my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] I want to write a function that will iterate over slices of n elements to the left and right of each item of this list: def sliding_window_n_elements_left_and_right(lst, n): ... The function should work like this: &gt;&gt;&gt; list(sliding_window_n_elements_left_and_right(my_list, 0)) [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] &gt;&gt;&gt; list(sliding_window_n_elements_left_and_right(my_list, 1)) [[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]] &gt;&gt;&gt; list(sliding_window_n_elements_left_and_right(my_list, 2)) [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]] Thank you for your time and skill!
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/46792062
type: Question
tagged with: algorithm
has answer: http://stackoverflow.com/a/46792062
tagged with: slice
has comment: http://stackoverflow.com/comment/80533904
has title: Iterate over slices of n elements to the left and right of each item in a list in python
upvote count: 1
linked to: http://stackoverflow.com/q/6822725
downvote count: 7
answer count: 1

http://stackoverflow.com/comment/80541195
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46797221
has text: Agree with @JonClements Regex should be last resort only.

http://stackoverflow.com/comment/80581880
type: QuestionComment
comment on: http://stackoverflow.com/q/46811610
score: 0
type: Comment
has text: @Raf. I have posted an answer with a simple example. There is no need to block signals, but I have added a check to see if the thread is running.

http://stackoverflow.com/comment/80684579
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46868616
has text: The docs explain that this is so you can look for a config file in several different places: https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.read. I guess they probably could throw an exception if nothing was found.
score: 0

http://stackoverflow.com/comment/80518452
type: QuestionComment
comment on: http://stackoverflow.com/q/46785924
has text: @Eldy that's easier to understand that way. `command` is built-in, so `shell=True` is necessary. But what does "command" do?
score: 0
type: Comment

http://stackoverflow.com/q/46844444
has answer: http://stackoverflow.com/a/46844497
tagged with: opencv
has title: Python OpenCV: Cannot resize image
type: AnsweredQuestion
tagged with: image-resizing
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/46844497
tagged with: image
has body: I am using Python 3 and OpenCV 3. I am trying to use the EigenFace Recognizer which uses the same size images for the training and test dataset. I read the image from a webcam and I resize the images to 200 x 200 but it shows an error . This is my code: faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cam=cv2.VideoCapture(0); rec=cv2.face.EigenFaceRecognizer_create() #rec=cv2.face.LBPHFaceRecognizer_create() rec.read("recognizer/EigenData.xml") id=0 fontFace = cv2.FONT_HERSHEY_SIMPLEX fontScale = 1 fontColor = (0, 0, 255) while(True): ret,img=cam.read(); resize_img = img.resize((200,200) , img) gray=cv2.cvtColor(resize_img,cv2.COLOR_BGR2GRAY) faces=faceDetect.detectMultiScale(gray,1.3,5); for(x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w, y+h), (0,255,0) , 2) id, conf=rec.predict(gray[y:y+h, x:x+w]) #EigenFace Predict cv2.putText(img,str(id),(x,y+h), fontFace, fontScale, fontColor,thickness=2) cv2.imshow("Face", img); if(cv2.waitKey(1)==ord('q')): break; cam.release() cv2.destroyAllWindows() The error I get is: resize_img = img.resize((200,200) , img) TypeError: 'tuple' object cannot be interpreted as an integer
type: Question
upvote count: 4
downvote count: 0
answer count: 1
score: 4
favorite count: 0
tagged with: python

http://stackoverflow.com/q/46755639
tagged with: python
tagged with: dictionary
upvote count: 0
has answer: http://stackoverflow.com/a/46755689
score: -1
type: Question
has answer: http://stackoverflow.com/a/46755766
has comment: http://stackoverflow.com/comment/80456780
has title: python loop through a dictionary to see if values exist
has comment: http://stackoverflow.com/comment/80456705
has comment: http://stackoverflow.com/comment/80456614
answer count: 3
has body: I am trying to loop though a python dictionary to see if values that I am getting from a csv file already exist in the dictionary, If the values do not exist I want to add them to the dictionary. then append this to a list. I am getting the error list indices must be integers, not str. example input first name last name john smith john smith example output first_name john last name smith user_list =[] with open(input_path,'rU') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['first_name'] not in user_dictionary['first_name'] and not in row['last_name'] not in user_dictionary['last_name']: user_dictionary = { 'first_name':row['first_name'], 'last_name':row['last_name'] } user_list.append(user_dictionary)
downvote count: 1
has answer: http://stackoverflow.com/a/46755808
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/80694564
comment on: http://stackoverflow.com/q/46867014
score: 0
has text: It is possible to point some one in the right direction without giving them a fully implemented solution , allowing the person asking the question to get some kind of learning experience.As has been done in the accepted answer.You are correct this is a programming site where people who encounter an issue can ask for help. That is inherently different from a do my homework for me site. I will however add python to the tag as suggested
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46859263
type: Answer
answers question: http://stackoverflow.com/q/46859151
upvote count: 1
has body: T + as_matrix df.T.as_matrix() Out[70]: array([[12345, 23456, 12376, 56842, 45678, 78324], [ 10, -15, 10, 25, -5, 20]], dtype=int64)
score: 1
downvote count: 0

http://stackoverflow.com/comment/80614016
type: Comment
type: QuestionComment
has text: Explain the setup a little more. What systems, host information?
score: 0
comment on: http://stackoverflow.com/q/46832162

http://stackoverflow.com/a/47318269
downvote count: 0
has comment: http://stackoverflow.com/comment/81594243
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46856584
answers question: http://stackoverflow.com/q/46856584
has body: I've reproduced your problem and I've found a solution that works on my platform anyhow: Remove the -u flag from your cmd build config option. I'm not 100% sure why that works, but it seems to be a poor interaction resulting from the console interpreting an unbuffered stream of data containing multi-byte characters. Here's what I've found: The -u option switches Python's output to unbuffered This problem is not at all specific to the replacement character. I've gotten similar behaviour with other characters like "あ" (U+3042). Similar bad results happen with other encodings. Setting "env": {"PYTHONIOENCODING": "utf-16be"} results in print u'\u3042' outputting 0B. That last example with the encoding set to UTF-16BE illustrates what I think is going on. The console is receiving one byte at a time because the output is unbuffered. So it receives the 0x30 byte first. The console then determines this is not valid UTF-16BE and decides instead to fallback to ASCII and thus outputs 0. It of courses receives the next byte right after and follows the same logic to output B. With the UTF-8 encoding, the console receives bytes that can't possibly be interpreted as ASCII, so I believe the console is doing a slightly better job at properly interpreting the unbuffered stream, but it is still running into the difficulties that your question points out.
type: AcceptedAnswer

http://stackoverflow.com/comment/80651609
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46851898
score: 0
has text: Please post your code...

http://stackoverflow.com/a/51833702
type: Answer
answers question: http://stackoverflow.com/q/46756718
has body: Input: from io import StringIO import pandas as pd df = pd.read_table(StringIO("""id1 id2 content 20 10 item 1 20 10 item 2 20 10 item 3 30 20 item 4 30 20 item 5 30 20 item 6"""), sep=' ', engine='python') Use pd.merge to (self) join dataframe on id1/id2 and add suffix to common columns: merged_df = pd.merge(df, df, how='inner', left_on='id2', right_on='id1', suffixes=('','_previous')) # Take essential columns merged_df = merged_df'content','content_previous' Groupby content columns, take the count to get number of occurances, rename the "index" column: # Reset index so we have something to count, then group by grouped_df = merged_df.reset_index().groupby(['content','content_previous']).count() # Reset index and change name of column final_df = grouped_df.reset_index().rename(columns={'index':'sum_of_occurances'}) #There may be a better to get unique count across two columns Output: content content_previous sum_of_occurances 0 item 4 item 1 1 1 item 4 item 2 1 2 item 4 item 3 1 3 item 5 item 1 1 4 item 5 item 2 1 5 item 5 item 3 1 6 item 6 item 1 1 7 item 6 item 2 1 8 item 6 item 3 1
score: 0

http://stackoverflow.com/comment/81458158
has text: I tried this but I get the following: error:root@raspberrypi:/home/pi# sudo pip3 install llvmite==0.15.0 Downloading/unpacking llvmite==0.15.0 Could not find any downloads that satisfy the requirement llvmite==0.15.0 Cleaning up... No distributions at all found for llvmite==0.15.0 Storing debug log for failure in /root/.pip/pip.log
comment on: http://stackoverflow.com/a/46840976
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80577255
score: 0
type: AnswerComment
type: Comment
has text: add `label='Year {}'.format(i + 1980)` to the `step` `dict`, see updated answer.
comment on: http://stackoverflow.com/a/46780582

append
tags question: http://stackoverflow.com/q/46781835
tag name: append
tags question: http://stackoverflow.com/q/46763727
tags question: http://stackoverflow.com/q/46848079
tags question: http://stackoverflow.com/q/46833160
tags question: http://stackoverflow.com/q/46758894
tags question: http://stackoverflow.com/q/46759615
type: Tag

http://stackoverflow.com/q/46821171
tagged with: python
has title: Django with Docker Module NOT found Error
has comment: http://stackoverflow.com/comment/90968292
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: django
score: 3
tagged with: docker-compose
tagged with: docker
type: Question
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has body: I am trying to build a Django app with Docker. My application will run on local server however when I try to migrate with docker it throws a Module Not Found Error. This is my requirements.txt djangorestframework==3.7.0 Django==1.11.5 #import_export==0.5.1 django-csvimport==2.2 psycopg2 This is my docker-compose.yml`. docker-compose.yml version: '3' services: web: build: . command: python djangorest/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" This is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ #COPY . /code/ RUN pip install -r requirements.txt ADD . /code/ I am get following error when i pass this cmd docker-compose run web python djangorest/manage.py migrate docker-compose run web python djangorest/manage.py migrate Traceback (most recent call last): File "djangorest/manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 941, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 219, in _…

http://stackoverflow.com/q/46765518
linked to: http://stackoverflow.com/q/46643176
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46767234
tagged with: matplotlib
downvote count: 3
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/46766042
has comment: http://stackoverflow.com/comment/80476336
has title: How can I adjust my plot to make it easier to read?
has answer: http://stackoverflow.com/a/46766042
has comment: http://stackoverflow.com/comment/80476399
score: -2
has body: I am generating a barplot with many elements. As shown below, the plot generated is not very easy to read. How can I adjust it to make it look better and move the columns a bit further? Here is the code. import numpy as np import matplotlib.pyplot as plt def barchart(Gbar, Vbar, Wbar, Rbar, Dbar, Nebar, Tbar, Abar): N = 10 G = Gbar ind = np.arange(N) # the x locations for the groups width = 0.12 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, G, width, color='b') V = Vbar rects2 = ax.bar(ind + width, V, width, color='g') W = Wbar rects3 = ax.bar(ind + width*2, W, width, color='y') R = Rbar rects4 = ax.bar(ind + width*3, R, width, color='r') D = Dbar rects5 = ax.bar(ind + width * 4, D, width, color='orange') N = Nebar rects6 = ax.bar(ind + width * 5, N, width, color='black') T = Tbar rects7 = ax.bar(ind + width * 6, T, width, color='purple') Ab = Abar rects8 = ax.bar(ind + width * 7, Ab, width, color='cyan') # add some text for labels, title and axes ticks ax.set_ylabel('Char edit distance') ax.set_xticks(ind + width/2) ax.set_xticklabels(('A1', 'A2', 'A3', 'A4', 'A5', 'B1', 'B2', 'B3', 'B4', 'C1')) ax.legend((rects1[0], rects2[0], rects3[0], rects4[0], rects5[0],rects6[0],rects7[0],rects8[0]), def autolabel(rects): """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) autolabel(rects3) autolabel(rects4) autolabel(rects5) autolabel(rects6) autolabel(rects7) autolabel(rects8) plt.savefig('plot.png') plt.show() Note: the image attached is part of the entire image but should be more than enough to get an idea about my issue.
tagged with: python-2.7
answer count: 2
accepted answer: http://stackoverflow.com/a/46767234
has comment: http://stackoverflow.com/comment/80476471
favorite count: 0
has comment: http://stackoverflow.com/comment/80476902

http://stackoverflow.com/comment/132907130
has text: This returns `np.recarray`, not a structured `np.ndarray`; I've tested this and converting to `np.ndarray` after the fact; Using `pd.melt(df).to_records(index=False).view(np.ndarray)` doesn't seem to lead to the desired result. `df.to_records(index=False).view(np.ndarray)` seems to work, but seems to yield a slightly different type from the other answers.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46837719
type: AnswerComment

http://stackoverflow.com/comment/80605652
comment on: http://stackoverflow.com/a/46817666
type: Comment
type: AnswerComment
score: 0
has text: The dummy thing was excellent, and maybe the most easy way to do it, imho :) It works now. Thank you !

http://stackoverflow.com/comment/80679338
has text: This counts length of sitemap_urls. I want to get number of urls found in Sitemap. Is it possible?
type: AnswerComment
comment on: http://stackoverflow.com/a/46865576
score: 0
type: Comment

http://stackoverflow.com/comment/80805199
comment on: http://stackoverflow.com/q/46884612
score: 0
type: Comment
type: QuestionComment
has text: I do not know how to check which version I have.

http://stackoverflow.com/comment/80676233
has text: he's not asking about that though. and of course if you create a __new__ method than __init__ will be initialized later
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46864368

http://stackoverflow.com/q/46856453
has title: Matrix of matrices in python
answer count: 1
favorite count: 0
tagged with: matrix
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/53254738
downvote count: 0
has body: Hey so I'm working on this code for a material analysis. I have a matrix generated for each layer of the material and I want to save each of these matrices as their own element. The way I was doing this was by saving it to a dictionary. I then form one matrix by summing all the values of the dictionary. Now I do this for three different conditions which leaves me with 3 matrices: A, B, and D. I want to make a matrix of all of these so that it looks like: | A B | | B D | However I can't get it to print properly as it always says matrix: then one of the matrices such as A. It prints the second matrix, B, on the third line where A ended instead of being next to A. I also need to perform future operations on this massive matrix so I'm wondering what the best way to go about that would be. This is a part of my code: Qbars = {} for i in plies: Qbar11 = Q11 * math.cos(float(thetas[j]))**4 + Q22 *math.sin(float(thetas[j]))**4 + \ 2 * (Q12 + 2 * Q66) * math.sin(float(thetas[j]))**2 * math.cos(float(thetas[j]))**2 Qbar22 = Q11 * math.sin(float(thetas[j]))**4 + Q22 *math.cos(float(thetas[j]))**4 + \ 2 * (Q12 + 2 * Q66) * math.sin(float(thetas[j]))**2 * math.cos(float(thetas[j]))**2 Qbar12 = (Q11 + Q22 - 4 * Q66) * math.sin(float(thetas[j]))**2 * \ math.cos(float(thetas[j]))**2 + Q12 * (math.cos(float(thetas[j]))**4 + \ math.sin(float(thetas[j]))**4) Qbar66 = (Q11 + Q22 - 2 * Q12 - 2 * Q66) * math.sin(float(thetas[j]))**2 * \ math.cos(float(thetas[j])) **2 + Q66 * (math.sin(float(thetas[j]))**4 + \ math.cos(float(thetas[j]))**4) Qbar16 = (Q11 - Q12 - 2 * Q66) * math.cos(float(thetas[j]))**3 * \ math.sin(float(thetas[j])) - (Q22 - Q12 - 2 * Q66) * math.cos(float(thetas[j])) * \ math.sin(float(thetas[j]))**3 Qbar26 = (Q11 - Q12 - 2 * Q66) * math.cos(float(thetas[j])) * \ math.sin(float(thetas[j]))**3 - (Q22 - Q12 - 2 * Q66) * \ math.cos(float(thetas[j]))**3 * math.sin(float(thetas[j])) Qbar = np.matrix ([[Qbar11, Qbar12, Qbar16], [Qbar12, Qbar22, Qbar26], \ [Qbar16, Qbar26, Qbar6…
type: Question
has comment: http://stackoverflow.com/comment/80664847
has answer: http://stackoverflow.com/a/46859218
accepted answer: http://stackoverflow.com/a/46859218
has comment: http://stackoverflow.com/comment/80664782
upvote count: 2
tagged with: numpy
tagged with: python-2.7

http://stackoverflow.com/q/46760895
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/80467246
favorite count: 0
type: UnansweredQuestion
tagged with: io
tagged with: python
has body: I have data in the following format: 1_engineer_grade1 |Boolean IsMale IsNorthAmerican IsFromUSA |Name blah 2_lawyer_grade7 |Boolean IsFemale IsAlive |Children 2 I need to convert this into a dataframe with the following columns: id job grade Bool.IsMale Bool.IsFemale Bool.IsAlive Bool.IsNorthAmerican Bool.IsFromUSA Name Children 1 engineer 1 True False False True True blah NaN 2 lawyer 7 False True True True False NaN 2 I could preprocess this data in python and then call pd.DataFrame on this, but I was wondering if there was a better way of doing this? UPDATE: I ended up doing the following: If there are obvious optimizations, please let me know with open(vwfile, encoding='latin-1') as f: data = [] for line in f: line = [x.strip() for x in line.strip().split('|')] # line == [ # "1_engineer_grade1", # "|Boolean IsMale IsNorthAmerican IsFromUSA", # "|Name blah" # ] ident, job, grade = line[0].split("_") features = line[1:] bools = { "IsMale": False, "IsFemale": False, "IsNorthAmerican": False, "IsFromUSA": False, "IsAlive": False, } others = {} for category in features: if category.startswith("Bools "): for feature in category.split(' ')[1:]: bools[feature] = True else: feature = category.split(" ") # feature == ["Name", "blah"] others[feature[0]] = feature[1] featuredict = { 'ident': ident, 'job': job, 'grade': grade, } featuredict.update(bools) featuredict.update(others) data.append(featuredict) df = pd.DataFrame(data) UPDATE-2 A million line file took about 55 seconds to process this.
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80467203
type: Question
has title: pandas custom file format parsing
tagged with: dataframe

http://stackoverflow.com/comment/80558750
has text: You place them in a bag, and count them, as you suggested in your question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46805667
type: Comment

http://stackoverflow.com/a/46835209
has comment: http://stackoverflow.com/comment/80622541
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/80629268
has comment: http://stackoverflow.com/comment/80619857
type: Answer
has comment: http://stackoverflow.com/comment/80620674
has body: You should read the tzinfo manual carefully, as it is explained there. First, dst() should usually return a timedelta(0) or timedelta(hours=1), never 2 or more hours, and rarely something in between (e.g. 30 mins). This is only a dst shift relative to the normal TZ offset, not the full TZ offset in the dst mode. Second, utcoffset() must include dst correction already. The dst() method on its own is also used in some cases described in the manual (e.g. for detection if dst is in effect or not), but it is NOT automatically applied to the TZ offset unless you do so. Your code should look like this: from datetime import datetime, tzinfo, timedelta class CET(tzinfo): def utcoffset(self, dt): return timedelta(hours=1) + self.dst(dt) def dst(self, dt): dston = datetime(year=dt.year, month=3, day=20) dstoff = datetime(year=dt.year, month=10, day=20) if dston &lt;= dt.replace(tzinfo=None) &lt; dstoff: return timedelta(hours=1) else: return timedelta(0) class UTC(tzinfo): def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return timedelta(0) def from_cet_to_utc(year, month, day, hour, minute): cet = datetime(year, month, day, hour, minute, tzinfo=CET()) utc = cet.astimezone(tz=UTC()) return '{:%Y-%m-%d:T%H:%MZ}'.format(utc) print from_cet_to_utc(year=2017, month=7, day=24, hour=10, minute=30) # 2017-07-24:T08:30Z Here, I bravely assume that the DST is in effect 20.03.YYYY - 19.10.YYYY inclusive, where YYYY is the year of the date/datetime object. Usually this logic of the on &amp; off dates is much more complicated: the shifts happen on the Sunday nights only, sometimes on the last Sunday of the month, and vary between the years, sometimes between the sovereignty of the states (with borderlines also changing over the years), and with the daylight saving laws and timezoning changing every few years (hello, Russia).
answers question: http://stackoverflow.com/q/46834202
score: 5

http://stackoverflow.com/a/47017108
has comment: http://stackoverflow.com/comment/80981001
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/80980875
answers question: http://stackoverflow.com/q/46889031
has comment: http://stackoverflow.com/comment/80981287
has comment: http://stackoverflow.com/comment/80984104
has comment: http://stackoverflow.com/comment/80981840
has body: I will try to give another answer based on my approach when starting development of a new python project. Do you plan to distribute your project, or maybe just share it with someone? If you do, what do you think - will this someone be happy with needing to remember the command $ python path/to/project/codebase/cli/cli.py --help to use your tool? Wouldn't it be easier for him to remember the command $ cli --help instead? I suggest you to start with packaging of your project right away - write a minimal setup script: from setuptools import setup, find_packages setup( name='mypkg', version='0.1', packages=find_packages(), install_requires=['click'], entry_points={ 'console_scripts': ['cli=cli.cli:cli'], }, ) You can always enhance your setup script when new requirements emerge. Place the setup script in the root directory of your codebase: ├── setup.py ├── cli │ ├── __init__.py │ ├── aws ... Now run python setup.py develop or even better, pip install --editable=.1 from the codebase root directory (where the setup.pyscript is). You have installed your project in the development mode and now can invoke $ cli --help with all the imports being resolved correctly (which would resolve your issue). But you gain much more besides that - you gain a way to package your project to be ready to be distributed to your target users and a clean command line interface which your users will invoke the same way as you just did. Now continue with the project development. If you change the code of the cli command, it will be applied on the fly so you don't need to reinstall the project each time you change anything. Once you are ready with the project development and want to deliver it to your users, issue: $ python setup.py bdist_wheel This will package your project into a installable wheel file (you will need to install wheel package to be able to invoke the command: pip install wheel --user). Usually it will reside in the dist subdirectory of the codebase root dir. Give this file to the…
downvote count: 0
has comment: http://stackoverflow.com/comment/80983530
has comment: http://stackoverflow.com/comment/80984958
has comment: http://stackoverflow.com/comment/80981615
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46889031
has comment: http://stackoverflow.com/comment/80980963

http://stackoverflow.com/q/46893798
tagged with: regex
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46893941
has comment: http://stackoverflow.com/comment/80734910
has answer: http://stackoverflow.com/a/46894044
has comment: http://stackoverflow.com/comment/80736573
has body: I am trying to find the exact match of a certain string: The user is prompted to enter a string, say 'AAAA' and I want to find the exact instants that this key is in a certain dictionary, dict that looks like {'AAAA':1, 'ZZZZ':2, 'BCBC':3} Right now i have: string = input("enter string") for key in dict.keys(): regex = re.compile(r'^(key)$') if re.search(regex, string): match = re.search(string) print('match at %s') % (match.group(0)) I want the user to input a string, then to loop through all the possible keys and see if there's an exact match. If there is an exact match, I want to return the value (the index) where that key is. Hence, if a user inputs AAAAZZZZ, I want it to print (1,2)
has title: Python regex: Looping through keys to find exact match
has comment: http://stackoverflow.com/comment/80798983
type: Question
answer count: 2
score: 0
tagged with: python

http://stackoverflow.com/comment/81949718
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46755468
has text: Hi efkin, Do you have an email I can contact you?

http://stackoverflow.com/q/46787357
tagged with: openmdao
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46788025
type: UnansweredQuestion
has title: How to create an Optimization in OpenMDAO framework using apply_nonlinear?
has body: I tried to optimize the Rosebrock function that relates with a simple implicit equation (see apply_nonlinear section) as shown below using OpenMDAO framework. from openmdao.api import Component, Problem, Group, ScipyOptimizer, IndepVarComp, Newton, ScipyGMRES class optimization(Component): def __init__(self): super(optimization, self).__init__() # Parameter self.add_param('x', 0.5) #Design Variable self.add_param('d1', 1.0) self.add_param('d2', 1.0) #Iteration Variable self.add_state('y', 1.0) self.add_state('z', 1.0) self.add_output('f', shape=1) def solve_nonlinear(self, params, unknowns, resids): d1 = params['d1'] d2 = params['d2'] y = unknowns['y'] z = unknowns['z'] a = y/5.833333; b = z/2.666667*100; # print('a=%f'% a) # print('b=%f'% b) # Exact value for a and b is 1 and 100 # Rosenbrock function for Optimization unknowns['f'] = (a-d1)**2 + b*(d2-d1**2)**2 def apply_nonlinear(self, params, unknowns, resids): x = params['x'] y = unknowns['y'] z = unknowns['z'] resids['y'] = x*z + z - 4 resids['z'] = x + 2*z - y if __name__ == "__main__": top = Problem() root = top.root = Group() root.add('p1', IndepVarComp('x', 0.9)) root.add('p2', IndepVarComp('y', 0.9)) root.add('p', optimization()) root.connect('p1.x', 'p.d1') root.connect('p2.y', 'p.d2') top.driver = ScipyOptimizer() top.driver.options['optimizer'] = 'SLSQP' top.driver.add_desvar('p1.x', lower=-50, upper=50) top.driver.add_desvar('p2.y', lower=-50, upper=50) top.driver.add_objective('p.f') # Tell these components to finite difference root.p.deriv_options['type'] = 'fd' root.p.deriv_options['form'] = 'central' root.p.deriv_options['step_size'] = 1.0e-4 top.root.nl_solver = Newton() top.root.nl_solver.options['maxiter']=int(200) top.root.nl_solver.options['atol']=float(1e-12) top.root.nl_solver.options['rtol']=float(1e-10) top.root.nl_solver.options['iprint']=int(2) top.root.ln_solver = ScipyGMRES() top.root.ln_solver.options['iprint']=int(-1) top.setup() top['p1.x'] = 0.9 top['p2.y'] = 0.9 top.run() print('\…
tagged with: python
type: Question

http://stackoverflow.com/comment/80565184
comment on: http://stackoverflow.com/q/46806552
type: Comment
score: 0
has text: @Bear Brown. The select works perfect. The problem is getting a model instance (especially a model property) from the query set. my_instance = qs[0], my_prop = my_instance.my_prop <-this throws the ORA-00942
type: QuestionComment

http://stackoverflow.com/comment/80583780
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46818148
score: 1
has text: @WillemVanOnsem love that show!

http://stackoverflow.com/comment/80685765
score: 0
type: AnswerComment
has text: Did you try my comment? `df['C'] = df.apply(lambda r: [a+'-'+b for a,b in zip(r.A, r.B)], axis=1)` Does it work on your example data?
type: Comment
comment on: http://stackoverflow.com/a/46866505

http://stackoverflow.com/a/63266533
type: Answer
has body: You can use object_versions. def delete_all_versions(bucket_name: str, prefix: str): s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) if prefix is None: bucket.object_versions.delete() else: bucket.object_versions.filter(Prefix=prefix).delete() delete_all_versions("my_bucket", None) # empties the entire bucket delete_all_versions("my_bucket", "my_prefix/") # deletes all objects matching the prefix (can be only one if only one matches)
upvote count: 12
answers question: http://stackoverflow.com/q/46819590
score: 12
downvote count: 0

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/46829657
type: Tag

http://stackoverflow.com/comment/80554203
comment on: http://stackoverflow.com/a/46797974
score: 1
has text: You don't mention what error or block you hit that means you "couldn't load" it, so it's hard to be sure what the problem might be. But as the model's author mentions, you probably need to use his old custom fork of gensim as available on Github. Did you try that? If not, that's the 1st thing to try. But also: even if that succeeds, you may be disappointed with that model, for all the reasons I've mentioned.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46840602
tagged with: string
accepted answer: http://stackoverflow.com/a/46841240
possible better answer: http://stackoverflow.com/a/46840700
tagged with: python
has answer: http://stackoverflow.com/a/46840700
has title: Optimize beginner python script about substring replacement
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46841240
score: 0
answer count: 2
tagged with: char
has body: I'm tutoring a friend in python, not great at it myself. The assignment is to write a script that reverses some made up alien language in which they repeat every vowel-sequence after adding the letter "p". Some examples: tomato -&gt; topomapatopo groovy-&gt;groopoovy and beautiful -&gt; beaupeautipifupul The goal is to reverse this. From groopoovy -&gt; groovy. As it is a dutch assignment, there is an exception: "ij" is seen as a vowel. So blijpij -&gt; blij (which complicates things a lot, I find) My solution seems quite bulky to me and I am interested in a better, more elegant solution. As this is an introduction course to programming, basics are key, unfortunately. word = input() vowels = ('a', 'e', 'i', 'o', 'u') position = 0 solution = "" while position &lt; len(word): if word[position] == 'p': # obviously, search for the letter 'p' add = 1 # keep track of the sub string size group = "" while True: # loop to get consecutive vowels if word[position + add] in vowels: group += word[position + add] if word[position + add] == 'i' and word[position + add + 1] == 'j': # recognize the "ij" group += 'j' add += 1 add += 1 else: break if position+add == len(word): # stay within the bounds of the string break add -= 1 if word[position - add:position].lower() == group.lower() and group != "": position += add else: solution += 'p' else: solution += word[position] position += 1 print(solution)

glob
tags question: http://stackoverflow.com/q/46859413
tags question: http://stackoverflow.com/q/46904428
tag name: glob
type: Tag

http://stackoverflow.com/comment/80756083
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46895751
has text: wow, what a rocky road. Finally it works. I'm so grateful, thank you! Interesting though that he ask me for doubles while floats seem to be fine for you. One last thing. while `cythonizing my .pyx file` python throws the warning `Index should be typed for more efficient access`

http://stackoverflow.com/q/46756719
upvote count: 2
has comment: http://stackoverflow.com/comment/80458811
has comment: http://stackoverflow.com/comment/80458977
possible better answer: http://stackoverflow.com/a/46757026
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/80459071
accepted answer: http://stackoverflow.com/a/46757095
has comment: http://stackoverflow.com/comment/80459323
has comment: http://stackoverflow.com/comment/80458867
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80459171
has title: How to store a sparse list in python?
has comment: http://stackoverflow.com/comment/80458877
has comment: http://stackoverflow.com/comment/80459249
has comment: http://stackoverflow.com/comment/80458730
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80458905
favorite count: 0
has comment: http://stackoverflow.com/comment/80458881
has comment: http://stackoverflow.com/comment/80459085
has comment: http://stackoverflow.com/comment/80459104
has answer: http://stackoverflow.com/a/46757095
has comment: http://stackoverflow.com/comment/80458824
has comment: http://stackoverflow.com/comment/80459059
has comment: http://stackoverflow.com/comment/80458803
has answer: http://stackoverflow.com/a/46757026
has comment: http://stackoverflow.com/comment/80459701
has comment: http://stackoverflow.com/comment/80459054
has body: Now I have a dict object, where the key is a unique hashed id and the value is a length > 100 sparse list. I'd like to store this in plain text(e.g., csv/tsv/whatever that is not pickle.dump). Is there any good way to store this kind of sparse list? For example: d = {"a": [0,0,0, ..., 1,0], "b": [0.5,0,0, ...,0.5,0], "c":...} The length of each list is exactly the same. I was thinking whether it's worth storing this kind of sparse list as index-value pair. But I'm not sure whether there is any package do this.

http://stackoverflow.com/comment/80676447
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46864408
has text: @cᴏʟᴅsᴘᴇᴇᴅ: Those routines are not called from Python (but some compiled C-API code or similar) and I cannot control how they are being called.
score: 0

memoization
type: Tag
tags question: http://stackoverflow.com/q/46848642
tag name: memoization

http://stackoverflow.com/comment/80478804
has text: I have been checking my data and the problem of the nan values come from the sort_values function of pandas...I checked my solution and there is no problems to run it. Thanks!
comment on: http://stackoverflow.com/a/46757729
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80495188
score: 1
comment on: http://stackoverflow.com/a/46774705
type: AnswerComment
has text: When I answer these questions. I usually post the first thing that comes to my head that works. I then explore to see if I can come up with a better answer. So far, you have something that works. We'll see what else I can come up with, or what others can come up with.
type: Comment

http://stackoverflow.com/q/46892103
has answer: http://stackoverflow.com/a/46892379
tagged with: python
upvote count: 2
accepted answer: http://stackoverflow.com/a/46892131
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46892512
tagged with: group-by
has answer: http://stackoverflow.com/a/46892512
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/46892131
has title: pandas convert groupby values to column names
favorite count: 0
answer count: 3
has body: I have a pandas table where I have many lines with loan maturity year (can have multiple loans for any given year), loan notional, and loan type (fixed rate/floating rate). I want to extract the debt tower of a company into the a dataframe table which looks like: Year, FixedRate, FloatingRate 2018, sumofallfixed loans, sumofallfloatloans for the given year. MaturityYear Type Notional (MM) 0 2020 FIXED 600.0 1 2021 FIXED 750.0 2 2021 FLOATING 250.0 3 2025 FIXED 700.0 to convert into Year, FIXED, FLOAT 2020, 600, 0 2021, 750, 250 2025 700, 0 How can I do this with pandas? Many thanks, Toni
tagged with: pandas

http://stackoverflow.com/q/46864696
type: Question
has answer: http://stackoverflow.com/a/46864761
has title: How to resolve Python error while generating Pie chart : ValueError: 'explode' must be of length 'x'
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 8
tagged with: python
score: 8
accepted answer: http://stackoverflow.com/a/46864761
tagged with: charts
type: AnsweredQuestion
tagged with: matplotlib
has body: Can anyone help me to resolve below error while generating Pie chart with Explode option. ValueError: 'explode' must be of length 'x' import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime as dt figureObject, axesObject = plt.subplots() labels = "ABC", "XYZ" delay = [delay1, delay2] colors = ("red", "green", "orange", "cyan", "brown", "grey","blue","indigo", "beige", "yellow") explode = (0, 0.1, 0, 0) # Draw the pie chart axesObject.pie(delay, explode=explode, labels=labels, colors=colors, shadow=True, autopct='%1.2f', startangle=90, wedgeprops = { 'linewidth' : 2, 'edgecolor' : "cyan" }) plt.legend(patches, labels, loc="best") # Aspect ratio - equal means pie is a circle axesObject.axis('equal') plt.show() additional information: I am using anaconda 3.6 version. I am able to generate pie chart without explode, but when I use explode I am getting an error - ValueError: 'explode' must be of length 'x'. Please help me, how to overcome this issue.

http://stackoverflow.com/q/46856548
upvote count: 1
type: AnsweredQuestion
has title: Python, How to make one data frame from two
tagged with: dataframe
score: -1
has answer: http://stackoverflow.com/a/46856659
accepted answer: http://stackoverflow.com/a/46856659
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/80660769
tagged with: python
favorite count: 0
has body: 1)I have two data frames. They have the same amount and name of columns. How can I unite it into one data frame? I need smth like np.vstack for data frames. 2) I have data frame with column 'Sex', where are 'male' and 'female'. How can I change values 'male' to 1 and 'female' to 0 (without loops) Thanks in advance
downvote count: 2

http://stackoverflow.com/comment/80740152
comment on: http://stackoverflow.com/q/46896469
has text: Please add details by editing your question with code (not an image but copy/paste the **relevant** code) rather than adding comments. :) Also, please include whatever happens when you run your script using the IP file, what error did you get?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46897315
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46897153
downvote count: 0
has body: couple things that went wrong with your code: 1:You don't need f = [] since you overwrite it with an integer. 2:The while loop will not exit once you hit a number that is a multiple of 5, which will crash your console. It will keep printing. Use if instead. 3: Use [] instead of () to access an element by index import random for x in range(1,10): f = random.randint(1,101) if f%5.0 == 0.0: print f If you are trying to add the integer to a list f, then you need to append it, do f.append

http://stackoverflow.com/comment/80741395
comment on: http://stackoverflow.com/a/46896757
type: AnswerComment
score: 0
type: Comment
has text: FileExistsError: [WinError 183] Cannot create a file when that file already exists:

http://stackoverflow.com/comment/85034155
comment on: http://stackoverflow.com/a/46789472
type: AnswerComment
type: Comment
score: 0
has text: @GuangyangLi **1.** I'd use `async for item in io_gen(x): yield item` **2.** In that case you might consider using [aiostream.stream.map](http://aiostream.readthedocs.io/en/latest/operators.html#aiostream.stream.map) and limit the amount of running tasks using the `task_limit` argument.

http://stackoverflow.com/comment/80454574
has text: Please do not ask several unrelated questions in one question. For the animation consider using `FuncAnimation`. Please read [ask] and if there is a problem of implementation, make sure to refer to already present question here on SO; only if they do not help, ask as specific question about the animation, but make sure to clearly state in how far other resources don't help.
comment on: http://stackoverflow.com/q/46751667
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46870489
answers question: http://stackoverflow.com/q/46862722
downvote count: 0
upvote count: 1
type: Answer
score: 1
has body: Try with tensorflow.contrib.keras.python.keras: from tensorflow.contrib.keras.python.keras.models import Sequential

http://stackoverflow.com/comment/80567239
type: Comment
has text: Like you've just shown... what are you asking exactly?
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/46810056

http://stackoverflow.com/q/46816393
type: AnsweredQuestion
has body: I am trying to write a snippet for removing duplicate elements in a linked list in python. my condition of checking previous node values in dictionary is not yielding true. I am unable to figure out why it always returns false. Node values are [ 0->1->2->2->3->4->4->5 def RemoveRepeatNode(self): curr_node = self.head unique_list = {} unique_list[curr_node.data] = 1 while(curr_node.next != None): if curr_node.next.data in unique_list: ## doesn't evaluate to True print "repeated values ", curr_node.next.data curr_node = curr_node.next.next else: unique_list[curr_node.data] = 1 curr_node = curr_node.next
tagged with: linked-list
has answer: http://stackoverflow.com/a/46816455
accepted answer: http://stackoverflow.com/a/46816455
type: Question
has title: checking node value exists in dictionary
score: 0
answer count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/46897974
has body: I'm trying to minimize a functional (integral of a function), given constraints def s(y,a,b,c,d): v = [1, y, y**2, y**3] alpha = [a, b, c, d] q = np.inner(v,alpha) return -q*np.exp(-q) def p(y,a,b,c,d): v = [1, y, y**2, y**3] alpha = [a, b, c, d] q = np.inner(v,alpha) return np.exp(-q) def Q(u): a, b, c, d = u d = integrate.quad(lambda y: s(y,a,b,c,d), 0, 1) return d[0] cons = ({'type': 'eq', 'fun' : integrate.quad(lambda y: p(y,a,b,c,d), 0, 1)[0]-1}, {'type': 'eq', 'fun' : integrate.quad(lambda y: (p(y,a,b,c,d)*y), 0, 1)[0]-0.483523521402009}, {'type': 'eq', 'fun' : integrate.quad(lambda y: (p(y,a,b,c,d)*y**2), 0, 1)[0]-0.300458990347083}, {'type': 'eq', 'fun' : integrate.quad(lambda y: (p(y,a,b,c,d)*y**3), 0, 1)[0]-0.209996591802522}) res = minimize(Q, x0 = (0, 0, 0, 0), method='BFGS', constraints=cons) print(res) I get an output fun: -0.36787942624169967 hess_inv: array([[ 17.98311921, -49.74794121, 2.50822967, 36.21942131], [ -49.74794121, 191.70720321, -23.14586623, -158.65310285], [ 2.50822967, -23.14586623, 8.1640543 , 25.72129091], [ 36.21942131, -158.65310285, 25.72129091, 142.59127393]]) jac: array([ -3.54647636e-06, -1.94460154e-06, -1.75461173e-06, 3.24100256e-07]) message: 'Optimization terminated successfully.' nfev: 126* *nit: 19 njev: 21 status: 0 success: True x: array([ 0.99920744, 0.0092224 , -0.02276881, 0.0150456 ])** However using this array of X, does not satisfy the constraint x = (0.99920744, 0.0092224 , -0.02276881, 0.0150456) integrate.quad(lambda y: p(y,x[0],x[1],x[2],x[3]), 0, 1)[0] 0.3678829742546207 which is not 1, as specifically stated in the constraint. How is it claiming convergence when it clearly has not converged?
downvote count: 0
has comment: http://stackoverflow.com/comment/80759275
favorite count: 0
has comment: http://stackoverflow.com/comment/80767471
type: UnansweredQuestion
has title: Functional Constrained Optimization Python Incorrect Answer
has comment: http://stackoverflow.com/comment/80743194
tagged with: python
has comment: http://stackoverflow.com/comment/80759248
answer count: 0
score: 1
upvote count: 1
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/80743203
tagged with: optimization

http://stackoverflow.com/q/46849467
type: Question
has answer: http://stackoverflow.com/a/46850049
has body: I'm writing code to convert a CSV into XML. Suppose I have a single list like: input = ['name', 'val', 0, \ 'name', 'val', 1, 'tag', 'val', \ 'name', 'val', 2, 'tag', 'val', 'tag', 'val', \ 'name', 'val', 0] Every slice of this list starting with 'name' denotes an element with a name, a value, and a variable number of optional tag-value pairs. I want to turn this into: output = [['name', 'val', []], ['name', 'val', ['tag', 'val']], ['name', 'val', ['tag', 'val', 'tag', 'val']], ['name', 'val', []]] No need to separate the tag-value pairs into tuples, this is handled in a separate method. I have a solution, but it's not very pythonic: output=[] cursor=0 while cursor &lt; len(input): name=input[cursor] val=input[cursor+1] ntags=int(input[cursor+2]) optslice=input[cursor+3:cursor+3+2*ntags] cursor = cursor+3+2*ntags print name, val, ntags, optslice, cursor output.append([name, val, optslice]) print output &gt; name val 0 [] 3 &gt; name val 1 ['tag', 'val'] 8 &gt; name val 2 ['tag', 'val', 'tag', 'val'] 15 &gt; name val 0 [] 18 &gt; [['name', 'val', []], ['name', 'val', ['tag', 'val']], ['name', 'val', ['tag', 'val', 'tag', 'val']], ['name', 'val', []]] I think I could probably do this as a list comprehension, but the variable length of each element is throwing me for a loop. The input is parsed from a CSV, and I can change the format to better fit a different solution. Ideas?
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/46849772
tagged with: python-2.7
score: 2
downvote count: 0
favorite count: 0
has title: Python list comprehension with multiple elements of variable length?
tagged with: python
answer count: 4
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46850034
has answer: http://stackoverflow.com/a/46849778

http://stackoverflow.com/comment/80469651
score: 0
has text: If you want every possible version of operations then you might as well do that systematically rather than randomly choosing operations.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46762075

http://stackoverflow.com/a/46841942
answers question: http://stackoverflow.com/q/46841896
has comment: http://stackoverflow.com/comment/80631766
score: 0
has comment: http://stackoverflow.com/comment/80631880
type: Answer
has body: There's no difference for Python. People usually follow the same nomenclature used in the literature, for example, E for energy is usually capitalized, or names for matrices. It is just a personal choice.
has comment: http://stackoverflow.com/comment/80631950

http://stackoverflow.com/q/46790021
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/46790296
favorite count: 0
type: Question
tagged with: python
has title: Making post requests in python
score: -1
has body: When i make this requests it returns code 200 which it should. But if i change sizeLoadedVarient or colorLoadedID then checkout should not return true. The first request should add an item to cart. The second request should only return 200 if there is something in the cart Currently it is outputting checkout ok Even when it should return false import requests atcURL = "http://www.thenextopening.com/shop/111222/add.json" sizeLoadedVarient = "40414" colorLoadedID = "19824" headers = user = {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1"} sessionProfile = requests.session() senddata = { 'size' : sizeLoadedVarient, 'style' : colorLoadedID, 'qty' : 1 } r = sessionProfile.post(atcURL,data=senddata, verify=False, headers=headers) if (r.status_code == 200): print("ATC ok") r2 = sessionProfile.get("http://www.thenextshopopen.com/checkout")#.text #print(r2) if(r2.status_code == 200): print('checkout ok') elif(r2.status_code != 200): print('checkout not ok') else: print('checkout not ok') elif (r.status_code != 200): print("Atc not ok") else: print('atc not ok')
tagged with: request
tagged with: python-requests
downvote count: 1
tagged with: http
answer count: 1
has answer: http://stackoverflow.com/a/46790296
has comment: http://stackoverflow.com/comment/80526384

http://stackoverflow.com/q/46857328
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80662720
type: Question
has answer: http://stackoverflow.com/a/46857440
has body: I can't seem to figure out a way to include some multiples into my non prime list. for examples "15" "49" "9" is considered a prime number. Any ideas or corrections ? number = int(input("Enter a number. ")) non_prime = [] prime = [] def isPrime(number): for i in range(2,number): if number % i == 0: return False else: return True def append(number): for i in range(1,number+1): if isPrime(i) == True: prime.append(i) else: non_prime.append(i) append(number) print(non_prime) print(prime) print (len(prime))
has comment: http://stackoverflow.com/comment/80662456
has title: conditional not appending all correct integers to proper list
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80662403
accepted answer: http://stackoverflow.com/a/46857440
has comment: http://stackoverflow.com/comment/80662683
tagged with: python
linked to: http://stackoverflow.com/q/18833759

http://stackoverflow.com/q/46762533
has comment: http://stackoverflow.com/comment/80527714
has comment: http://stackoverflow.com/comment/80494518
has comment: http://stackoverflow.com/comment/80691319
has comment: http://stackoverflow.com/comment/80685428
has comment: http://stackoverflow.com/comment/80722649
has comment: http://stackoverflow.com/comment/80491091
tagged with: multiprocessing
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/46900727
has body: I am trying to parallelize an embarrassingly parallel for loop (previously asked here) and settled on this implementation that fit my parameters: with Manager() as proxy_manager: shared_inputs = proxy_manager.list([datasets, train_size_common, feat_sel_size, train_perc, total_test_samples, num_classes, num_features, label_set, method_names, pos_class_index, out_results_dir, exhaustive_search]) partial_func_holdout = partial(holdout_trial_compare_datasets, *shared_inputs) with Pool(processes=num_procs) as pool: cv_results = pool.map(partial_func_holdout, range(num_repetitions)) The reason I need to use a proxy object (shared between processes) is the first element in the shared proxy list datasets that is a list of large objects (each about 200-300MB). This datasets list usually has 5-25 elements. I typically need to run this program on a HPC cluster. Here is the question, when I run this program with 32 processes and 50GB of memory (num_repetitions=200, with datasets being a list of 10 objects, each 250MB), I do not see a speedup even by factor of 16 (with 32 parallel processes). I do not understand why - any clues? Any obvious mistakes, or bad choices? Where can I improve this implementation? Any alternatives? I am sure this has been discussed before, and the reasons can be varied and very specific to implementation - hence I request you to provide me your 2 cents. Thanks. Update: I did some profiling with cProfile to get a better idea - here is some info, sorted by cumulative time. In [19]: p.sort_stats('cumulative').print_stats(50) Mon Oct 16 16:43:59 2017 profiling_log.txt 555404 function calls (543552 primitive calls) in 662.201 seconds Ordered by: cumulative time List reduced from 4510 to 50 due to restriction &lt;50&gt; ncalls tottime percall cumtime percall filename:lineno(function) 897/1 0.044 0.000 662.202 662.202 {built-in method builtins.exec} 1 0.000 0.000 662.202 662.202 test_rhst.py:2(&lt;module&gt;) 1 0.001 0.001 661.341 661.341 test_rhst.py:70(test_…
has comment: http://stackoverflow.com/comment/80486098
has answer: http://stackoverflow.com/a/46909791
has comment: http://stackoverflow.com/comment/80718426
score: 12
has comment: http://stackoverflow.com/comment/80630934
answer count: 3
has comment: http://stackoverflow.com/comment/80671352
has comment: http://stackoverflow.com/comment/80616595
downvote count: 0
has comment: http://stackoverflow.com/comment/80623459
has comment: http://stackoverflow.com/comment/80622545
has answer: http://stackoverflow.com/a/46919075
has comment: http://stackoverflow.com/comment/80722621
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/80670339
has title: Why am I not seeing speed up via multiprocessing in Python?
favorite count: 0
has comment: http://stackoverflow.com/comment/80685423
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80494877
tagged with: python
linked to: http://stackoverflow.com/q/46391191
has comment: http://stackoverflow.com/comment/80671164
has comment: http://stackoverflow.com/comment/80530081
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/80623498
linked to: http://stackoverflow.com/q/5375624
has comment: http://stackoverflow.com/comment/80631147

http://stackoverflow.com/comment/80540934
comment on: http://stackoverflow.com/q/46796943
score: 0
type: QuestionComment
type: Comment
has text: @AlexS Funnily enough, iterrows is faster than apply in some instances. At its heart, apply is just a python loop with overhead.

http://stackoverflow.com/q/46886513
has comment: http://stackoverflow.com/comment/80720165
downvote count: 5
has answer: http://stackoverflow.com/a/46886776
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80720197
accepted answer: http://stackoverflow.com/a/46886567
possible better answer: http://stackoverflow.com/a/46886776
favorite count: 0
upvote count: 2
has body: I am new in python. I would like to ask, how I can use a relative path in this function: with open('path?', 'r') as file: I want to have a relative path to my desktop. This function is from the module: import xlsxwriter thanks a lot
has title: Python - relative path "with open(..) - function
score: -3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/135889945
has answer: http://stackoverflow.com/a/46886567
type: Question
answer count: 2

http://stackoverflow.com/q/46833212
has comment: http://stackoverflow.com/comment/80616534
has body: I'm trying to store some data that's scraped from a website. The data I need is the text from the element, to then store in a csv for querying later on. In the code below, I'm finding all references to the class 'vip'. Then I want to loop through those to strip away the unnecessary HTML to get the text data only. Finally I encode it with utf-8, ready to be inserted into a csv. # parse the page and store in var soup soup = BeautifulSoup(page, 'html.parser') # find the title title_box = soup.findAll('a', attrs={'class': 'vip'}} print title_box # loop through each iteration for each in title_box: if each.find('title_box'): title = title_box.text.strip().encode('utf-8') # print the result print title However whenever I print the result of 'title' I get the following error: Traceback (most recent call last): File "/Users/XXXX/Projects/project-kitchenaid/scaper.py", line 28, in <module> print title NameError: name 'title' is not defined From what I understand, title is out of scope. How do I retrieve the the data from the loop and write it to a print call? For context, this is just one result of print title_box: KITCHENAID CLASSIC MIXER 5K45SS - ATTACHMENTS AND INSTRUCTIONS]
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46835627
has comment: http://stackoverflow.com/comment/80616734
has comment: http://stackoverflow.com/comment/80614616
downvote count: 0
type: UnansweredQuestion
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/80614791
has answer: http://stackoverflow.com/a/46834705
has answer: http://stackoverflow.com/a/76235716
has title: Looping through elements with Beautifulsoup
has comment: http://stackoverflow.com/comment/80614096
score: 5
has answer: http://stackoverflow.com/a/46835810
has comment: http://stackoverflow.com/comment/80618758
favorite count: 0
tagged with: beautifulsoup
upvote count: 5

http://stackoverflow.com/a/46991957
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46849915
has body: Thanks to 'empet' at community.plot.ly, here is the code that ended up working. Basically, needed to make a seperate plot just for the shaded section. #### Plot ploints for the text #### trace_stages=dict(type='scatter', x= stages_x, y=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], mode='markers', text=['stage 0', 'stage 1', 'stage 2', 'stage 3', 'stage 4', 'stage 5', 'stage 6', 'stage 7', 'stage 8','stage 9', 'stage 10'], hoverinfo='text', marker=dict(size=[0]), showlegend = False ) #### Plot for the shading #### trace_stage0=go.Scatter( x = [points['A'][0], points['B'][0]], y = [1,1], mode = 'markers+lines', line = dict(width=0), # Setting width = 0 = no lines marker=dict(size=[0,0]), # Setting size = [0,0] = no dots fill = 'tozeroy', fillcolor = 'rgba(190,0,0,.15)', # The '.15' sets opaqueness hoverinfo = "none", showlegend = False) Makes for some long code, but it works.

deep-learning
tags question: http://stackoverflow.com/q/46878201
tags question: http://stackoverflow.com/q/46813667
tags question: http://stackoverflow.com/q/46825257
tags question: http://stackoverflow.com/q/46870336
tags question: http://stackoverflow.com/q/46810120
tags question: http://stackoverflow.com/q/46777556
tags question: http://stackoverflow.com/q/46892270
tags question: http://stackoverflow.com/q/46764464
tags question: http://stackoverflow.com/q/46779659
tags question: http://stackoverflow.com/q/46892880
tags question: http://stackoverflow.com/q/46902947
tags question: http://stackoverflow.com/q/46793190
tags question: http://stackoverflow.com/q/46819088
tags question: http://stackoverflow.com/q/46806112
tags question: http://stackoverflow.com/q/46861966
tags question: http://stackoverflow.com/q/46892061
tags question: http://stackoverflow.com/q/46782575
tags question: http://stackoverflow.com/q/46903154
tags question: http://stackoverflow.com/q/46842321
tags question: http://stackoverflow.com/q/46843565
tags question: http://stackoverflow.com/q/46779097
tags question: http://stackoverflow.com/q/46832151
tags question: http://stackoverflow.com/q/46768519
tags question: http://stackoverflow.com/q/46846081
tags question: http://stackoverflow.com/q/46777793
tags question: http://stackoverflow.com/q/46748938
tags question: http://stackoverflow.com/q/46853247
tags question: http://stackoverflow.com/q/46840037
tags question: http://stackoverflow.com/q/46875546
type: Tag
tags question: http://stackoverflow.com/q/46794257
tags question: http://stackoverflow.com/q/46758489
tags question: http://stackoverflow.com/q/46807010
tags question: http://stackoverflow.com/q/46757247
tags question: http://stackoverflow.com/q/46784688
tags question: http://stackoverflow.com/q/46843430
tag name: deep-learning
tags question: http://stackoverflow.com/q/46815825
tags question: http://stackoverflow.com/q/46753234

http://stackoverflow.com/q/46783775
has title: how to give commands to the running instance of maya with mayapy.exe?
score: 1
upvote count: 1
type: Question
has body: I want to create a simple python script which will directly transfer objects from blender to Maya. I created a python script which exports the object from blender to a temp folder. now I want to import that object into Maya without actually going to Maya>file>import. I searched for the solution for a while and found out that I can create a standalone instance of Maya with mayapy.exe and work in non-GUI instance of Maya. but what I want to do is import the object into an already running instance of Maya(GUI version) as soon as the exporting script is done running.
has comment: http://stackoverflow.com/comment/80530988
answer count: 1
downvote count: 0
tagged with: maya
favorite count: 0
has comment: http://stackoverflow.com/comment/80540161
has comment: http://stackoverflow.com/comment/80523607
has answer: http://stackoverflow.com/a/46792329
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46792329

http://stackoverflow.com/a/46773597
has body: I'm a little confused about your question, but if I understand right, you want to get just the average wine ratings from the top of the page, like those circled in red here. average wine ratings As long as this list is always the first one on the page, you can use something like this to get them. list_of_ratings = soup.find("ul", {"class", "wineRatings_list"})('span') Note that the "find" method will just grab the first instance it finds, hence the need for the average rating list to be at the top of the page.
type: Answer
answers question: http://stackoverflow.com/q/46772932
score: 0
has comment: http://stackoverflow.com/comment/80495910

http://stackoverflow.com/q/46894490
has comment: http://stackoverflow.com/comment/80736295
has comment: http://stackoverflow.com/comment/80736634
tagged with: python
has comment: http://stackoverflow.com/comment/80738198
has comment: http://stackoverflow.com/comment/80736662
answer count: 0
type: UnansweredQuestion
has title: Negative values over trained data using svm but 0.99 accuracy using LinearRegression
has comment: http://stackoverflow.com/comment/80736577
type: Question
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/80736596
tagged with: svm
score: 0
has body: I am following a tutorial for predicting stock market prices using Linear Regression. I am using the LinearRegression tool from sklearn.linear_model. After doing a fit and score using this, I got an accuracy of 0.992 over my test data. The tutorial then goes on to use svm for the same. It uses sklearn.svm.SVR for this. When I fit the same training data and test it using this, I get -0.15 score and I checked in the docs, it means the model can be arbitrarily worse. Confused, I go on to score the model over the same data it was trained over and the score again is -0.15. What am I missing here? Also, the doc says "The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).", What does "can be arbitrarily worse" signify? I am using quandl.get('WIKI/GOOGL') for my data if that helps. This is my code : clf = LinearRegression() clf.fit(X_train, y_train) clf.score(X_test, y_test) //0.9924 clf = svm.SVR() clf.fit(X_train, y_train) clf.score(X_test, y_test) //-0.1514 Also, I am currently taking Andrew Ng's ML course along with this so I know about Linear Regression but I haven't reached svm till now so when this one used svm for making predictions and the predictions were way off, it confused me. So, I wanted to know if there was a particular reason why this happened.

http://stackoverflow.com/a/46833787
has body: As discussed in another answer, threads are one common approach. The other approach is to use an event loop and nonblocking I/O. Recent versions of Python (I think starting at 3.4) include a package called asyncio that supports this. You can call the create_connection method on an event_loop to create an asyncio connection. See this example for a simple server that reads and writes over TCP. In many cases an event loop can permit higher performance than threads, but it has the disadvantage of requiring most or all of your code to be aware of the event model.
answers question: http://stackoverflow.com/q/46833561
score: 0
type: Answer

http://stackoverflow.com/q/46893058
has body: Referring to this thread I was trying to apply a function to a time series that returns multiple values. It is suggesting a workaround with pd.Series object. import pandas as pd import numpy as np def some_function(data): mu, std = norm.fit(data) a = mu * 3 b = std * 5 return a, b rng = pd.date_range('1/1/2011', periods=72, freq='H') ts = pd.Series(np.random.randn(len(rng)), index=rng) r = ts.resample('2h') r'a', 'b' = r.agg(lambda x: pd.Series(some_function(x))) However, I want to apply this to resampled data while getting the following error. I am know what is the issue, but cannot figure out how to achieve my goal. ValueError: cannot set items on DatetimeIndexResampler My desired output looks like this: a b 2011-01-01 00:00:00 mu1 std1 2011-01-01 02:00:00 mu2 std2 Cheers!
tagged with: pandas
has answer: http://stackoverflow.com/a/46893471
linked to: http://stackoverflow.com/q/31421045
tagged with: python
has title: Create multiple columns from multiple return value of lambda function of resampled dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46894025
accepted answer: http://stackoverflow.com/a/46893471
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/46894025
type: Question
answer count: 2
score: 0

http://stackoverflow.com/a/46828761
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80604979
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46828499
has body: Use enums, which PyCharm for instance code completes just nicely, especially if you use type hinting. import enum class ChemFormula(enum.Enum): Chlorine = "cl2" Hydrogen = "h2" Water = "h2o" def example(formula: ChemFormula) -&gt; None: ....
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46828499
has comment: http://stackoverflow.com/comment/80604997
has comment: http://stackoverflow.com/comment/80605033

http://stackoverflow.com/comment/80692801
type: Comment
comment on: http://stackoverflow.com/a/46872738
score: 0
type: AnswerComment
has text: And I create helper Series `macd` for better readable code only.

http://stackoverflow.com/comment/80576695
score: 0
comment on: http://stackoverflow.com/q/46813921
type: QuestionComment
type: Comment
has text: A function is a function. A `lambda` expression is simply one way to create a value of type `function`.

http://stackoverflow.com/q/46781292
has body: I have an application that I wan't to run on a 10" touch screen. I am trying to make the QSlider handle larger so it will be easier to move. I have found plenty of examples of changing the handle width in the style sheet, but the changes are not being reflected when I run the code. I am using PyQt5 Designer and here is the style sheet for the slider. QSlider::groove:horizontal {height: 10px; margin: 0 0;} QSlider::handle:horizontal {background-color: black; border: 1px; height: 40px; width: 40px; margin: 0 0;} Here is the main program: from Slidertest import Ui_MainWindow import sys from PyQt5.QtWidgets import QApplication, QMainWindow class RPTApp(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(RPTApp, self).__init__(parent) self.setupUi(self) def main(): app = QApplication(sys.argv) window = RPTApp() window.show() app.exec_() if __name__ == '__main__': main() Here is the designer code for the slider: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(640, 480) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.PS_timeSlider = QtWidgets.QSlider(self.centralwidget) self.PS_timeSlider.setGeometry(QtCore.QRect(100, 100, 371, 50)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.PS_timeSlider.sizePolicy(). hasHeightForWidth()) #needed to add a return and break the line above self.PS_timeSlider.setSizePolicy(sizePolicy) self.PS_timeSlider.setBaseSize(QtCore.QSize(0, 0)) font = QtGui.QFont() font.setPointSize(12) font.setKerning(False) self.PS_timeSlider.setFont(font) self.PS_timeSlider.setFocusPolicy(QtCore.Qt.WheelFocus) self.PS_timeSlider.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.PS_timeSlider.setToolTip("") self.PS_timeSlider.…
tagged with: qtstylesheets
score: 4
upvote count: 4
tagged with: pyqt
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46796460
favorite count: 0
accepted answer: http://stackoverflow.com/a/46796460
has title: How to change QSlider handle width using stylesheet
tagged with: python
tagged with: qslider
type: AnsweredQuestion
tagged with: pyqt5
type: Question

http://stackoverflow.com/q/46876259
has answer: http://stackoverflow.com/a/46876993
type: AnsweredQuestion
has title: How to sort all the available users for booking in Flask?
type: Question
has comment: http://stackoverflow.com/comment/80699636
tagged with: flask
has body: I've created a small booking application where the client can book for a service, i've also made a form search where the client can search in a specific date to book. The results should be all the available users except if one of them is busy in the given date by the client. here is my models.py: class User(db.Model, UserMixin): __tablename__ = 'user' id = db.Column(db.Integer(), primary_key=True) public_id = db.Column(db.String(50), default=uuid.uuid4) name = db.Column(db.String()) appointments = db.relationship('Appointment', backref='user', passive_deletes=True, lazy='dynamic') class Appointment(db.Model): id = db.Column(db.Integer(), primary_key=True) public_id = db.Column(db.String(50), default=uuid.uuid4) start_time = db.Column(db.DateTime(), default=datetime.utcnow) end_time = db.Column(db.DateTime(), default=datetime.utcnow) user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')) Here is my code: from datetime import timedelta from dateutil.parser import parse date_time = parse(request.form.get('datetime')) end_time = date_time + timedelta(minutes=20) overlapping = db.session.query(Appointment).filter( not_( or_(Appointment.start_time &gt; end_time, Appointment.end_time &lt; date_time))) overlapping.count() # if overlapping returns &gt; 0 so the client can't book # Here i am joining the two tables so i can get the available users on that date results = User.query.join(Appointment, Appointment.user_id == User.id).filter( Appointment.start_time &gt; end_time).filter( Appointment.end_time &lt; date_time).all() In the results i get nothing . Please any suggestions guys !!!
score: 0
has comment: http://stackoverflow.com/comment/80700290
tagged with: sql
has comment: http://stackoverflow.com/comment/80699731
answer count: 1
linked to: http://stackoverflow.com/q/8603088
tagged with: flask-sqlalchemy
accepted answer: http://stackoverflow.com/a/46876993
has comment: http://stackoverflow.com/comment/80699715
tagged with: python

http://stackoverflow.com/a/46792924
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46789896
type: Answer
has comment: http://stackoverflow.com/comment/80537573
has body: I think the simpliest way would be using ROI as you did. cv::Mat workingRegion = img(cv::Rect(x_coord,y_coord,width,height), img.type()); In images created with software like microsoft online borders are always located in the same part of image. You could cut it off. To detect border i would use OTSU threshold cv::threshold(img,img,100,255, CV_THRESH_OTSU); I would produce better results. Add some images so I can help you better.
score: 0
accepted answer of: http://stackoverflow.com/q/46789896

multi-index
tags question: http://stackoverflow.com/q/46832603
type: Tag
tags question: http://stackoverflow.com/q/46780792
tag name: multi-index
tags question: http://stackoverflow.com/q/46900483
tags question: http://stackoverflow.com/q/46901513

http://stackoverflow.com/q/46807010
tagged with: word2vec
type: Question
score: 3
tagged with: deep-learning
tagged with: doc2vec
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46816101
accepted answer: http://stackoverflow.com/a/46816101
tagged with: python
tagged with: gensim
has title: What are doc2vec training iterations?
has body: I am new to doc2vec. I was initially trying to understand doc2vec and mentioned below is my code that uses Gensim. As I want I get a trained model and document vectors for the two documents. However, I would like to know the benefits of retraining the model in several epoches and how to do it in Gensim? Can we do it using iter or alpha parameter or do we have to train it in a seperate for loop? Please let me know how I should change the following code to train the model for 20 epoches. Also, I am interested in knowing is the multiple training iterations are needed for word2vec model as well. # Import libraries from gensim.models import doc2vec from collections import namedtuple # Load data doc1 = ["This is a sentence", "This is another sentence"] # Transform data docs = [] analyzedDocument = namedtuple('AnalyzedDocument', 'words tags') for i, text in enumerate(doc1): words = text.lower().split() tags = [i] docs.append(analyzedDocument(words, tags)) # Train model model = doc2vec.Doc2Vec(docs, size = 100, window = 300, min_count = 1, workers = 4) # Get the vectors model.docvecs[0] model.docvecs[1]
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/46765881
has title: I have installed scrapy succefully why command not found?
tagged with: python
has answer: http://stackoverflow.com/a/46766051
tagged with: macos
has comment: http://stackoverflow.com/comment/80477011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80477428
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/80477068
answer count: 1
has body: qiao-lideMacBook-Pro:~ qiao-li$ pip3 freeze ...... **Scrapy==1.4.0** ...... qiao-lideMacBook-Pro:~ qiao-li$ scrapy version **-bash: scrapy: command not found**
score: 0

http://stackoverflow.com/comment/80730592
type: AnswerComment
comment on: http://stackoverflow.com/a/46890687
type: Comment
has text: That requires signatures to be equal for all functions inside
score: 0

http://stackoverflow.com/comment/80635537
has text: there is no row numbers in Spark.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46844000

http://stackoverflow.com/q/46793528
has title: Spark fails on task with SparkException: Can only zip RDDs with same... with no zip() direct call
tagged with: spark-submit
tagged with: apache-spark
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: pyspark
has body: I'm using Spark with a spark-submit call and a python script for cluster analysis I send with it. From the script: spark = SparkSession.builder.appName(results.taskName).getOrCreate() dataset = spark.read.format("com.mongodb.spark.sql").load() assembler = VectorAssembler(inputCols=results.inputColumns, outputCol="features") output = assembler.transform(dataset) topAnomalies = int((results.nOutliers / 100) * output.count()) kmeans = KMeans().setK(results.nClusters).setSeed(1) model = kmeans.fit(output) The last command - model = kmeans.fit(output) - fails (not every time, though) and produce these errors: py4j.protocol.Py4JJavaError: An error occurred while calling o41.fit. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 6.0 failed 4 times, most recent failure: Lost task 0.3 in stage 6.0 (TID 9, 10.0.3.153, executor 0): org.apache.spark.SparkException: Can only zip RDDs with same number of elements in each partition at org.apache.spark.rdd.RDD$$anonfun$zip$1$$anonfun$apply$27$$anon$2.hasNext(RDD.scala:860) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:461) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$an…
type: Question
upvote count: 1

http://stackoverflow.com/q/46890203
type: UnansweredQuestion
tagged with: python
tagged with: excel
tagged with: openpyxl
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47106014
tagged with: defaultdict
score: 0
has title: Using DefaultDict(List) with Openpyxl
answer count: 1
has body: I'm trying to accomplish this with Python 3.6.1, Pycharm 2017.1.3., Openpyxl 2.4.7, and Excel 2016. Here is my dataset: Sheet1: productnum|keyword1|keyword2 0001 |red |big 0001 |blue |red 0001 |large |blue 0002 |green | 0002 |small |blue I'd like to end up with this: productnum|keyword1 |keyword2 |combinedkeywords 0001 |red;blue;large|big;red;blue|red;blue;large;big 0002 |green;small |blue |green;small;blue I have been informed that DefaultDict(List) is a good way to accomplish this task. Here is what I've tried thus far to do so: for rownum in range(1,maxRow): partnum = str(sheet1.cell(row=rownum, column=1).value) keyword1 = str(sheet1.cell(row=rownum, column=3).value) s = [(partnum,keyword1)] print(s) d = defaultdict(list) for k, v in s: d[k].append(v) But what I end up isn't exactly what I need, coming out as something like: [('0001', 'red'] [('0001', 'blue'] And so on. Does anyone have any advice on how I can accomplish this using defaultdict(list)? Thanks in advance!
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80503741
type: Comment
type: QuestionComment
score: 2
has text: Did you go to line 6452 and see what your data looks like and why it throws that error?
comment on: http://stackoverflow.com/q/46778899

http://stackoverflow.com/comment/80508953
comment on: http://stackoverflow.com/a/46781252
has text: In case you wanted an update, I implemented that and it works perfect!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80614548
type: Comment
type: QuestionComment
score: 0
has text: @Divakar: It's simply (index, value) pairs. I need to increase `x[index]` by `value`. The problem is that indices are not unique
comment on: http://stackoverflow.com/q/46833398

http://stackoverflow.com/comment/80465352
score: 0
comment on: http://stackoverflow.com/q/46759620
type: Comment
type: QuestionComment
has text: I've also simplified the code since you're initial response. Right now I believe the error to be a syntax error regarding calling the method from class Useful.

http://stackoverflow.com/a/46775778
downvote count: 0
score: 1
has body: You are trying to update "dic" without initializing it in index(). Also add an else statement in case none of the three situations you declared are true.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46775664

http://stackoverflow.com/comment/80757943
has text: Bad caption and why are you adding so many commands?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46905542
type: QuestionComment

http://stackoverflow.com/a/58125308
upvote count: 1
answers question: http://stackoverflow.com/q/46895772
type: Answer
downvote count: 0
score: 1
has body: You need to perform a dilation. A dilation is a morphological operation which causes brighter regions within the input image to grow. As explained here, dilation is performed by convoluting the input image with some kernel: As the kernel B is scanned over the image, we compute the maximal pixel value overlapped by B and replace the image pixel in the anchor point position with that maximal value. The anchor point is usually the center of the kernel. In your case, I would suggest using an elliptical kernel with a size of your choice. With one pixel thick lines and with a kernel of size (n,n), the lines in your resulting dilated image will be approximately 2*n thick. Here's a sample code : kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) result = cv2.dilate(outline, kernel) Here is an example of dilation :

http://stackoverflow.com/comment/80497020
score: 0
has text: And, if I solved your problem, feel free to mark this as a solution to potentially help other users possibly facing the same problem to find a solution!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46775491

http://stackoverflow.com/a/46835720
score: 1
has comment: http://stackoverflow.com/comment/80649045
has comment: http://stackoverflow.com/comment/80649330
upvote count: 1
has comment: http://stackoverflow.com/comment/122862961
has body: Unless you're doing this for your own amusement or as a learning exercise, my very strong advice is don't do this. PRNGs have the same general structure, even if the details are wildly different. They map a seed value s into an initial state S via some function f: S←f(s); they then iterate states via some transformation h: Si+1←h(Si); and finally they map the state to an output U via some function g: Ui←g(Si). (For simple PRNGs, f() or g() are often identity functions. For more sophisticated generators such as Mersenne Twister, more is involved.) The state transition function h() is designed to distribute new states uniformly across the state space. In other words, it's already a hash function, but with the added benefit that for any widely accepted generator it has been heavily vetted by experts to have good statistical behavior. Mersenne Twister, Python's default PRNG, has been mathematically proven to have k-tuples be jointly uniformly distributed for all k ≤ 623. I'm guessing that whatever hash function you choose can't make such claims. Additionally, the collapsing function g() should preserve uniformity in the outcomes. You've proposed that you "can use the integer version of the hash to create a flat number range, just by taking the modulus." In general this will introduce modulo bias, so you won't end up with a uniformly distributed result. If you stick with the built-in PRNG, there's no reason not to use the built-in Gaussian generator. If you want to do it for your own amusement there are lots of resources that will tell you how to map uniforms to Gaussians. Well-known methods include the Box-Muller method, Marsaglia's polar method, and the ziggurat method. UPDATE Given the additional information you've provided in your question, I think the answer you want is contained in this section of Python's documentation for random: The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate y…
answers question: http://stackoverflow.com/q/46831581
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80647556
has comment: http://stackoverflow.com/comment/80640524

http://stackoverflow.com/comment/80456311
comment on: http://stackoverflow.com/q/46755445
type: Comment
type: QuestionComment
score: 2
has text: Could you provide what research you've done, what code you've thus-far completed and if neither former or latter are proficiently available- I would suggest to post less ambiguous questions that detail errors and hiccups you've encountered instead.

http://stackoverflow.com/comment/80456830
comment on: http://stackoverflow.com/q/46755340
score: 0
type: Comment
type: QuestionComment
has text: Where? I think I already set the input shape like (2050, 75), correct me if I am wrong.

http://stackoverflow.com/comment/80507662
type: AnswerComment
score: 0
has text: Thanks, it will definitely be a clean way to do it but I have a reason to not concatenate them all together yet.
type: Comment
comment on: http://stackoverflow.com/a/46780637

http://stackoverflow.com/comment/80583826
type: QuestionComment
comment on: http://stackoverflow.com/q/46817766
score: 0
type: Comment
has text: Is your app `webapps` or `webapp`?

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/46865169
tags question: http://stackoverflow.com/q/46801261
tags question: http://stackoverflow.com/q/46790390
tags question: http://stackoverflow.com/q/46762014
tags question: http://stackoverflow.com/q/46784877
tags question: http://stackoverflow.com/q/46777899
tags question: http://stackoverflow.com/q/46831929
tags question: http://stackoverflow.com/q/46748739
tags question: http://stackoverflow.com/q/46831294
tags question: http://stackoverflow.com/q/46809787
tags question: http://stackoverflow.com/q/46782427
tags question: http://stackoverflow.com/q/46781708
tags question: http://stackoverflow.com/q/46846295
tags question: http://stackoverflow.com/q/46767221
tags question: http://stackoverflow.com/q/46810099
tags question: http://stackoverflow.com/q/46890562
tags question: http://stackoverflow.com/q/46808017
tags question: http://stackoverflow.com/q/46861647
tags question: http://stackoverflow.com/q/46856276
tags question: http://stackoverflow.com/q/46775963
tags question: http://stackoverflow.com/q/46854964
tags question: http://stackoverflow.com/q/46872424
tags question: http://stackoverflow.com/q/46867932
tags question: http://stackoverflow.com/q/46776298
tags question: http://stackoverflow.com/q/46855071
tags question: http://stackoverflow.com/q/46869358
tags question: http://stackoverflow.com/q/46803034
tags question: http://stackoverflow.com/q/46857087
tags question: http://stackoverflow.com/q/46749014
tags question: http://stackoverflow.com/q/46757860
tags question: http://stackoverflow.com/q/46829568
tags question: http://stackoverflow.com/q/46843619
type: Tag
tags question: http://stackoverflow.com/q/46862581
tags question: http://stackoverflow.com/q/46841939
tags question: http://stackoverflow.com/q/46753436
tags question: http://stackoverflow.com/q/46796570
tags question: http://stackoverflow.com/q/46755832
tags question: http://stackoverflow.com/q/46889283
tags question: http://stackoverflow.com/q/46773447
tags question: http://stackoverflow.com/q/46887497
tags question: http://stackoverflow.com/q/46867215
tags question: http://stackoverflow.com/q/46767533
tags question: http://stackoverflow.com/q/46805610
tags question: http://stackoverflow.com/q/46765421
tags question: http://stackoverflow.com/q/46777349
tags question: http://stackoverflow.com/q/46881343
tags question: http://stackoverflow.com/q/46870809
tags question: http://stackoverflow.com/q/46807876
tags question: http://stackoverflow.com/q/46775117
tags question: http://stackoverflow.com/q/46892999
tags question: http://stackoverflow.com/q/46820898
tags question: http://stackoverflow.com/q/46821927
tags question: http://stackoverflow.com/q/46804799
tags question: http://stackoverflow.com/q/46756858
tags question: http://stackoverflow.com/q/46824393
tags question: http://stackoverflow.com/q/46768322
tags question: http://stackoverflow.com/q/46755007
tags question: http://stackoverflow.com/q/46831044
tags question: http://stackoverflow.com/q/46900269
tags question: http://stackoverflow.com/q/46859958
tags question: http://stackoverflow.com/q/46787155
tag name: json
tags question: http://stackoverflow.com/q/46831269
tags question: http://stackoverflow.com/q/46761569
tags question: http://stackoverflow.com/q/46865008
tags question: http://stackoverflow.com/q/46800101
tags question: http://stackoverflow.com/q/46768151
tags question: http://stackoverflow.com/q/46876355
tags question: http://stackoverflow.com/q/46895204
tags question: http://stackoverflow.com/q/46750834
tags question: http://stackoverflow.com/q/46782218
tags question: http://stackoverflow.com/q/46806994
tags question: http://stackoverflow.com/q/46806615
tags question: http://stackoverflow.com/q/46749124
tags question: http://stackoverflow.com/q/46774217
tags question: http://stackoverflow.com/q/46798057
tags question: http://stackoverflow.com/q/46786342
tags question: http://stackoverflow.com/q/46829657
tags question: http://stackoverflow.com/q/46778435

http://stackoverflow.com/comment/80450627
type: Comment
type: QuestionComment
has text: Check my answer. You don't speecify where you want to put the html code from the response (inside of a `div`, etc.). I've given you a example adding it to the body
score: 0
comment on: http://stackoverflow.com/q/46752209

http://stackoverflow.com/comment/80727895
type: QuestionComment
has text: https://stackoverflow.com/a/14649949/4799172. You don't need admin rights. Set the path to `C:\Users\Me\AppData\Local\Continuum\anaconda3\` You'll need to close the cmd (and maybe restart) before testing.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46890172

http://stackoverflow.com/comment/80456780
has text: Your indentation also needs fixing; as posted, your `for` loop should exit immediately with an exception for trying to read a closed file (because the `for` loop is outside the `with` block).
comment on: http://stackoverflow.com/q/46755639
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46814207
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/11160192
has comment: http://stackoverflow.com/comment/80575902
favorite count: 0
has comment: http://stackoverflow.com/comment/80575802
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80576250
answer count: 0
tagged with: google-vision
has comment: http://stackoverflow.com/comment/80632995
type: Question
has title: How to extract name and address from packing labels using regex in python?
has body: I have scanned image and extracted text from image using Google Vision Api. Now i'm facing problem in extracting name and address from scanned text.Through some regex i'm able to detect street code and zipcode from text but not whole address and name. def find_between_r(s, first, last): try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return "" text=""" 17000 AJHshkjadj dakd ext ESTES RICHMOND VA 23230 On Coll UNIFORM STRAIGHT BILL OF LADING - Original - Not Negotiable - Short Form (EXLA, 3901 WEST BROAD STREET Date 10/12/2017 OBOL No W093556Shippers No P.0. No 16846 very shipments, the letters 'COD appear befo For Payment Bill To Bill being paid by Shipper Consignee ENCANTADA RESORT Ken Smith 407-997-3731 Sp tio 3070 SECRET LAKE DR Ruwes Turiff EXLA 105. KISSIMMEE FL 34747 Shipper WINDWARD DESIGN NO ACCESSORIAL SERVICESADDED WITHOUT PRIOR APPROVAL FROM WINDWARD 941-359-0890 1130 COMMERCE BLVD N SARASOTA FL 34243 ird Is M trial E cy P le # O00 000 0000 NOTE: Liability Limitation for loss or damage on this shipment may be applicable. See 49 U.S.C. 14706 (c)(1XA) and (B No. Pkgs HMI Kind or Peak ange. Description of Articles, Special Marks and Exceptions NMFC Declared Valius TW. (Sub Com) | Chass/Rate Ohk22 CT PATIO FURNITURE 1400 200.0 22 1400 Quote# 4867496 APPOINTMENT CHARGE LIFTGATE DELIVERY CHARGE Rade doled val jeclared Excess WARNING Additional dam Mc LiabiRef IOS the d rges Advanced S Received $. to apply NOTE: Wh JOTE: Commodi requnng speci Subject to Sect 7 of Condit this shipmentrequired specific handling marked and to be delivered to the consignee without recourse wning the agreed or declared ith ordinary ignor, the ignor shall sign the property. The agreed or declared value See Sec NMFC 360. follohereby sp Sally stated by the The fibe booxes used thms shipment Innke del shipp 6pecif forth in the box Lake itbour payme freight and all other lawfuland all other repair Consolidated US NMFC | charge the…
score: 0

http://stackoverflow.com/q/46778860
score: 1
upvote count: 1
type: Question
has title: Flask-Security 'SQLAlchemy' object has no attribute 'add' when registering new user
linked to: http://stackoverflow.com/q/46616260
has body: I'm trying to implement the factorial pattern as described here and here. Currently, on my app.py I have this code: def create_app(mode): app = Flask(__name__) app.config.from_pyfile(mode) app.register_blueprint(app_blueprint) from models import db db.init_app(app) user_data_store = SQLAlchemySessionUserDatastore(db, User, Role) security = Security(app, user_data_store) with app.app_context(): db.create_all() return app When I create a new user from the view registger_user.html I receive the following error: AttributeError: 'SQLAlchemy' object has no attribute 'add' File "W:\myApp\envs\myApp_app\lib\site-packages\flask_security\views.py", line 118, in register user = register_user(**form.to_dict()) File "W:\myApp\envs\myApp_app\lib\site-packages\flask_security\registerable.py", line 29, in register_user user = _datastore.create_user(**kwargs) File "W:\myApp\envs\myApp_app\lib\site-packages\flask_security\datastore.py", line 217, in create_user return self.put(user) File "W:\myApp\envs\myApp_app\lib\site-packages\flask_security\datastore.py", line 34, in put self.db.session.add(model) AttributeError: 'SQLAlchemy' object has no attribute 'add' Any idea what might be going on? When I was using the SQLAlchemy with session Link I did have this problem.
downvote count: 0
tagged with: flask-security
tagged with: flask
tagged with: flask-sqlalchemy
duplicate of: http://stackoverflow.com/q/46616260
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/106346165

http://stackoverflow.com/q/46843565
type: UnansweredQuestion
tagged with: tensorflow
type: Question
score: 3
has title: How to define new models in Tensorflow Object Detection API?
has body: Tensorflow Object Detection API is a marvelous resource and a unique piece of well-documented code. Its performance on object detection encourage me to use this API for detecting object poses similar to Poirson et. al. In the case of faster-rcnn meta-architecture, pose detection requires adding a new regression layer along with bbox classification &amp; regression layers and modifying ground truth feeding pipeline. So, is there an easy way to modify the networks? Or should I dig into the code and make proper modifications which seems challenging? Any sample work or guidance will be appreciated.
tagged with: deep-learning
downvote count: 1
has comment: http://stackoverflow.com/comment/81263033
has comment: http://stackoverflow.com/comment/81262949
favorite count: 0
has comment: http://stackoverflow.com/comment/81262868
has comment: http://stackoverflow.com/comment/81263482
has comment: http://stackoverflow.com/comment/81262703
tagged with: python
upvote count: 4
tagged with: object-detection
tagged with: object-detection-api
answer count: 0

http://stackoverflow.com/a/60536661
has comment: http://stackoverflow.com/comment/115626362
type: Answer
downvote count: 2
has body: I think PyOxidizer is what you're looking for.
score: 3
upvote count: 5
answers question: http://stackoverflow.com/q/46811800

http://stackoverflow.com/comment/80608171
has text: @halfer Thank you, I was suspecting this but didn't knew the right search term to google
score: 0
comment on: http://stackoverflow.com/q/46827233
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46773773
has body: I'd suggest to use a context manager instead: from contextlib import contextmanager from server import Server class SystemModule(object): def __init__(self, server, serv_ip, serv_port, username, password, hostname, radio_module_ip, radio_module_port=2323, host_ip='127.0.0.1', host_port=10022): self.server = server self.hostname = hostname self.username = username self.password = password self.serv_ip = serv_ip self.serv_port = serv_port self.radio_module_ip = radio_module_ip self.radio_module_port = radio_module_port self.host_ip = host_ip self.host_port = host_port @contextmanager def connect(): with SSHTunnelForwarder( (self.serv_ip, int(self.serv_port)), ssh_username=self.username, ssh_password=self.password, remote_bind_address=(self.radio_module_ip, int(self.radio_module_port)), local_bind_address=(self.host_ip, int(self.host_port)), # for debugging purposes: # logger=create_logger(loglevel=1), ): with TelnetClient(self.host_ip, int(self.host_port)) as telnet: yield telnet def do_some_stuff(self): with self.connect() as connection: #doing stuff with connection pass
accepted answer of: http://stackoverflow.com/q/46772410
answers question: http://stackoverflow.com/q/46772410
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80516200
has comment: http://stackoverflow.com/comment/80515979
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/80524137
downvote count: 0
has comment: http://stackoverflow.com/comment/80519117
score: 3

http://stackoverflow.com/comment/80467085
comment on: http://stackoverflow.com/q/46760847
has text: @mentalita how exactly would you incorporate isspace()? beacuse if I do it in the for loop, it makes the string a bool and not iterable
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80655414
comment on: http://stackoverflow.com/q/46853511
type: Comment
type: QuestionComment
score: 0
has text: That is from my Main.py file. So, in Main.py in my u = Groovy("test.txt") while test.txt is in the XML_TXT folder.

http://stackoverflow.com/comment/80655277
type: Comment
has text: Thanks for the help!
comment on: http://stackoverflow.com/a/46820161
score: 0
type: AnswerComment

http://stackoverflow.com/q/46865352
has title: How to put 2 variables together
type: UnansweredQuestion
score: -4
type: Question
answer count: 2
downvote count: 4
duplicate of: http://stackoverflow.com/q/1316887
upvote count: 0
has answer: http://stackoverflow.com/a/46865537
has body: On python my current code is: Import random Import sys Import os Print ("Hello! What is your name traveller?") name = sys.stdin.readline () training = ",we are in peril! Start your training now!" first_mission = (name + training) Print (first_mission) It then runs like this: (example name: Dave) Dave ,We are under peril! Start your training now! How do I make it run like this: Dave , We are under peril! Start your training now! Thanks!
favorite count: 0
linked to: http://stackoverflow.com/q/1316887
has comment: http://stackoverflow.com/comment/80678319
has answer: http://stackoverflow.com/a/46865381
tagged with: python

http://stackoverflow.com/comment/80744771
type: Comment
score: 2
has text: If speed is an issue then a regex will probably be the quickest way
comment on: http://stackoverflow.com/q/46898757
type: QuestionComment

http://stackoverflow.com/comment/80683449
type: QuestionComment
has text: [[x for x in it] for it in last] creates a list, and I need to take them one at a time , for example, next(x) for ea iteration in series.index
comment on: http://stackoverflow.com/q/46868000
score: 0
type: Comment

http://stackoverflow.com/comment/80484026
has text: You do have the standard [array](https://docs.python.org/3/library/array.html#module-array) lib in Python which, for all intents and purposes, is a dynamic array. As for the specific behavior you gave to `insert` I doubt it to be valid (in other words, I don't think insert will add nulls automatically). My advice is for you to make your own implementation storing a numpy array (and using its methods to obtain your required behavior).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46766469
type: Comment

http://stackoverflow.com/q/46858668
tagged with: opencl
has title: PyOpenCL 2D array kernel get_global_id(1) error
tagged with: python
tagged with: pyopencl
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm really a newbie with OpenCL. I've taken the example code from this website: http://www.drdobbs.com/open-source/easy-opencl-with-python/240162614?pgno=2 and I've customized it a little bit. I aim to send to the kernel a 4x4 matrix filled with 1 numbers and recover it back from the kernel. I know it's a trivial code, but I need to do this to understand how OpenCL works. The input matrix is this one: [[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 1.]] However, the output I get from the kernel is this one and should be the same as the input: [[ 1. 1. 1. 1.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] This is my full code: import pyopencl as cl from pyopencl import array import numpy as np ## Step #1. Obtain an OpenCL platform. platform = cl.get_platforms()[0] ## It would be necessary to add some code to check the check the support for ## the necessary platform extensions with platform.extensions ## Step #2. Obtain a device id for at least one device (accelerator). device = platform.get_devices()[1] ## It would be necessary to add some code to check the check the support for ## the necessary device extensions with device.extensions ## Step #3. Create a context for the selected device. context = cl.Context([device]) ## Step #4. Create the accelerator program from source code. ## Step #5. Build the program. ## Step #6. Create one or more kernels from the program functions. program = cl.Program(context, """ __kernel void matrix_dot_vector(const unsigned int size, __global const float *matrix, __global float *result) { int x = get_global_id(0); int y = get_global_id(1); result[x + size * y] = matrix[x + size * y]; } """).build() matrix = np.ones((4,4), np.float32) ## Step #7. Create a command queue for the target device. queue = cl.CommandQueue(context) ## Step #8. Allocate device memory and move input data from the host to the device memory. mem_flags = cl.mem_flags #matrix_buf = cl.Buffer(context, mem_flags.READ_ONLY | mem_flags.COPY_HOST_PTR, hostbuf=matri…
type: Question
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/46860200
accepted answer: http://stackoverflow.com/a/46860200
answer count: 1
downvote count: 0
favorite count: 0
tagged with: multidimensional-array

http://stackoverflow.com/comment/80796146
comment on: http://stackoverflow.com/a/46886742
type: AnswerComment
score: 0
type: Comment
has text: ok but i am not allowed to ask question before next five days. so can i send my my code through mail?

http://stackoverflow.com/q/46852156
accepted answer: http://stackoverflow.com/a/46852166
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46852166
has title: How to take all elements except the first k
downvote count: 1
tagged with: python
upvote count: 0
type: AnsweredQuestion
tagged with: list
has body: I'm very new to python and trying to write a concise list-comprehension. Here is what I currently have: def __to_list(i): #return some list k = 3 some_list = #... result = [e for el in some_list for e in __to_list(el) if #take all elements in __to_list(el) except the first k] What is the pythonic way to do this?
score: -1
tagged with: list-comprehension
type: Question

http://stackoverflow.com/comment/80688150
type: Comment
has text: @Parfait none of these. I don't know whether is it possible to create such _image_. Each data-nodeX file contains a set of recordings from some objects in my model. Column's number is ID of an object. Objects can be grouped in populations, so some of the nodes compute object from different populations. I want to create some 'virtual' data file, which looks like it contains all data, but it just accesses to another data file and provides data from there. Kind of collective image of all data.
comment on: http://stackoverflow.com/q/46868623
score: 0
type: QuestionComment

http://stackoverflow.com/q/46801490
type: Question
answer count: 2
upvote count: 1
favorite count: 0
tagged with: ioerror
has title: Python subprocess.Popen error handling with shell=True/False issues
tagged with: python
possible better answer: http://stackoverflow.com/a/48121188
accepted answer: http://stackoverflow.com/a/46801877
tagged with: python-3.x
tagged with: subprocess
has body: I am trying to get some error handling for the following code. In the line subprocess.Popen...... if the shell=True the script will encrypt if a correct file name is given, however there is no file with that name the error code is not printed, but it does show on terminal as no existing file/directory. if I run the shell=False then I am not able to encrypt files but the error message does print. Would it be possible for anyone to explain what I am doing wrong? As I have looked at different posts on here but I still do not understand why it won't work. My guess is that it has something to do with the shell=True portion of the script. SrcDIR ="/home/test/testsource/" DstDIR ="/home/test/testdest/" try: subprocess.Popen(["openssl aes-128-cbc -salt -in " + SrcDIR + str(var1) + " -out " + DstDIR + "enc." + str() + " -k " + str(var2)], shell=True) output3 = ("file " + str(var1) + "created") print(output3) except IOError as reason2: errormsg = ("Error encrypting file due to: \n" + str(reason2)) print(errormsg)
has answer: http://stackoverflow.com/a/46801877
type: AnsweredQuestion
downvote count: 0
tagged with: popen
score: 1
has answer: http://stackoverflow.com/a/48121188

http://stackoverflow.com/a/46841291
score: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46840907
has body: This is what I am going to do, drop_duplicates, you can drop the Notnullvalue by using .drop('Notnullvalue', 1) df['Notnullvalue'] = df.isnull().sum(1) df.sort_values(['id', 'Notnullvalue']).drop_duplicates(['id'], keep='first') Out[15]: id q1 q2 q3 Notnullvalue 0 a 1.0 low NaN 1 4 b 0.0 low 0.0 0 5 c NaN high 0.0 1 6 d 1.0 high 1.0 0 9 e 0.0 low NaN 1
upvote count: 3

http://stackoverflow.com/comment/80610370
score: 0
has text: @Salih, are they in format of int stored in a variable or string stored in a variable ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46831437

http://stackoverflow.com/comment/80612567
type: AnswerComment
type: Comment
has text: @brunodesthuilliers: Point taken. I will think about it more next time! It's hard to take your time in answering here, though. But once you write an elaborate answer there are 5 other shorter ones...
comment on: http://stackoverflow.com/a/46832159
score: 0

http://stackoverflow.com/comment/80622401
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46836518
has text: @roganjosh I think the problem can be expressed as finding the connected components of a graph, where the given pairs are edges and the numbers are nodes. OP, check out networkx.
type: Comment

http://stackoverflow.com/comment/80613213
comment on: http://stackoverflow.com/q/46832125
type: QuestionComment
has text: what about python??
score: 0
type: Comment

http://stackoverflow.com/comment/80695663
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46874271
type: Comment
has text: Ugh... sorry folks - think my brain went on strike there for a moment :)

web-scraping
tags question: http://stackoverflow.com/q/46783142
tags question: http://stackoverflow.com/q/46774291
tags question: http://stackoverflow.com/q/46757494
tags question: http://stackoverflow.com/q/46786303
tags question: http://stackoverflow.com/q/46818622
tags question: http://stackoverflow.com/q/46800125
tags question: http://stackoverflow.com/q/46790044
tags question: http://stackoverflow.com/q/46830631
tags question: http://stackoverflow.com/q/46857087
tags question: http://stackoverflow.com/q/46890431
tags question: http://stackoverflow.com/q/46803077
tags question: http://stackoverflow.com/q/46760671
tags question: http://stackoverflow.com/q/46854971
tags question: http://stackoverflow.com/q/46819433
tags question: http://stackoverflow.com/q/46780979
tags question: http://stackoverflow.com/q/46756154
tags question: http://stackoverflow.com/q/46792079
tags question: http://stackoverflow.com/q/46806994
tags question: http://stackoverflow.com/q/46842966
tags question: http://stackoverflow.com/q/46871133
tags question: http://stackoverflow.com/q/46754929
tags question: http://stackoverflow.com/q/46788988
tags question: http://stackoverflow.com/q/46834418
tags question: http://stackoverflow.com/q/46773924
tags question: http://stackoverflow.com/q/46889274
tags question: http://stackoverflow.com/q/46772932
tags question: http://stackoverflow.com/q/46798527
tags question: http://stackoverflow.com/q/46762881
tags question: http://stackoverflow.com/q/46894569
tags question: http://stackoverflow.com/q/46862719
tags question: http://stackoverflow.com/q/46904369
tags question: http://stackoverflow.com/q/46831150
tags question: http://stackoverflow.com/q/46825189
tags question: http://stackoverflow.com/q/46808831
tags question: http://stackoverflow.com/q/46859242
tag name: web-scraping
tags question: http://stackoverflow.com/q/46755306
tags question: http://stackoverflow.com/q/46878999
tags question: http://stackoverflow.com/q/46889844
tags question: http://stackoverflow.com/q/46766113
tags question: http://stackoverflow.com/q/46890120
tags question: http://stackoverflow.com/q/46776610
tags question: http://stackoverflow.com/q/46792631
type: Tag
tags question: http://stackoverflow.com/q/46860838
tags question: http://stackoverflow.com/q/46798038
tags question: http://stackoverflow.com/q/46751813
tags question: http://stackoverflow.com/q/46864233
tags question: http://stackoverflow.com/q/46889292
tags question: http://stackoverflow.com/q/46834036
tags question: http://stackoverflow.com/q/46758807
tags question: http://stackoverflow.com/q/46892032
tags question: http://stackoverflow.com/q/46901064
tags question: http://stackoverflow.com/q/46877488
tags question: http://stackoverflow.com/q/46804324
tags question: http://stackoverflow.com/q/46786278
tags question: http://stackoverflow.com/q/46885331
tags question: http://stackoverflow.com/q/46896765
tags question: http://stackoverflow.com/q/46898644
tags question: http://stackoverflow.com/q/46768629
tags question: http://stackoverflow.com/q/46833212
tags question: http://stackoverflow.com/q/46850954
tags question: http://stackoverflow.com/q/46751028
tags question: http://stackoverflow.com/q/46844342
tags question: http://stackoverflow.com/q/46786173
tags question: http://stackoverflow.com/q/46762111

http://stackoverflow.com/comment/81262949
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46843565
has text: Thanks alot. I really appreciate the feedback

http://stackoverflow.com/comment/80739977
type: AnswerComment
comment on: http://stackoverflow.com/a/46895371
type: Comment
has text: Are you using python 3 or python 2?
score: 0

http://stackoverflow.com/a/69169597
score: 0
answers question: http://stackoverflow.com/q/46800269
type: Answer
has body: I guess the only way could be printing the variable word_lenght_list, instead of returning it.

http://stackoverflow.com/comment/80547453
has text: IOW, `itertuples` *without* assignment gives `0.08292317390441895`, whereas with `apply` 0.05028414726257324.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46799496
type: Comment

http://stackoverflow.com/a/46820312
answers question: http://stackoverflow.com/q/46820182
type: Answer
score: -4
downvote count: 4
upvote count: 0
has body: My code is as vals = array("i", [-1, 1]) def my_rnd(): return vals[randint(0, 7) % 2]
has comment: http://stackoverflow.com/comment/80588538
has comment: http://stackoverflow.com/comment/80588111

http://stackoverflow.com/q/46834312
tagged with: python
has body: I have two data frames, (FYI created one using Groupby) I want to map data array x which looks like the below Fruit # Apple 2 Pear 5 lemon 1 into Data Frame y which looks like the below Date Fruit Cost Mon Apple 1.00 Mon Pear 2.00 Tues lemon 1.50 Tues Apple 1.00 When mapping into y I want to create new column called #. so the final outcome should look like the below Date Fruit Cost # Mon Apple 1.00 2 Mon Pear 2.00 5 Tues lemon 1.50 1 Tues Apple 1.00 2 I have tried using the below y['#'] = np.where(y['Fruit'].map(x.set_index('Fruit')['#'])) however this kicks out valueerror:Length of values does not match length of index. The length of both data arrays could vary as well depending on the underlying data. Any suggestions would be most appreciated. Thanks
upvote count: 1
type: UnansweredQuestion
tagged with: python-2.7
answer count: 0
downvote count: 0
has title: mapping two data frames using one common column
score: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/46810011
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/80567421
answer count: 1
has title: Tkinter alter child window from parent
has answer: http://stackoverflow.com/a/46813649
has comment: http://stackoverflow.com/comment/80567485
type: AnsweredQuestion
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46813649
tagged with: python
has body: Trying make two windows. One to display an random image, the other has a button which changes to a new random image. Currently if I put a timer in the Display.update_image() and call it in the Display.__init__, I can get it to change picture regularly. But putting the update_image() command in a button on the parent window doesn't work. Is it possible to alter the second window from the first? import tkinter as tk from PIL import Image, ImageTk import random def top_100(): """ Returns a list of the top 100 biggest NZ cities. """ file = open("Top100NZcities.csv") cities = file.readlines() return [city.strip() for city in cities] class UserInt(): def __init__(self): self.root = tk.Tk() self.newWindow = tk.Toplevel(self.root) self.app = Display(self.newWindow) self.random_100_button = tk.Button(text = 'Random from top 100', width = 50, command = self.app.update_image()) self.random_100_button.pack() self.root.mainloop() class Display(): def __init__(self, master): self.root = master #Get the list of cities,. self.cities = top_100() #Set to fullscreen. w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight() self.root.overrideredirect(1) self.root.geometry("%dx%d+0+0" % (w, h)) #Display initial image. self.image_init = ImageTk.PhotoImage(Image.open("black_background.jpg")) self.panel = tk.Label(self.root, image=self.image_init) self.display = self.image_init self.panel.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES) def update_image(self): """ Replaces the screen's current image with a new random image. """ self.city = random.choice(self.cities) self.image_rand = Image.open("NZ maps/{}_nz.png".format(self.city)) #Rescale image to fit window. w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight() self.scale_factor = h / self.image_rand.height self.scaled_image = self.image_rand.resize( (int(self.scale_factor * self.image_rand.width), h), Image.ANTIALIAS ) self.image_display = ImageTk.PhotoImage(self.scaled_image) self.panel.configure(image=self.i…
score: -1
has comment: http://stackoverflow.com/comment/80567470
tagged with: tkinter

http://stackoverflow.com/comment/80705770
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46879257
has text: Installing `apache2` and `apache2-dev` also installed `gcc` and `binutils` it looks like. Clearing up the errors I was having. I saw `libapache2-mod-wsgi-py3` but I wasn't sure if it was cause problems between the existing python installations and the one I did from anaconda. Thanks for your answer.

http://stackoverflow.com/a/46781624
type: Answer
answers question: http://stackoverflow.com/q/46781371
score: 11
has comment: http://stackoverflow.com/comment/137090369
downvote count: 0
has body: It shouldn't "take you hours" to find the bad byte. The error tells you exactly where it is; it's at index 4484 in your input with a value of 0x92; if you did: with open('compounds.dat', 'rb') as f: data = f.read() the invalid byte would be at data[4484], and you can slice as you like to figure out what's around it. In any event, if you just want to ignore or replace invalid bytes, that's what the errors parameter is for. Using io.open (because codecs.open is subtly broken in many ways, and io.open is both faster and more correct): # If this is Py3, you don't even need the import, just use plain open which is # an alias for io.open import io with io.open('compounds.dat', encoding='utf-8', errors='ignore') as f: for line in f: if u"InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line: print(line) will just ignore the invalid bytes (dropping them as if they never existed). You can also pass errors='replace' to insert a replacement character for each garbage byte, so you're not silently dropping data. In this case, 0x92 is the cp1252 encoding of ’, so your file is likely cp1252, and ignoring errors is the wrong solution, you should just use the proper encoding, changing the with statement to: with io.open('compounds.dat', encoding='cp1252') as f:
has comment: http://stackoverflow.com/comment/137092957
upvote count: 11
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/137088009
accepted answer of: http://stackoverflow.com/q/46781371

http://stackoverflow.com/a/49499661
type: Answer
has body: In my case, the error didn't said much So first I handled No handlers could be found for logger "paramiko.transport" with adding at the top of my script import logging logging.getLogger('paramiko.transport').setLevel(logging.DEBUG) paramiko.util.log_to_file("/tmp/example.log") &lt;= to redirect the logs to a file Then I cat /tmp/example.log and found this error https://github.com/pyca/cryptography/issues/4010 (it happens to do with cryptography lib.) Looking around, I found that there are two libs ( enum and enum34 ) and above &gt;&gt;&gt; import cryptography &gt;&gt;&gt; cryptography.__version__ '2.1.3' you need enum34 vs the default that pip is installing ( enum ) Personally I had another problem, that I first installed enum34 globally vs personal with --user so I did pip uninstall enum pip uninstall enum --user pip install enum34 --user That worked for me, hope it helps
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46830620

http://stackoverflow.com/q/46820838
has answer: http://stackoverflow.com/a/46820895
type: Question
has answer: http://stackoverflow.com/a/46821032
has comment: http://stackoverflow.com/comment/80589504
score: 0
answer count: 2
has title: Using a python dictionary of arrays
has comment: http://stackoverflow.com/comment/80589431
has comment: http://stackoverflow.com/comment/80589450
accepted answer: http://stackoverflow.com/a/46821032
tagged with: python
has body: EDIT: I'm sorry, I realized that I didn't give the full question, this edit should contain the full question. I thougth that my previous question was similar enough to the full question that I could get the answer that way without having to add too many additional details, but I was wrong. I have a dictionary params in python, where each entry is a numpy array of some sort. But the arrays in this dictionary are not all of the same shape. Some are size (n,m), some are size (1,m), some still are totally different sizes. I can call a specific number in this dictionary via: params[key][i,j] I need to loop over x of the keys in this dictionary, so I have a loop like: for i in range(0,x): for j in range(0,(dim of 0th axis of array at key x)): for k in range(0,(dim of 1 axis of array at key x)): stuff = f(params['W'+str(i)][i,j]) I want to create a new dictionary paramscheck which will be contain the elements that I'm going to loop over, but the specific numbers in paramscheck will be some function of the corresponding numbers in params. I can't quite figure out the best way to do this. If I write code like: paramscheck = {} for i in range(0,x): for j in range(0,n): for k in range(0,m): paramscheck['W'+str(i)][i,j] = f(params['W'+str(i)][i,j]) Then I will get that I'm outside the range of the index of paramscheck since that dictionary started out empty. If I copy params to paramscheck first and then do the loop with a line like paramscheck = params Then, I won't have issue accessing any entry in paramscheck, but my params dictionary will be modified simultaneously (from what I understand of Python, dictionaries are not actually copied, it just makes an extra label that references to the one underlying dictionary). I've tried something like paramscheck = params.copy() and paramscheck = dict(params), but still the params dictionary is being modified when I go to modify paramscheck. How should I accomplish this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80589398
possible better answer: http://stackoverflow.com/a/46820895

http://stackoverflow.com/a/46757690
has comment: http://stackoverflow.com/comment/80477656
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/80516565
downvote count: 0
has body: We can optimize on memory and performance by working with array data. Approach #1 First off, let's have an array solution to get the correlation coefficients for corresponding elements between two 1D arrays. This would be basically inspired by this post and would look something like this - def corrcoeff_1d(A,B): # Rowwise mean of input arrays &amp; subtract from input arrays themeselves A_mA = A - A.mean(-1,keepdims=1) B_mB = B - B.mean(-1,keepdims=1) # Sum of squares ssA = np.einsum('i,i-&gt;',A_mA, A_mA) ssB = np.einsum('i,i-&gt;',B_mB, B_mB) # Finally get corr coeff return np.einsum('i,i-&gt;',A_mA,B_mB)/np.sqrt(ssA*ssB) Now, to use it , use the same loop but on array data - lcl = 100 ar = tabla.values N = len(ar) out = np.zeros(N) for i in range(N): out[i] = corrcoeff_1d(ar[i:i+lcl,0], ar[i:i+lcl,1]) We can optimize further on performance by pre-computing the rolling mean values as used to compute A_mA in corrcoeff_1d with convolution, but first let's get the memory error out of the way. Approach #2 Here's an almost vectorized approach as we would vectorize most of the iterations except for the leftover slices at the end that won't have proper window lengths. The loop count would be reduced from 97165 to lcl-1 i.e. mere 99. lcl = 100 ar = tabla.values N = len(ar) out = np.zeros(N) col0_win = strided_app(ar[:,0],lcl,S=1) col1_win = strided_app(ar[:,1],lcl,S=1) vectorized_out = corr2_coeff_rowwise(col0_win, col1_win) M = len(vectorized_out) out[:M] = vectorized_out for i in range(M,N): out[i] = corrcoeff_1d(ar[i:i+lcl,0], ar[i:i+lcl,1]) Helper funcs - # https://stackoverflow.com/a/40085052/ @ Divakar def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 n = a.strides[0] return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n)) # https://stackoverflow.com/a/41703623/ @Divakar def corr2_coeff_rowwise(A,B): # Rowwise mean of input arrays &amp; subtract from input arrays themeselves A_mA = A - A.mean(-1,keepdi…
has comment: http://stackoverflow.com/comment/80476615
answers question: http://stackoverflow.com/q/46757318
has comment: http://stackoverflow.com/comment/80476462
type: Answer
has comment: http://stackoverflow.com/comment/80614663
has comment: http://stackoverflow.com/comment/80497769

http://stackoverflow.com/q/46793129
tagged with: pyspark
has title: How to match string with rdd's field name
has comment: http://stackoverflow.com/comment/80534594
score: 0
has comment: http://stackoverflow.com/comment/80535046
answer count: 1
accepted answer: http://stackoverflow.com/a/46794640
has comment: http://stackoverflow.com/comment/80535795
tagged with: python
has body: In my pyspark 2.0.1 version I need to check if particular name[say client] appears in my rdd column name or not &amp; generates an error message if that field, client, is not present in my data fame.Can you please suggest some syntax like below syntax field='client' field not in df.schema.fields: print('field: ', field, "is not available)
has comment: http://stackoverflow.com/comment/80535089
has comment: http://stackoverflow.com/comment/80535029
has comment: http://stackoverflow.com/comment/80533334
has comment: http://stackoverflow.com/comment/80532930
has comment: http://stackoverflow.com/comment/80533133
has answer: http://stackoverflow.com/a/46794640
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/46783572
upvote count: 1
tagged with: gis
type: Question
answer count: 2
tagged with: polygon
downvote count: 0
has body: I would like to create buffered polygons of locations (towns, villages etc) in order to use them for searching in radius. This is what I would like to achieve (units for ilustration): This is how I do it in pyclipper: import pyclipper coordinates = # Array of lat,lng tuples clipper_offset = pyclipper.PyclipperOffset() coordinates = pyclipper.scale_to_clipper(coordinates) clipper_offset.AddPath(coordinates, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) scaled_coordinates = clipper_offset.Execute(1000.0) scaled_coordinates = pyclipper.scale_from_clipper(scaled_coordinates) Number 1000.0 is arbitrary and my question is - how do I calculate the right offset ratio for Execute method, so that the offsetted polygon will approximately represent 10,20 and 50km radius ? Btw. is this the right approach to this problem ?
has answer: http://stackoverflow.com/a/53228173
possible better answer: http://stackoverflow.com/a/50562200
accepted answer: http://stackoverflow.com/a/53228173
tagged with: clipper
has title: Offsetting polygons by meters with clipper
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50562200
tagged with: pyclipper
score: 1

http://stackoverflow.com/q/46777164
answer count: 1
favorite count: 0
tagged with: cookielib
linked to: http://stackoverflow.com/q/17037668
has body: I'm trying to use requests.Session to make some requests and I'd like cookies to not be set. Looking at this question, it appears I can create a cookie policy, and create a cookie jar given that policy to ignore cookies. However, for my requests, it would seem that cookies are still be set: from http import cookiejar class BlockAll(cookiejar.CookiePolicy): """ Blocks all cookies for a given request. """ return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False netscape = True rfc2965 = hide_cookie2 = False def get_cookie_jar(): cookies = cookiejar.CookieJar(policy=BlockAll()) return cookies session = requests.Session() response = session.request( method='post', url='some_url.com', cookies=get_cookie_jar(), .... ) print(response.cookies) &lt;RequestsCookieJar[Cookie(version=0, name='JSESSIONID', value='1234', port=None, port_specified=False, domain='some_url.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]&gt; Is this the correct way to set the policy for this type of request? Any help / links to relevant documentation would be greatly appreciated.
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
has title: Cookie policy getting ignored?
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46777356
accepted answer: http://stackoverflow.com/a/46777356
type: Question
tagged with: cookiejar
upvote count: 1

http://stackoverflow.com/a/46904615
has comment: http://stackoverflow.com/comment/80756145
answers question: http://stackoverflow.com/q/46904575
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80756233
has comment: http://stackoverflow.com/comment/80756504
has comment: http://stackoverflow.com/comment/80756548
type: Answer
score: 3
has body: Try groupby + apply: try_df.groupby("ID")["J1"].apply(lambda x: pd.qcut(x, 4, ["Q1","Q2","Q3","Q4"])) 0 Q1 1 Q1 2 Q2 3 Q3 4 Q4 5 Q1 6 Q1 7 Q2 8 Q3 9 Q4 10 Q1 11 Q1 12 Q2 13 Q3 14 Q4 Name: J1, dtype: category Categories (4, object): [Q1 &lt; Q2 &lt; Q3 &lt; Q4]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46904575

http://stackoverflow.com/comment/80656223
comment on: http://stackoverflow.com/q/46854330
has text: @Jean-FrançoisFabre works for python3 not for python 2. The code I am running only works for python 2.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46892061
downvote count: 0
tagged with: keras
has title: How to train Keras model with Image AND separate value as input? Mixed input
has answer: http://stackoverflow.com/a/46893017
tagged with: reinforcement-learning
tagged with: deep-learning
answer count: 1
favorite count: 0
has body: I am building a reinforcement learning agent for my autonomous copter. My Keras (1.0.7) model for pure image input looks like this: image_model = Sequential() image_model.add(Convolution2D(32, 8, 8, subsample=(4, 4), input_shape=(1, 120, 215))) image_model.add(Activation('relu')) image_model.add(Convolution2D(64, 4, 4, subsample=(2, 2))) image_model.add(Activation('relu')) image_model.add(Convolution2D(64, 3, 3, subsample=(1, 1))) image_model.add(Activation('relu')) image_model.add(Flatten()) image_model.add(Dense(512)) image_model.add(Activation('relu')) image_model.add(Dense(nb_actions)) image_model.add(Activation('linear')) In order to learn properly I have to pass some additional values to my model besides the pure image (orientation, position of my copter etc.). I guess I have to streams of network architecture that result in one single output layer or several output layers. image_model = Sequential() image_model.add(Convolution2D(32, 8, 8, subsample=(4, 4), input_shape=input_shape)) image_model.add(Activation('relu')) image_model.add(Convolution2D(64, 4, 4, subsample=(2, 2))) image_model.add(Activation('relu')) image_model.add(Convolution2D(64, 3, 3, subsample=(1, 1))) image_model.add(Activation('relu')) image_model.add(Flatten()) image_model.add(Dense(512)) image_model.add(Activation('relu')) value_model = Sequential() value_model.add(Flatten(input_shape=values)) value_model.add(Dense(16)) value_model.add(Activation('relu')) value_model.add(Dense(16)) value_model.add(Activation('relu')) value_model.add(Dense(16)) value_model.add(Activation('relu')) model = Sequential() #merge together somehow model.add(Dense(nb_actions)) model.add(Activation('linear')) The Merge API of Keras are meant for merging image and image in my understanding. How do I bring together these different type of inputs? Edit: Here my attempt on what I mean to do. I want to train my agent at each time step with one image and one separate value. Since I think that the I should not pass the sep…
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: image-processing
type: Question

http://stackoverflow.com/comment/80449715
type: AnswerComment
score: 0
has text: Have you tried submitting this form? I think it will get prefilled since you pass request.POST as argument to the form. Look at action attribute of form
type: Comment
comment on: http://stackoverflow.com/a/46751584

http://stackoverflow.com/a/46852645
type: AcceptedAnswer
has body: Try: content = [] with open(fname) as f: content.append([f.readline()]) Also as a one liner: content = [[line] for line in open('fname')] Note that '\n' can be removed with str.rstrip('\n'). You can further post process your lines in order to drop all empty lines (e.g. lines that contain only '\n') or insert it as an if statement in the list comprehension: content = [[line] for line in open('fname') if line != '\n']
has comment: http://stackoverflow.com/comment/80653683
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46852081
accepted answer of: http://stackoverflow.com/q/46852081

http://stackoverflow.com/comment/80466625
type: AnswerComment
has text: I have thought that `nest("foo", 0)` must be `"foo"`, not `["foo"]`.
type: Comment
comment on: http://stackoverflow.com/a/46760533
score: 0

http://stackoverflow.com/a/50351885
answers question: http://stackoverflow.com/q/46779745
score: 0
type: Answer
has body: The package psycopg2 is not pure Python, so it will not work with Glue. From the setup.py: If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. From the AWS Glue documentation: You can use Python extension modules and libraries with your AWS Glue ETL scripts as long as they are written in pure Python. C libraries such as pandas are not supported at the present time, nor are extensions written in other languages.

http://stackoverflow.com/comment/80529161
score: 0
has text: @DanielRoseman I understand, the best way is through `form_valid` in my case 'cuz I use CBV. I updated my post.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46790396

http://stackoverflow.com/q/46821170
upvote count: 1
tagged with: python
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80589790
has comment: http://stackoverflow.com/comment/80589850
tagged with: numpy
has body: I just noticed that if np.random.choice is used on a list that contains both strings and integers, then when integers are returned, they are coerced to strings. Is this intended behavior? e.g. &gt;&gt;&gt;numpy.random.choice([1,2,3,4]) 1 but &gt;&gt;&gt;numpy.random.choice(['a',1,2,3,4]) '1' I guess I can do my_list[np.random.choice(range(len(my_list)))], but that seems rather ugly.
has comment: http://stackoverflow.com/comment/80589862
has comment: http://stackoverflow.com/comment/80589775
type: UnansweredQuestion
has title: Is np.random.choice supposed to coerce?
tagged with: random
has comment: http://stackoverflow.com/comment/80591836
tagged with: coercion
favorite count: 0
has answer: http://stackoverflow.com/a/46822909
type: Question
score: 0

http://stackoverflow.com/q/46762791
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: This is the structure I'm trying to accomplish with my code. I want to use registry.filter and registry.action to load in filters and actions for an application I'm building. I recognize that I could just split them up into two different decorators. def registry(): def filter(*expected_args): def decorator(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return decorator def filter(*expected_args): def decorator(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return decorator @registry.filter({ }) def my_filter(): print "Hello World!" @registry.action({ }) def my_action(): print "Hello World!" if __name__ == "__main__": my_filter() my_action() Whenever I run my code I receive this error: Traceback (most recent call last): File "/Users/chris/Documents/Content-Management/registry.py", line 19, in &lt;module&gt; @registry.filter({ AttributeError: 'function' object has no attribute 'filter'
has title: How can I have decorator.other?
has comment: http://stackoverflow.com/comment/80471024
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80470821
tagged with: python-decorators

http://stackoverflow.com/comment/80655568
comment on: http://stackoverflow.com/a/46841241
score: 0
type: AnswerComment
type: Comment
has text: I'm looking for a solution that fits more than just 2 points. If I print out pts[:,0], I get a 1d array of scalars that looks like this: [10,30,value,value,value..] This should meet the criteria for broadcasting.

http://stackoverflow.com/comment/80727534
type: AnswerComment
comment on: http://stackoverflow.com/a/46889644
has text: I believe better you check all model that depend on the one you renamed
type: Comment
score: 0

http://stackoverflow.com/q/46799588
answer count: 0
score: 1
tagged with: group-by
type: Question
downvote count: 0
has title: Python Pandas calculate funnel
tagged with: pandas
upvote count: 1
favorite count: 0
tagged with: pivot
type: UnansweredQuestion
tagged with: python
has body: Working with the python pandas dataframe df: Customer_ID | Transaction_ID | Item_ID | date | trans_nr ABC 2017-04-12-333 X8973 2017-04-12 1 ABC 2017-04-12-333 X2468 2017-04-12 1 ABC 2017-05-22-658 X2906 2017-05-22 2 ABC 2017-05-22-757 X8790 2017-05-22 2 ABC 2017-07-13-864 X8790 2017-07-13 3 BCD 2017-08-11-879 X2346 2017-08-11 1 BCD 2017-08-11-879 X2468 2017-08-11 1 CDE 2017-03-05-879 X8973 2017-03-05 1 CDE 2017-05-22-879 X2468 2017-05-22 2 CDE 2017-10-15-879 X2346 2017-10-15 3 I need to basically pivot it, to create the item funnel - in other words, understand how many people bought each item in each visit and which item they bought next. This is the output I am looking for: item_1trans|count_customer|item_2trans|count_customer|item_3trans|count_customer X8973 2 X2906 1 X8790 1 X8790 1 X8790 1 X2468 1 X2346 1 X2468 2 X2906 1 X8790 1 X8790 1 X8790 1 X2346 1 I manage to accomplish this with some ugly code: df_first = df.loc[df['trans_nr'] == 1].copy() df_first = df_first.rename(columns={'Item_ID': 'item_1trans'}) df_second = df.loc[df['trans_nr'] == 1].copy() df_second = df_second.rename(columns={'Item_ID': 'item_2trans'}) df_third = df.loc[df['trans_nr'] == 1].copy() df_third = df_third.rename(columns={'Item_ID': 'item_3trans'}) df_step1 = pd.merge(df_first,df_second,how='outer',on=['Customer_ID']) df_final = pd.merge(df_step1,df_third,how='outer',on=['Customer_ID']) pd.pivot_table(df_final,index= \ ['item_1trans','item_2trans','item_3trans'],values=["Customer_ID"],\ aggfunc=lambda x: len(x.unique())).to_csv('test.csv') But there has to be a smoother way.

http://stackoverflow.com/comment/80655087
score: 1
comment on: http://stackoverflow.com/q/46852824
type: QuestionComment
type: Comment
has text: Anyway, using `selector.register(s, EVENT_WRITE)` should solve your problem. In that case, `selector` holds the reference to the socket object.

http://stackoverflow.com/q/46901926
has comment: http://stackoverflow.com/comment/80750665
tagged with: python
possible better answer: http://stackoverflow.com/a/46902168
has answer: http://stackoverflow.com/a/46902168
has comment: http://stackoverflow.com/comment/80750807
score: 0
has body: I am trying to ask the user what they want to name a file that is about to be created on my desktop. When I try to add the variable to the string, it gives me this error: appendFile = open('%s.txt', 'a') % cusername TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'str' Here is my program: def CNA(): cusername = input("Create username\n&gt;&gt;") filehandler = open("C:/Users/CJ Peine/Desktop/%s.txt", "w") % cusername filehandler.close() cpassword = input("Create password\n&gt;&gt;") appendFile = open('%s.txt', 'a') % cusername appendFile.write(cpassword) appendFile.close() print ("Account Created") How do I make the variable compatible to the string?
linked to: http://stackoverflow.com/q/4960208
has answer: http://stackoverflow.com/a/46901982
has comment: http://stackoverflow.com/comment/80750593
has title: why is this type of variable not compatible with string?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80750645
accepted answer: http://stackoverflow.com/a/46901982
type: Question
answer count: 2

http://stackoverflow.com/comment/80512172
score: 1
comment on: http://stackoverflow.com/q/46782871
type: Comment
type: QuestionComment
has text: can you also paste the initial text content ?

http://stackoverflow.com/comment/80521948
comment on: http://stackoverflow.com/q/46787674
type: QuestionComment
type: Comment
score: 1
has text: Why do you need to add parameters to enum members? What exactly are you trying to do?

http://stackoverflow.com/comment/80449042
has text: Greenstick won't get a notification for your comment because he hasn't posted on this page. I guess you could put a comment on the answer he wrote, politely directing him here, but please bear in mind that he's under no obligation to help you with this.
comment on: http://stackoverflow.com/q/46751428
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46887030
has answer: http://stackoverflow.com/a/46887085
accepted answer: http://stackoverflow.com/a/46887085
tagged with: python-3.x
has body: So I wrote a small project to practice objects: import random import os import sys class Animal: __name = "" __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_height(self, height): self.__height = height def get_height(self): return self.__height def set_weight(self, weight): self.__weight = weight def get_weight(self): return self.__weight def set_sound(self, sound): self.__sound = sound def get_sound(self): return self.__sound def get_type(self): print("animal") def toString(self): return "{} is {} cm tall and {} kilograms and says {}".format(self.__name, self.__height, self.__weight, self.__sound) cat = Animal('Whiskers', 33, 7, 'Meow') print(cat.toString()) class Dog(Animal): __owner = "" def __init__(self, name, height, weight, sound, owner): self.__owner = owner super(Dog, self).__init__(name, height, weight, sound) def set_owner(self, owner): self.__owner = owner def get_owner(self): return self.__owner def get_type(self): print("Dog") def toString(self): return "{} is {} cm tall and {} kilograms and says {}. His owner is {}".format(self.__name, self.__height, self.__weight, self.__sound, self.__owner) pitbull = Dog('James', 70, 30, 'woef', 'john') print(Dog.toString()) It outputs Whiskers is 33 cm tall and 7 kilograms and says Meow Traceback (most recent call last): File "C:/Users/*****/AppData/Local/Programs/Python/Python36-32/practice object oriented programming.py", line 78, in &lt;module&gt; print(Dog.toString()) TypeError: toString() missing 1 required positional argument: 'self' why is this? It output the cat correctly even though I didn't define 'self'. Why doesn't it output dog correctly? I have tried multiple things I found here, but I have defined the function and I didn't have to define 'self' with the cat. Any help would be appreciated…
tagged with: python
has answer: http://stackoverflow.com/a/46887152
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80721153
type: Question
has title: TypeError: toString() Missing 1 required positional argument: 'self'
possible better answer: http://stackoverflow.com/a/46887152
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80721212

http://stackoverflow.com/comment/80588526
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46820496
has text: Do you want a list of indexes where the word fields appears?
score: 0

http://stackoverflow.com/comment/91262676
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52155198
has text: It is a very efficient way. Thank you.

http://stackoverflow.com/q/46793532
answer count: 1
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/29909515
has title: seaborne jointplot - how to get rectangular plot
tagged with: seaborn
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/80545472
type: Question
score: -1
has answer: http://stackoverflow.com/a/46799699
has body: I came across this post which shows how to get a rectangular plot. The code runs. But I was wondering how to print this image on python screen? i tried `grid' but it prints as below grid Out[91]: &lt;seaborn.axisgrid.JointGrid at 0x1fbb7e76cf8&gt;
upvote count: 0

http://stackoverflow.com/q/46794381
has body: I'm trying to write a program that takes in a pcap file, filters the packet data through the application tshark, and outputs the data into a dictionary, separating the individual packets. I'm having problems with the seperation segment. Here is basically what I have so far: #example data input records = ["Jamie,20,12/09/1997,Henry,15,05/12/2002,Harriot,22,11/02/1995"] dict = {} list1 = str(records).split(',') i = 0 #seperates list into sublists with length "3" list1 = [list1[i:i + 3] for i in range(0, len(list1), 3)] #places the sublists into a dictionary for i in range (0,len(fields)): #places the sublists into dictionary dict[i] = list1[i][0].split(',') + list1[i][1].split(',') + list1[i][2].split(',') print(dict) The output looks like this: {0: ["['Jamie", '20', '12/09/1997'], 1: ['Henry', '15', '05/12/2002'], 2: ['Harriot', '22', "11/02/1995']"]} I understand my code is quite flawed and messy. In order to store get more data from each row, you need to manually add each additional field to the dictionary along with having to change where to split the list. Any help on how to better automate this process, considering an input of varying size, would be greatly appreciated. If I explained my problem poorly just ask. EDIT: Here is the code I use to call tshark. The input for the previous code is "out" converted to string. The name, age and date of birth in the previous example represents ip source, ip destination and protocol. filters = ["-e","ip.src"," -e ","ip.dst"," -e ","_ws.col.Protocol] #Specifies the metadeta to be extracted tsharkCall = ["tshark.exe", "-r", inputpcap, "-T", "fields", filters] tsharkProc = subprocess.Popen(tsharkCall, stdout=subprocess.PIPE) out, err= tsharkProc.communicate()
type: AnsweredQuestion
score: 3
tagged with: pcap
upvote count: 3
has comment: http://stackoverflow.com/comment/80536085
tagged with: organization
has answer: http://stackoverflow.com/a/46794821
type: Question
has comment: http://stackoverflow.com/comment/80535573
downvote count: 0
has comment: http://stackoverflow.com/comment/80535719
has comment: http://stackoverflow.com/comment/80535480
tagged with: filter
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80535532
tagged with: python
has comment: http://stackoverflow.com/comment/80535580
has comment: http://stackoverflow.com/comment/80535614
accepted answer: http://stackoverflow.com/a/46794821
has title: How to effectively separate data inputs of varying sizes?

http://stackoverflow.com/q/46806457
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
answer count: 1
accepted answer: http://stackoverflow.com/a/46806619
upvote count: 1
has body: I'm working with a web framework and I'm using variables from Python into Javascript code. I get next array in Python, which can contain more than one cell with dictionaries inside it: [[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]] I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next: var X = JSON.parse(("").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\"")); Where X is the Python variable. Unfortunately, this does not run with the array I wrote above. How can I do that? Thanks beforehand, Regards.
has answer: http://stackoverflow.com/a/46806619
has title: Get data from an array of dictionaries in Javascript
tagged with: arrays
tagged with: javascript
has comment: http://stackoverflow.com/comment/80560012
has comment: http://stackoverflow.com/comment/80560015
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80562325
score: 1

http://stackoverflow.com/q/46818148
has title: How to convert string to number in python
linked to: http://stackoverflow.com/q/4289331
linked to: http://stackoverflow.com/q/39239506
answer count: 1
has comment: http://stackoverflow.com/comment/80585058
duplicate of: http://stackoverflow.com/q/39239506
favorite count: 0
has comment: http://stackoverflow.com/comment/80583758
has comment: http://stackoverflow.com/comment/80583780
tagged with: python
has comment: http://stackoverflow.com/comment/80583693
has body: I have a column in a dataframe named 'term'. its value is ('36 months', '60 months', '36 months', '36 months', '60 months') Now I want to convert that column to numeric like (36,60,36,36,60) How can I do that?
upvote count: 2
has comment: http://stackoverflow.com/comment/80583790
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/46818242
type: Question
downvote count: 5

http://stackoverflow.com/q/46885052
type: AnsweredQuestion
upvote count: 0
has body: I am trying to show a Bokeh plot in Firefox. There are quite many sub-graphs (approximately 200), each showing 1-4 objects. I am receiving in Firefox: "A webpage is slowing down your browser." Some notes: After rebooting, it works fine for a couple of times. I am behind a corporate proxy. I ask myself if it may be the cause. Some JavaScript and CSS is being loaded from cnb.pydata.com.
has title: Bokeh plots are very difficult to load
tagged with: bokeh
type: Question
has comment: http://stackoverflow.com/comment/80718012
has comment: http://stackoverflow.com/comment/80717897
tagged with: javascript
has comment: http://stackoverflow.com/comment/80735402
accepted answer: http://stackoverflow.com/a/46885294
has comment: http://stackoverflow.com/comment/80718043
answer count: 1
favorite count: 0
tagged with: python-3.x
downvote count: 3
has answer: http://stackoverflow.com/a/46885294
score: -3
tagged with: python

http://stackoverflow.com/comment/80715941
has text: Then I would like to apologize for the sarcasm in my answer, as it was not intended.
type: QuestionComment
comment on: http://stackoverflow.com/q/46847066
score: 0
type: Comment

http://stackoverflow.com/comment/80523607
comment on: http://stackoverflow.com/q/46783775
type: Comment
type: QuestionComment
has text: You can use the [commandPort](http://download.autodesk.com/us/maya/2010help/commandspython/commandPort.html) command in maya .
score: 1

http://stackoverflow.com/a/46842260
has body: Using groupby + head: g = df.groupby('name', as_index=False, group_keys=False)\ .apply(lambda x: x.head(-1) if x.shape[0] &gt; 1 else x) print(g) name gender count 0 A M 3 1 A F 2 3 B NaN 2 4 C F 4 5 D M 5
answers question: http://stackoverflow.com/q/46842225
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/60284493
type: Answer
answers question: http://stackoverflow.com/q/46825978
has body: I inquired many solutions, some of them worked but It affected the calculous used this one and it will skip the line that is causing the error: pd.read_csv(file,engine='python', error_bad_lines=False) #engine='python' provides a better output
score: 5
upvote count: 6
has comment: http://stackoverflow.com/comment/107390150
downvote count: 1
has comment: http://stackoverflow.com/comment/136674638

http://stackoverflow.com/comment/80721542
type: QuestionComment
comment on: http://stackoverflow.com/q/46886903
has text: This question might help: https://stackoverflow.com/q/472575/5311735
score: 0
type: Comment

http://stackoverflow.com/comment/122862961
has text: For anyone that comes across this, completely ignore this post, it's making recommendations with no consideration of context. Super high quality PRNGs are pretty terrible for procedural generation like this and trying to use them will introduce more problems than it solves. Look up how to use something like xxHash instead.
comment on: http://stackoverflow.com/a/46835720
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80747925
type: Comment
comment on: http://stackoverflow.com/a/46899853
score: 0
has text: Thanks a lot. That worked except few changes to the code at two places
type: AnswerComment

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/46789284
type: Tag
tags question: http://stackoverflow.com/q/46903363

http://stackoverflow.com/q/46880494
has comment: http://stackoverflow.com/comment/80708725
favorite count: 0
has answer: http://stackoverflow.com/a/46880513
has title: Why does pd.DataFrame with pd.isnull fail?
type: Question
upvote count: 1
tagged with: python
answer count: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/46880513
downvote count: 0
score: 1
tagged with: pandas
type: AnsweredQuestion
has body: tt = pd.DataFrame({'a':[1,2,None,3],'b':[None,3,4,5]}) bb=pd.DataFrame(pd.isnull(tt).astype(int), index = tt.index, columns=map(lambda x: x + '_'+'NA',tt.columns)) bb I want create this dataframe with pd.isnull(tt), and the columns name contain the NA, but why does this fail?

apache-spark
tags question: http://stackoverflow.com/q/46749342
tags question: http://stackoverflow.com/q/46799511
tags question: http://stackoverflow.com/q/46763249
tags question: http://stackoverflow.com/q/46779745
tags question: http://stackoverflow.com/q/46844000
tags question: http://stackoverflow.com/q/46884276
tags question: http://stackoverflow.com/q/46822852
tags question: http://stackoverflow.com/q/46797086
tags question: http://stackoverflow.com/q/46854905
tags question: http://stackoverflow.com/q/46796108
tags question: http://stackoverflow.com/q/46893539
tags question: http://stackoverflow.com/q/46825445
tags question: http://stackoverflow.com/q/46813283
tags question: http://stackoverflow.com/q/46834126
tags question: http://stackoverflow.com/q/46817453
tag name: apache-spark
tags question: http://stackoverflow.com/q/46858172
tags question: http://stackoverflow.com/q/46829276
tags question: http://stackoverflow.com/q/46817704
tags question: http://stackoverflow.com/q/46809200
tags question: http://stackoverflow.com/q/46833883
tags question: http://stackoverflow.com/q/46838488
tags question: http://stackoverflow.com/q/46824495
tags question: http://stackoverflow.com/q/46749327
tags question: http://stackoverflow.com/q/46855520
tags question: http://stackoverflow.com/q/46793528
tags question: http://stackoverflow.com/q/46895876
type: Tag
tags question: http://stackoverflow.com/q/46853123
tags question: http://stackoverflow.com/q/46754149
tags question: http://stackoverflow.com/q/46751531
tags question: http://stackoverflow.com/q/46769464

http://stackoverflow.com/q/46760465
has answer: http://stackoverflow.com/a/46760913
tagged with: python
has body: How to decode this string in python? title = '&amp;#70;&amp;#97;&amp;#115;&amp;#116;&amp;#32;&amp;#38;&amp;#32;&amp;#70;&amp;#117;&amp;#114;&amp;#105;&amp;#111;&amp;#117;&amp;#115;&amp;#32;&amp;#54;' to get: Fast &amp; Furious 6 Thank you!
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
tagged with: decode
has answer: http://stackoverflow.com/a/46760517
accepted answer: http://stackoverflow.com/a/46760517
possible better answer: http://stackoverflow.com/a/46760913
has title: HTML string decode in python
tagged with: python-2.7
answer count: 2
downvote count: 0
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/80466855

http://stackoverflow.com/comment/90461736
comment on: http://stackoverflow.com/a/46833531
type: Comment
score: 2
has text: Upvoted, useful stuff. Is there a way of doing this when creating the environment? does not seem the right thing to do with automated deployment
type: AnswerComment

http://stackoverflow.com/q/46803465
possible better answer: http://stackoverflow.com/a/50983980
has body: I'm trying to read a video file in opencv (python 2.7), and I just copied the example in the opencv tutorial, but nothing happens: import numpy as np import cv2 cap = cv2.VideoCapture('input.mp4') while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() The function cap.isOpened always returns FALSE.I have already tried to use absolute path in the argument of VideoCapture, but I still get the same result. What am I getting wrong?
type: Question
tagged with: opencv
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/46804895
has answer: http://stackoverflow.com/a/50983980
accepted answer: http://stackoverflow.com/a/46804895
has title: Read a video in opencv (python)
has comment: http://stackoverflow.com/comment/80555332
tagged with: python
has answer: http://stackoverflow.com/a/50738130
has comment: http://stackoverflow.com/comment/80555047
type: AnsweredQuestion

http://stackoverflow.com/comment/80675359
type: AnswerComment
has text: @Bharathshetty, suggested another alternative, if you want to compare.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46863713

http://stackoverflow.com/q/46864740
score: 11
has answer: http://stackoverflow.com/a/52192431
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46864964
has title: Selecting a subset using dropna() to select multiple columns
downvote count: 0
has answer: http://stackoverflow.com/a/46864779
accepted answer: http://stackoverflow.com/a/46864779
possible better answer: http://stackoverflow.com/a/52192431
has comment: http://stackoverflow.com/comment/80676997
answer count: 3
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80677019
favorite count: 0
upvote count: 11
has body: I have the following DataFrame: df = pd.DataFrame([[1,2,3,3],[10,20,2,],[10,2,5,],[1,3],[2]],columns = ['a','b','c','d']) From this DataFrame, I want to drop the rows where all values in the subset ['b', 'c', 'd'] are NA, which means the last row should be dropped. The following code works: df.dropna(subset=['b', 'c', 'd'], how = 'all') However, considering that I will be working with larger data frames, I would like to select the same subset using the range ['b':'d']. How do I select this subset?

clr
type: Tag
tag name: clr
tags question: http://stackoverflow.com/q/46768358

http://stackoverflow.com/q/46869214
has title: Replace a list of timestamps in a pandas dataframe with a list of our for every timestamp in every row
score: 0
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/46866480
tagged with: python
tagged with: timestamp
has body: I have a column in a pandas dataframe that consist of lists containing timestamps. I want to replace this list of timestamps with a list of the hour of each timestamp for every row. Below is an example df = pd.DataFrame( {'id':[1,2], 'time':[ [2017-09-05 03:34:51,2016-03-07 05:24:55], [2016-02-06 03:14:21,2014-08-09 09:12:44, 2011-05-02 07:43:21] ] }) I would like a new column named 'hour' where df['hour'] = [ [3,5], [3,9,7] ] I tried different functionalities using map() and apply() but nothing produced the desired outcome, any help is very much appreciated.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46869229
accepted answer: http://stackoverflow.com/a/46869229
type: Question
tagged with: time-series

http://stackoverflow.com/comment/80689928
comment on: http://stackoverflow.com/q/46871264
type: Comment
type: QuestionComment
score: 1
has text: why don't you load content of file all at once and process and write it back after processing it? writing into file frequently makes your code slow.

http://stackoverflow.com/q/46778936
answer count: 1
downvote count: 0
tagged with: python-asyncio
tagged with: exception
has answer: http://stackoverflow.com/a/46779849
tagged with: python
has title: How to catch exceptions in a python run_in_executor method call
tagged with: asynchronous
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46779849
type: AnsweredQuestion
score: 10
upvote count: 10
type: Question
has body: How can i raise the exception in the run_long_thing() function called with the run_in_executor? It looks like it is being swallowed. I don't need the result of the function in the blocking code. It is basically a fire and forget function, but still i need to catch the exceptions if there are any... import asyncio import time def fire_and_forget(task, *args, **kwargs): loop = asyncio.get_event_loop() if callable(task): #if threadpoolworker is set to None, #the max_workers will default to the number of processors on the machine, multiplied by 5 return loop.run_in_executor(None, task, *args, **kwargs) else: raise TypeError('Task must be a callable.') async def run_long_thing(sleep): print("Doing long thing... {:}".format(sleep)) time.sleep(sleep) print("Done doing long thing. {:}".format(sleep)) raise Exception("sh*t happens") def do_it(): print("Starting my main thing...") print("Calling my long thing...") for i in range(0,10,1): try: fire_and_forget(run_long_thing, i) print(i) print("Pom pi dom...") time.sleep(0.1) print("POOOOM Pom pi dom...") except: print("can i see the sh*t?") do_it()

http://stackoverflow.com/comment/80541182
type: AnswerComment
has text: maybe `df.value.clip(100, 200) // 25 * 0.25`?
type: Comment
score: 2
comment on: http://stackoverflow.com/a/46797240

http://stackoverflow.com/q/46758958
downvote count: 0
possible better answer: http://stackoverflow.com/a/48367811
tagged with: ubuntu
has answer: http://stackoverflow.com/a/48367811
favorite count: 0
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/47225419
has title: ImportError: No module named 'deployment'
has body: Not sure whether I should be posting this on askubuntu or here. I am trying to perform object detection using Tensorflow. I am therefor following this tutorial (this link shows the exact issue I am facing). When running this script, I get this error: $ python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config Traceback (most recent call last): File "train.py", line 51, in &lt;module&gt; from object_detection import trainer File "/usr/local/lib/python3.5/dist-packages/object_detection-0.1-py3.5.egg/object_detection/trainer.py", line 33, in &lt;module&gt; from deployment import model_deploy ImportError: No module named 'deployment According to the info I found online and the video I linked above I have to execute this command: export PYTHONPATH=$PYTHONPATH:`pwd`/slim While being in the tensorflow/model/ directory. Yet, it doesn't solve my issue. And I don't really know what I should check in order to find out what is causing this persistent issue. Could someone help me out? Thanks EDIT: exactly what I do: (tensorflow) xxx@yyy-ThinkPad-X200:~/Downloads/models/research/build/lib/object_detection$ cd ../../../../ (tensorflow) xxx@yyy-ThinkPad-X200:~/Downloads/models$ export PYTHONPATH=$PYTHONPATH:`pwd`/slim (tensorflow) xxx@yyy-ThinkPad-X200:~/Downloads/models$ cd ~/Downloads/models/research/build/lib/object_detection (tensorflow) xxx@yyy-ThinkPad-X200:~/Downloads/models/research/build/lib/object_detection$ python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config Traceback (most recent call last): File "train.py", line 51, in &lt;module&gt; from object_detection import trainer File "/usr/local/lib/python3.5/dist-packages/object_detection-0.1-py3.5.egg/object_detection/trainer.py", line 33, in &lt;module&gt; from deployment import model_deploy ImportError: No module named 'deployment' (tensorflow) xxx@yyy-ThinkPad-X200:~/Downloads/models/research/build/lib/obje…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49076413
has answer: http://stackoverflow.com/a/46759001
upvote count: 5
type: Question
score: 5
has answer: http://stackoverflow.com/a/47225419

http://stackoverflow.com/a/46773711
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46772858
has body: Main issue with threading is making sure nothing will explode, or if something will explode you have that scenario covered and you are willingly letting it explode. With that in mind and the fact that there is no feasible way for automating that part of threading with current architecture of operating systems without sacrificing benefits of multithreading let us get into your choices and correctness of your implementation. def construct_list(read_file, backup): with open(read_file) as read_obj: backup.put(read_obj.readlines()) backup.task_done() Okay, you seem to have this thing backwards. If you read something and based on that you post data/command/anything to queue for process you don't call task_done() since you only requested a task to be done. When you post such requests you don't perform that task. Second issue here is writing those commands to queue with no timeout. By default queue.put() is blocking and has no timeout, this is not a mistake, I'm just pointing this out to make sure this is conscious decision and it has to be taken into account when extending functionality of this example. read_thread.start() read_thread.join() Well... This actually defeats whole idea of multithreading. Idea being able to perform multiple tasks in parallel, with call to join() here you are blocking main thread until worker thread finishes. Which basically means you are creating a thread and performing all operations twice as slow as with a single thread. Whole idea of using queue is for multiple threads to communicate with each other WHILE THEY BOTH ARE RUNNING. You shouldn't join other thread in such way, just do it after you no longer need it and queue has been processed. while backup_list.empty() is False: print(backup_list.get()) First you shouldn't assume that if empty() returns False your get() call will not block. If main thread was GUI thread or any other variant that needs continuous running you would want to call it with non-blocking calls and deal with non-processi…
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46772858
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80494837

http://stackoverflow.com/comment/80585403
type: QuestionComment
has text: amended but still makes no difference
score: 0
comment on: http://stackoverflow.com/q/46818539
type: Comment

http://stackoverflow.com/a/46853165
answers question: http://stackoverflow.com/q/46850954
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80663923
has body: Indeed, I've tested the case and it seems that BeautifulSoup does not give the expected result. Use lxml.html library instead: import lxml.html as html import requests genus = 'Parsonsia' species = 'straminea' page = requests.get("https://www.anbg.gov.au/cgi-bin/apiiName?030=" + genus + "+" + species) root = html.fromstring(page.content) for td in root.xpath("//td[contains(text(),'Taken at')]"): print(td.text_content()) The actual output: Taken at. ANBG nursery Taken at. ANBG Taken at. ANBG Taken at. Robertson to Belmore Falls Road, NSW Taken at. Robertson to Belmore Falls Road, NSW Taken at. Robertson to Belmore Falls Road, NSW Taken at. Robertson to Belmore Falls Road, NSW Taken at. Back Hillston Rd, near Goolgowi, NSW Taken at. shoreline, Tuross Head, NSW Taken at. shoreline, Tuross Head, NSW Taken at. shoreline, Tuross Head, NSW Taken at. shoreline, Tuross Head, NSW Taken at. shoreline, Tuross Head, NSW Taken at. Tuross Head, near Memorial Gardens, Tuross, NSW Taken at. Tuross Head, near Memorial Gardens, Tuross, NSW Taken at. Lake Conjola beach, N of Ulladulla, NSW Taken at. Chain Valley Bay, Lake Macquarie State Conservation Area, NSW Taken at. Chain Valley Bay, Lake Macquarie State Conservation Area, NSW Taken at. Wright's Lookout walk, New England Nat Pk, NSW Taken at. Wright's Lookout walk, New England Nat Pk, NSW Taken at. Wright's Lookout walk, New England Nat Pk, NSW Taken at. Boondall Wet Lands, Brisbane QLD Taken at. Boondall Wet Lands, Brisbane QLD Taken at. Boondall Wet Lands, Brisbane QLD Taken at. see Australian Tropical Rainforest Plants Key Taken at. see Australian Tropical Rainforest Plants Key Taken at. see Australian Tropical Rainforest Plants Key Taken at. see Australian Tropical Rainforest Plants Key Taken at. see Australian Tropical Rainforest Plants Key Taken at. see Australian Tropical Rainforest Plants Key http://lxml.de/lxmlhtml.html
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46850954

http://stackoverflow.com/comment/80463356
has text: i have also used this from inventory import invent
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46758894

http://stackoverflow.com/q/46870692
tagged with: python
linked to: http://stackoverflow.com/q/35282456
has comment: http://stackoverflow.com/comment/80688812
type: AnsweredQuestion
has body: Suppose I have a Pandas data frame as follows: Test Parameter Value X1 0 0.033285423511615113 X1 1 0.78790279861666179 X1 2 0.79136989638378297 X1 3 0.80063190842016707 X1 4 0.7884653622402551 X1 5 0.78561849214309198... ... X1 22 22: 0.82241991278171311... ... X2 ... I'd like to get the row with Parameter value 3. That is the row with the last increasing value before the first drop. Notice that later on we might have higher values (eg row 22). Essentially, I'm trying to get the "last" number before the "first" decrease value. Also note that there are multiple Tests, so I probably need to do something like: myDF.groupby("Test").Something
tagged with: dataframe
has answer: http://stackoverflow.com/a/46870795
has answer: http://stackoverflow.com/a/46870945
accepted answer: http://stackoverflow.com/a/46870945
has comment: http://stackoverflow.com/comment/80688886
has comment: http://stackoverflow.com/comment/80688923
type: Question
tagged with: pandas
downvote count: 1
possible better answer: http://stackoverflow.com/a/46870795
has answer: http://stackoverflow.com/a/46870829
favorite count: 0
score: 8
upvote count: 9
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46870734
answer count: 5
has title: How to find first local maximum for every group?
has answer: http://stackoverflow.com/a/46870777

drf-queryset
type: Tag
tags question: http://stackoverflow.com/q/46752123
tag name: drf-queryset

http://stackoverflow.com/q/46831200
tagged with: django-urls
score: 0
answer count: 1
tagged with: url
tagged with: django
tagged with: python
has body: I've created a rest API for my Django app but how I go to api.website.com rather than something like www.website.com/api Btw I'm using nginx if that has to do anything with this
accepted answer: http://stackoverflow.com/a/46831740
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46831740
type: Question
tagged with: nginx
has title: how to change www to something else in Django urls?

http://stackoverflow.com/comment/80617895
type: AnswerComment
comment on: http://stackoverflow.com/a/46834881
score: 0
type: Comment
has text: You can also add `df['Date'].astype(str).str.replace('-','').astype(int)` , `df['Date'].astype(str).str.split('-').str.join('').astype(int)`to your options .

http://stackoverflow.com/q/46755340
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80456201
type: UnansweredQuestion
tagged with: regression
tagged with: python
has answer: http://stackoverflow.com/a/46755937
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80456830
type: Question
has body: I am trying to train a DNN with Keras. The model is here defined: model = Sequential() model.add(Dense(2050, input_shape=(2050, 75), activation='relu')) model.add(Dense(1024, activation='relu')) model.add(Dense(1024, activation='relu')) model.add(Dense(1024, activation='relu')) model.add(Dense(75, activation='sigmoid')) The cost function is the mse. The idea here is training with a set of 3000 images with size 2050*75, which basically are two different features extracted from a 1025*75 image, in order to get 3000 image with size 1025*75 in the output, which are some kind of representation of the original image. So, the input is a (3000, 2050, 75) tensor, while the output dimension is (3000, 1025, 75). I can see why Keras gives me the following error: ValueError: Error when checking target: expected dense_5 to have shape (None, 2050, 75) but got array with shape (3000, 1025, 75) There must be a way to avoid this error, maybe by redefining the DNN dimensions or layers. Do you have any suggestion? Thanks. EDIT: As requested, this is the complete code. X = train_set Y = m [n_samples, n_freq, n_time] = X.shape model = Sequential() model.add(Dense(n_freq, input_shape=(n_freq, n_time), activation='relu')) model.add(Dense(n_hid, activation='relu')) model.add(Dense(n_hid, activation='relu')) model.add(Dense(n_hid, activation='relu')) model.add(Dense(n_time, activation='sigmoid')) model.summary() model.compile(optimizer='rmsprop',loss='mse',metrics=['mae','accuracy']) model.fit(np.abs(X), np.abs(Y), epochs=n_epochs, batch_size=batch_size) score = model.evaluate(np.abs(X), np.abs(Y), batch_size = batch_size)
has comment: http://stackoverflow.com/comment/80456181
tagged with: keras
has title: Python: cannot train regression model in Keras

http://stackoverflow.com/comment/80645492
comment on: http://stackoverflow.com/q/46848095
type: Comment
type: QuestionComment
has text: I do that line in order to import the contents of the package.py directory such that when I import the package in python I can do package.function. When I add the directory to the path and do import package I just get a recursive package.package.package.package with no functions imported.
score: 0

http://stackoverflow.com/comment/80453133
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46752487
has text: Give an example. Not sure what you mean.

http://stackoverflow.com/comment/80647573
has text: I don't know R, but I could show a python solution if that might help.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46816111
score: 0

http://stackoverflow.com/comment/80842844
score: 1
has text: did you see my answer?
comment on: http://stackoverflow.com/q/46840828
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80618498
type: Comment
has text: @user2357112 thanks for your concern but I sort the keys before using them, I haven't shown that here sorry
type: QuestionComment
comment on: http://stackoverflow.com/q/46835310
score: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/46865289
tags question: http://stackoverflow.com/q/46874619
tags question: http://stackoverflow.com/q/46853383
type: Tag

http://stackoverflow.com/q/46867161
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/46868601
accepted answer: http://stackoverflow.com/a/46868601
has title: How can I update one (or a couple) files in a Google App Engine Flask App?
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
type: Question
has body: If I'm just updating, say, my main.py file, is there a better way to update the app then running gcloud app deploy, which takes several minutes? I wouldn't think I need to completely blow up and rebuild the environment if I'm just updating one file.

http://stackoverflow.com/q/46863565
tagged with: python
has comment: http://stackoverflow.com/comment/80674651
accepted answer: http://stackoverflow.com/a/46863663
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46863634
score: -3
has comment: http://stackoverflow.com/comment/80674608
type: Question
answer count: 2
downvote count: 4
possible better answer: http://stackoverflow.com/a/46863634
has answer: http://stackoverflow.com/a/46863663
tagged with: flask
favorite count: 0
has title: 405 when submitting form to Flask app
has body: I'm trying to create a webpage in html in which a user have to input a url into a textfield. submit When the user press the submit button a python script should intercept the data inserted by the user and pass it to another function inside this script. Python script: from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def indhtml() : return render_template('index.html') @app.route('/index.html', methods = ['POST']) def result(): result = request.form('url_target') link = result.link print (link) return if __name__ == '__main__' : app.run(debug = True) the first render is fine and i can see the index.html page, but when i insert something in the textfield appears the error HTTP 405. Do you have any suggestion for that? :( Thanks!

http://stackoverflow.com/a/46864234
has body: There are almost certainly better solutions to your problem, but your example is so short and contrived that it's hard to give good advice. To address the specific question you asked, you can use getattr to get a function or class from a module based on a string: for F in ('One', 'Two', 'Three', ...): Cls = getattr(mf, F) obj = Cls(var1, var2) self.my_dict[F] = obj A simpler approach might be to iterate over the classes themselves: for F in (mf.One, mf.Two, mf.Three): obj = F(var1, var2) ...
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46864049
answers question: http://stackoverflow.com/q/46864049
type: Answer
has comment: http://stackoverflow.com/comment/80685510
downvote count: 0
score: 1

http://stackoverflow.com/q/46864899
has title: Creating sentences by a function without using a package
tagged with: sentence
answer count: 2
has comment: http://stackoverflow.com/comment/80677378
has comment: http://stackoverflow.com/comment/80677478
has comment: http://stackoverflow.com/comment/80678157
score: 0
has body: Im currently writing a program that looks at a list and iterates through a groups the words into sentences but whenever i ran it, I got [] and im not 100% sure why. Here is my code for reading in the file, and creating the sentence and an attached snippet of the list. def import_file(text_file): wordcounts = [] with open(text_file, encoding = "utf-8") as f: pride_text = f.read() sentences = pride_text.split(" ") return sentences def create_sentance(sentance): sentence_list=[] my_sentence="" for character in sentance: if character=='.' or character=='?' or character=='!': sentence_list.append(my_sentence) my_sentence="" else: my_sentence=my_sentence + character return sentence_list Preview of List Calling of my functions pride=import_file("pride.txt") pride=remove_abbreviations_and_punctuation(pride) pride=create_sentance(pride) print(pride)
tagged with: python
has answer: http://stackoverflow.com/a/46865043
possible better answer: http://stackoverflow.com/a/46865076
has answer: http://stackoverflow.com/a/46865076
tagged with: list
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46865043

http://stackoverflow.com/a/46788232
answers question: http://stackoverflow.com/q/46787806
has body: pandas provides a very straight forward solution to the problem - import pandas as pd df = pd.DataFrame({ 'key1': ['value1', 'value2', 'value3', 'n'], 'key2': ['value1', 'value2', 'value3', 'n'], 'key3': ['value1', 'value2', 'value3', 'n'], 'key4': ['value1', 'value2', 'value3', 'n'] }) df.to_csv('/path/to/file')
type: Answer
score: 3
downvote count: 0
upvote count: 3

http://stackoverflow.com/a/72446806
type: Answer
has body: I solved this problem by indicating the full path to file (for example): pip install -r /Users/aleks/Desktop/....../requirements.txt
upvote count: 1
has comment: http://stackoverflow.com/comment/130422383
has comment: http://stackoverflow.com/comment/127983363
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46854451

http://stackoverflow.com/q/46820685
has body: So if I have this code in my models.py class Computer(models.Model): brand = models.CharField(max_length=225) How do I show either of the following additional field in my django admin depending on the value of brand above? mac_os_version = models.CharField(max_length=225) windows_os_version = models.CharField(max_length=225) linux_os_version = models.CharField(max_length=225) e.g. if brand == HP only the field for windows_os or linux will be shown when you try to input your data in the admin and will the hide field for mac_os.
type: Question
has comment: http://stackoverflow.com/comment/80627564
has comment: http://stackoverflow.com/comment/80611466
has answer: http://stackoverflow.com/a/46821765
answer count: 1
has comment: http://stackoverflow.com/comment/80591682
has comment: http://stackoverflow.com/comment/80604821
has comment: http://stackoverflow.com/comment/80588950
tagged with: python
type: UnansweredQuestion
score: 0
tagged with: django
has title: How do you hide a field if other field's condition is not met in django?
has comment: http://stackoverflow.com/comment/80606435

http://stackoverflow.com/comment/80928992
comment on: http://stackoverflow.com/q/46854905
score: 0
type: Comment
type: QuestionComment
has text: @Achyuth The number of partitions is 4 (or whatever number I pass in to wholeTextFiles)

http://stackoverflow.com/a/46900338
score: 0
type: Answer
has body: Your result is an unordered collection of key, value. One solution would be to convert to a list of tuples as you can still maintain the data association of word and count and simultaneously introduce indexing for sorting. https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts You can then slice off the first 10 for most common
answers question: http://stackoverflow.com/q/46900034

http://stackoverflow.com/comment/80500700
type: Comment
has text: Nothing was mentioned about pandas, so why bring it up?
comment on: http://stackoverflow.com/a/46777472
type: AnswerComment
score: 2

http://stackoverflow.com/comment/80583331
type: QuestionComment
has text: `from sampleA import classA`? And then you can just do `functionA = classA.functionA` in your `classB` definition.
score: 0
comment on: http://stackoverflow.com/q/46817900
type: Comment

http://stackoverflow.com/q/46885016
linked to: http://stackoverflow.com/q/5767228
answer count: 2
has answer: http://stackoverflow.com/a/46885821
upvote count: 0
duplicate of: http://stackoverflow.com/q/5767228
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46885893
accepted answer: http://stackoverflow.com/a/46885821
tagged with: tkinter
downvote count: 2
has title: python tkinter self.master.bind() is calling function without an event
possible better answer: http://stackoverflow.com/a/46885893
has body: I have a problem with tkinter self.master.bind. When I run the program below, it just calls the bind automatically! I have self.master.bind('&lt;left&gt;', self.moveleft), It just doesn't work! It runs automatically. I have listed where the error is in a comment saying ERROR HERE!!!. __init__ is working fine, self.master is working fine, it's just the bind, that's the only thing! from tkinter import * import time class game_Win_Start: def __init__(self, root): self.master = root self.master.title('Awesome game') self.canvas() def canvas(self): global c c = Canvas(self.master, width=root.winfo_screenwidth(), height=root.winfo_screenheight(), bg='black') c.pack() self.ButtonLabel() def ButtonLabel(self): global title title = Label(self.master, font=('arial', 50, 'bold'), text='A Game', fg='orange') title.place(x=750, y=75) self.BtnStart() def BtnStart(self): global BtnStart BtnStart = Button(self.master, font=('arial', 45, 'bold'), text='start', relief=RAISED, padx=25, pady=25, bd=8, command=self.MenuDestroy) BtnStart.place(x=750, y=700) def MenuDestroy(self): BtnStart.place(x=2000, y=0) title.place(x=2000, y=0) GameScreen() class gameScreen: def __init__(self, root): self.master = root self.drawBg() def drawBg(self): full = root.winfo_screenwidth() middle = full/2 global third third = full/3 third2 = third*2 global sixth sixth = third/2 c.create_line(third,0,third,1000,fill='blue') c.create_line(third2,0,third2,1000,fill='blue') c.create_rectangle(0,0,50,1000,fill='blue') c.create_rectangle(full,0,full-50,1000,fill='blue') self.spriteMe() def spriteMe(self): global sprite sprite = c.create_oval(0,0,50,50,fill='peru') c.move(sprite,sixth*3,850) self.master.update() Controls() def GameScreen(): gameScreen(root) class controls: def __init__(self, root): self.master = root self.keyBind() def moveleft(self, *args): c.move(sprite,-608,0) self.master.update() c.update() time.sleep(1) def moveright(self, *args): c.move(sprite,608,0) self.master.update() c.update() time.sleep…
type: Question
type: AnsweredQuestion
score: -2

http://stackoverflow.com/a/46836687
upvote count: 10
has comment: http://stackoverflow.com/comment/95972797
has body: In general, this message Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) informs you about the IP-address of your PC that will be listened to accept the request. It can be configured to listen to only one IP-address. As it has been stated in the comments, if you are trying to reach your Web site from the same PC you develop on, you may use virtual (loop) address 127.0.0.1. In case you want to check how your Web site will look on your other devices that are connected to the same network (i.e. tablet, phone, other PC whatever else), you need to type your PC's internal network IP address, and it differs from the loop. It may be e.g. 192.168.1.1 (you should check it on your NIC properties). And it may changes if you try to make something like live-demo to your friends. So in order, to prevent you from checking each time, which one IP-address is valid for your PC right now, you can use 0.0.0.0 telling to your application 'listen for incoming requests from ALL the NICs, whatever IP-address they have'.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/95796388
type: Answer
accepted answer of: http://stackoverflow.com/q/46835568
answers question: http://stackoverflow.com/q/46835568
score: 10

http://stackoverflow.com/comment/80682916
has text: And can you show an example of the setup of the csv file you are using?
comment on: http://stackoverflow.com/q/46867675
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/46862427
has body: You are using this anti-pattern: headlines = pd.DataFrame() for for y in years: for ind in days: headlines = headlines.append(blah) Instead, do this: headlines = [] for for y in years: for ind in days: headlines.append(pd.DataFrame(blah)) headlines = pd.concat(headlines) A second potential problem is that you are making 3650 web requests. If I were operating a website like that, I'd build in throttling to slow down scrapers like yours. You may find it better to collect the raw data once, store it on your disk, then process it in a second pass. Then you don't incur the cost of 3650 web requests every time you need to debug your program.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/46859939
answers question: http://stackoverflow.com/q/46859939

http://stackoverflow.com/q/46903340
type: Question
tagged with: python
upvote count: 1
has title: Skeletonize with 4-neighborhood
has answer: http://stackoverflow.com/a/46904916
answer count: 1
tagged with: scikit-image
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/46904916
score: 1
favorite count: 0
has body: I am using skeletonize from skimage, which delivers a result connected as a 8-neigborhood: import numpy as np from skimage.morphology import skeletonize image = np.array( [[0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 1, 1]]) print image print skel = skeletonize(image) print skel.astype(np.uint8) # result #[[0 0 0 0 0 0 0 0 0] # [0 0 0 1 1 1 0 0 0] # [0 0 0 0 0 0 1 1 1] # [0 0 0 0 0 0 0 0 0]] What I want to get instead is a 4-connected result such as: #[[0 0 0 0 0 0 0 0 0] #[0 0 0 1 1 1 1 0 0] #[0 0 0 0 0 0 1 1 1] #[0 0 0 0 0 0 0 0 0]] or #[[0 0 0 0 0 0 0 0 0] #[0 0 0 1 1 1 0 0 0] #[0 0 0 0 0 1 1 1 1] #[0 0 0 0 0 0 0 0 0]] but not #[[0 0 0 0 0 0 0 0 0] #[0 0 0 1 1 1 0 0 0] #[0 0 0 0 1 1 1 1 1] #[0 0 0 0 0 0 0 0 0]] How would I do this? There is no neigborhood option in skeletonize. The reason why I am asking is that I want to further process the connected lines with skimage.measure.find_contours, which would break the lines into two if they are not 4-connected.

http://stackoverflow.com/a/46853217
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80715436
has comment: http://stackoverflow.com/comment/80715367
answers question: http://stackoverflow.com/q/46853108
has body: What you are getting is just a warning the Row is begining concatenated to the dataframe not in a proper way. Row is a series and you are trying to concat series between two dataframes. Series has index dtype object (string) and df has index dtype int. Index will be sorted usually when concatenated. Now the function doesn't know how to sort the mixed dtype index. So you get that warning. So better convert Row to dataframe to avoid this error i.e ndf = pd.concat([mydf.head(index), pd.DataFrame(Row).T, mydf.tail(len(mydf) - index)]) For Example consider the dataframe mydf id offset code 0 1 3 21 1 1 3 24 2 1 5 21 index= 2 Row = mydf.iloc[index] df = pd.concat([mydf.head(index), Row , mydf.tail(len(mydf) - index)]) /python3.5/site-packages/pandas/core/indexes/api.py:77: RuntimeWarning: unorderable types: str() &lt; int(), sort order is undefined for incomparable objects result = result.union(other) id offset code 0 0 1.0 3.0 21.0 NaN 1 1.0 3.0 24.0 NaN id NaN NaN NaN 1.0 offset NaN NaN NaN 5.0 code NaN NaN NaN 21.0 2 1.0 5.0 21.0 NaN df = pd.concat([mydf.head(index), pd.DataFrame(Row).T , mydf.tail(len(mydf) - index)]) id offset code 0 1 3 21 1 1 3 24 2 1 5 21 2 1 5 21

http://stackoverflow.com/a/47866822
accepted answer of: http://stackoverflow.com/q/46804356
answers question: http://stackoverflow.com/q/46804356
has body: The main issue I run into is that long running tasks may get killed if you tell supervisor to killasgroup which would result in lost data. The solution I've moved to using is to tell the mainprocess to TERM which will kill off the workers as they finish their tasks. supervisor will then restart the main process after all the workers finish. ps aux | grep celery.*MainProcess | awk '{print $2}' | xargs kill -TERM This is also related. Celery Production Graceful Restart
type: Answer
score: 3
downvote count: 0
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/80505639
type: Comment
comment on: http://stackoverflow.com/q/46779690
score: 0
type: QuestionComment
has text: What actually you want to get at the end? Do you need a mask for frame?

http://stackoverflow.com/a/47719547
answers question: http://stackoverflow.com/q/46811850
has comment: http://stackoverflow.com/comment/86061479
score: 4
has comment: http://stackoverflow.com/comment/85838589
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/95522764
has body: You can simply do as follows to create chromosomes of multiple types: toolbox.register("attr_int", random.randint, 0, 1) toolbox.register("attr_flt", random.uniform, 0, 2) toolbox.register("individual", tools.initCycle, creator.Individual, (toolbox.attr_int, toolbox.attr_flt), n=1) and then create a population of size 100: toolbox.register("population", tools.initRepeat, list, toolbox.individual) population = toolbox.population(n=100)
type: Answer

http://stackoverflow.com/q/46795248
has answer: http://stackoverflow.com/a/46808563
accepted answer: http://stackoverflow.com/a/46808563
has title: Process messages from autobahn Subscriptions asynchronously, non-blocking
tagged with: autobahn
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: docker
upvote count: 2
has body: I have a python "Device" running in a docker container. It's connected to a Crossbar-router, receiving autobahn/WAMP event messages on subscribed channels. When a certain event is published, my Device is calling a method that's finishing in a few seconds. Now, i want it to skip or handle any messages of the same event that are received, while the method is still running. I tried to accomplish this by using the @inlinecallback decorator of Twisted and setting a "self.busy"-flag on the Device. But it's not returning with a deferred immediately, instead it's behaving like a normal, blocking method, so that incoming messages are processed one after another. Here's my Code: from autobahn.twisted.wamp import ApplicationSession from twisted.internet.defer import inlineCallbacks class Pixel(ApplicationSession): @inlineCallbacks def onJoin(self, details): yield self.subscribe(self.handler_no_access, 'com.event.no_access') @inlineCallbacks def handler_no_access(self, direction): entries = len(self.handlers['no_access'][direction]) if entries == 0: self.handlers['no_access'][direction].append(direction) result = yield self._handler_no_access() return result else: yield print('handler_no_access: entries not 0: ', self.handlers['no_access']) @inlineCallbacks def _handler_no_access(self): for direction in self.handlers['no_access']: for message in self.handlers['no_access'][direction]: yield self._timed_switch(self.direction_leds[direction], 'red', 0.2, 5) self.handlers['no_access'][direction] = [] I have already taken the hacky path with the self.handler dictionary, by the way. EDIT the blocking method is: yield self._timed_switch(self.direction_leds[direction], 'red', 0.2, 5) It controls a Neopixel at the GPIOs of a RaspberryPi, letting it flash on and off for 1s. Any further calls to the method def handler_no_access(self, direction) while the _timed_switch hasn't finished, shall be skipped, so they don't stack up. SOLUTION @inlineCallbacks def handler_no_access(self, direction…
tagged with: twisted
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/80632893
type: AnswerComment
comment on: http://stackoverflow.com/a/46842547
type: Comment
has text: Thank you very much for you respond, i dont use Anaconda and i have python 3.6.x on my computer now, and even if i try to install the 3.5.2 it still on python 3.6.x should i delete the python36 and download python again?
score: 0

http://stackoverflow.com/a/46797660
upvote count: 6
answers question: http://stackoverflow.com/q/46797598
has body: If you want to have C column as index: In [50]: r = df.set_index('C') In [51]: r Out[51]: A B C 1 a d 2 b e 3 c f In [52]: r.index.name Out[52]: 'C' In [53]: r.columns.name is None Out[53]: True In [54]: r = r.rename_axis(None,0).rename_axis('C',1) In [57]: r Out[57]: C A B 1 a d 2 b e 3 c f In [55]: r.index.name is None Out[55]: True In [56]: r.columns.name Out[56]: 'C' NOTE: but it looks pretty misleading...
has comment: http://stackoverflow.com/comment/80542967
has comment: http://stackoverflow.com/comment/80542089
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/80542110
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80542938
type: Answer
has comment: http://stackoverflow.com/comment/80543122
accepted answer of: http://stackoverflow.com/q/46797598

http://stackoverflow.com/comment/80551268
comment on: http://stackoverflow.com/a/46802153
type: AnswerComment
has text: @Akash KC :) I can see where strings would be needed, but yes, it has nothing to do with reversing! On the other hand, `map` is a really good function, I've learned it only recently so now I'm just looking for (reasonable) places to apply it ;)
type: Comment
score: 0

http://stackoverflow.com/q/46782963
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80512810
has comment: http://stackoverflow.com/comment/80653810
has answer: http://stackoverflow.com/a/46860649
upvote count: 6
has title: pycharm is showing error in module import resolution even if program is working fine
favorite count: 0
has comment: http://stackoverflow.com/comment/80512211
tagged with: python
has comment: http://stackoverflow.com/comment/80655383
tagged with: pycharm
downvote count: 0
possible better answer: http://stackoverflow.com/a/46860649
has answer: http://stackoverflow.com/a/64140431
accepted answer: http://stackoverflow.com/a/64140431
score: 6
linked to: http://stackoverflow.com/q/11725519
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80652559
has body: I am new in Python and pycharm ide. I have created one of my own module and importing it in another python file. Both of my python files are in same direcotary and parent directory has been made Sources Root directory. Now my program is working fine but pycharm ide is showing error in import statement and on hover prompting no such module. I am not sure if i am doing something wrong please let me know what is the proper way to import a module. here is my project structure - Main.py is importing Greeting.py and getting error.test is a root directory.
has comment: http://stackoverflow.com/comment/80668809

http://stackoverflow.com/a/46860138
answers question: http://stackoverflow.com/q/46808438
has body: random.randint only takes two arguments, a start and an end. The third argument mentioned by Python is self, which is done automatically. To pick a number between 1 and 3, just do random.randint(1,3). Those if statements don't make any sense, by the way; they should look something like: if userInput == "paper": # send discord messages
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/46808438

http://stackoverflow.com/a/46780679
answers question: http://stackoverflow.com/q/46777158
has body: It may be because the connection is being prematurely closed or the file is too large. Try this: import requests, shutil from requests.exceptions import ReadTimeout, ConnectionError img_url = data['img'] filename = 'hello.jpg' try: response = requests.get(img_url, stream=True) with open(filename, 'wb') as img_file: shutil.copyfileobj(response.raw, img_file) except ReadTimeout: print("Connection timeout") except ConnectionError: print("Connection refused")
has comment: http://stackoverflow.com/comment/89309203
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89240256

http://stackoverflow.com/q/46862000
tagged with: python
tagged with: sublimetext3
tagged with: build
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80671901
type: Question
has comment: http://stackoverflow.com/comment/80672795
has title: Sublime Text 3: Build Plots (Python) inline (within build window)
has body: I am using Sublime Text 3 and building my Python scripts within Sublime (CTRL + B). Since I am using matplotlib.pyplot a lot, I want the created plots to show up within the build window and NOT in an popup-window. Does anyone know how to accomplish this?
tagged with: matplotlib
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80672054
type: UnansweredQuestion

http://stackoverflow.com/comment/80597818
comment on: http://stackoverflow.com/a/46824598
score: 0
type: AnswerComment
has text: Then use it for 3 characters like `look.get(x[:3], '')` after updating `look`
type: Comment

http://stackoverflow.com/a/46850699
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80649195
has comment: http://stackoverflow.com/comment/80649164
has comment: http://stackoverflow.com/comment/80649376
answers question: http://stackoverflow.com/q/46850341
has body: You might be able to achieve what you want with this list comprehension and join: "".join([token.strip("@") for token in str2_tokens]) E.g. &gt;&gt;&gt; x = ["@a", "b@", "c"] &gt;&gt;&gt; "".join([y.strip("@") for y in x]) 'abc'
has comment: http://stackoverflow.com/comment/80648873

http://stackoverflow.com/a/46883680
answers question: http://stackoverflow.com/q/46883601
score: 1
has comment: http://stackoverflow.com/comment/80714695
has comment: http://stackoverflow.com/comment/80714668
has comment: http://stackoverflow.com/comment/80714846
has comment: http://stackoverflow.com/comment/80715212
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80715424
has body: You code works fine. Below is the driver test for the same. IN : 1 2 3 IN : 0 1 2 OUT : 0 3 But, there is a small logical mistake.You are not handling your inputs properly. But in the end, fortunately for you, it cancels out the problem it might create. They should be : set_1 = set(map(int,input().split())) set_2 = set(map(int,input().split())) #OR just set_1 = set(input().split()) set_2 = set(input().split()) A quick glance at the workings of your code and the correct code. &gt;&gt;&gt; s = set(input()) #your code 1 2 3 &gt;&gt;&gt; s =&gt; {'1', '2', ' ', '3'} &gt;&gt;&gt; s = set(map(int, input().split())) #should be 1 2 3 &gt;&gt;&gt; s =&gt; {1, 2, 3}
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46883601

http://stackoverflow.com/comment/80635412
type: AnswerComment
has text: Yes, I printed the json and it's updating fine. The only problem it's that it's not writing it in the data.json
comment on: http://stackoverflow.com/a/46843735
type: Comment
score: 0

http://stackoverflow.com/q/46892386
has title: SQLAlchemy: How to add conditionally to a collection via event listener?
upvote count: 1
answer count: 1
tagged with: sqlalchemy
has body: In sqlalchemy, I can listen for the append event on collections to intercept and possibly change values which are to be appended. How can I silently drop the value (not append), e.g. when I want to implement a set-like behaviour with arbitrary criteria? MCVE (works without any dependency except sqlalchemy, just copy and paste): from sqlalchemy import create_engine, Integer, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.event import listens_for engine = create_engine('sqlite:///:memory:') Base = declarative_base() _next_id = 1 def get_id(): global _next_id _ = _next_id _next_id += 1 return _ class A1(Base): __tablename__ = 'a1' id = Column(Integer, primary_key=True, default=get_id) a2 = relationship('A2', back_populates='a') class A2(Base): __tablename__ = 'a2' id = Column(Integer, primary_key=True, default=get_id) a_id = Column(Integer, ForeignKey('a1.id')) a = relationship('A1', back_populates='a2') name = Column(Text) @listens_for(A1.a2, 'append', retval=True) def coll_listener(target, val, initiator): for _ in target.a2: if _.name == val.name: # this is justs some arbitrary condition to illustrate things return return val Base.metadata.create_all(engine) Session = sessionmaker() Session.configure(bind=engine) _session = Session() a2_1 = A2(name='a2_1') a2_2 = A2(name='a2_2') a2_3 = A2(name='a2_1') a1 = A1() for thing in (a2_1, a2_2, a2_3, a1): _session.add(thing) _session.flush() for a in (a2_1, a2_2, a2_3): a1.a2.append(a) _session.flush() # raises FlushError: Can't flush None value found in collection A1.a2
has answer: http://stackoverflow.com/a/46909001
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46909001
tagged with: python

http://stackoverflow.com/a/46784585
downvote count: 0
score: 1
has body: This sequence diagram may help you build your app. Try to modify your program according to the diagram and tell us what problems you find.
upvote count: 1
answers question: http://stackoverflow.com/q/46770278
type: Answer

http://stackoverflow.com/comment/80591605
type: Comment
has text: same error message
comment on: http://stackoverflow.com/q/46821976
score: 0
type: QuestionComment

http://stackoverflow.com/a/46901510
score: 3
answers question: http://stackoverflow.com/q/46901452
downvote count: 0
has comment: http://stackoverflow.com/comment/80758320
type: Answer
has body: I find xargs useful in such a case. I haven't tried myself, but perhaps cat list.txt | xargs ./run.py p1 p2 works for you? In case you need to be specific where the arguments go, you can use the xargs placeholder option -J: cat list.txt | xargs -J{} ./run.py p1 {} p2 would put "a b" between "p1" and "p2".
upvote count: 3

http://stackoverflow.com/a/46773268
accepted answer of: http://stackoverflow.com/q/46768675
score: 2
answers question: http://stackoverflow.com/q/46768675
upvote count: 2
has body: Yes, Pandas has a robust system for MultiIndexing. One way to do what you want is as follows: vowels = ['A','E','I','O','U','Y'] tuples = [('Vowel' if x in vowels else 'Consonant', x) for x in df.columns.tolist()] df.columns = pd.MultiIndex.from_tuples(tuples, names=['Kind', 'Letter']) First you make a list of vowels (you may need to include letters with accents, diacritics, etc., depending on your use case). Then you make a list of tuples where the first value is either 'Vowel' or 'Consonant' and the second value is the letter for every letter in your column list. Then you make a MultiIndex out of those tuples.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81100411
score: 0
comment on: http://stackoverflow.com/q/46756326
type: QuestionComment
type: Comment
has text: This question would've received a more appropriate answer had you given it the pandas tag. None of these answers are exactly fit for adaptation into pandas code.

http://stackoverflow.com/q/46821838
downvote count: 0
has answer: http://stackoverflow.com/a/46822017
favorite count: 0
has answer: http://stackoverflow.com/a/46822018
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80591131
tagged with: python
tagged with: dictionary
answer count: 4
has title: How to create a list of dictionaries using for loop?
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46821946
has body: Textfile: VIP Room, 10, 250 Executive Room,30, 500 Pool Site, 50, 850 Banquet Hall, 200, 1000 Chamber Hall, 500, 2000 Concert Hall, 1000, 3500 My code so far to read the file and create a list: def readVenueList(): dic={} venueList=[] f=open("venue.txt","r") for line in f: line = line.split(",") print(line) for i in line: i.split() dic["name"]=i[0] dic["num"]=i[1] dic["cost"]=i[2] venueList.append(dic) return(venueList) How do I create a list of dictionaries with the following output? venueList = [{'cost': '250', 'name': 'VIP Room', 'num': '10'}, {'cost': '250', 'name': 'Executive Room', 'num': '30'}, # and so on and so forth... ]
has answer: http://stackoverflow.com/a/46821964

http://stackoverflow.com/comment/80673249
comment on: http://stackoverflow.com/q/46851087
has text: When I press Space image moves down, no issues with that unless its not moving continuously while holding the button.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80491088
score: 0
type: Comment
has text: `signal.alarm` doesn't stops the flow. So the exception will be raised by timeout and if the script will be in a try block, than the exception will be caught. You can see better how does it work if you increase `timeout_duration` to 3. Than there will be more time to print several 'sleep' messages.
type: AnswerComment
comment on: http://stackoverflow.com/a/46772405

http://stackoverflow.com/a/47998337
answers question: http://stackoverflow.com/q/46839835
accepted answer of: http://stackoverflow.com/q/46839835
score: 0
type: Answer
has body: My problem was solved with updates. After about a month I was able to use Kivy as intended with no error.
type: AcceptedAnswer

gmail
type: Tag
tags question: http://stackoverflow.com/q/46778824
tag name: gmail

http://stackoverflow.com/q/46754644
score: 3
has comment: http://stackoverflow.com/comment/80455668
has body: I am using python-social-auth and django in my authentication system. At the moment, when I authenticate with either Facebook or Google, the URL returns with either /#_=_ or /# appended. I understand that these are deliberate but I'd like to remove them. I've seen a number of javascript solutions for the facebook version, but I'd like to do this from the server side. I tried to do a basic redirect: def pre_home(request): return redirect(reverse('home')) def home(request): return render(request, 'core/home.html) where I directed the auth system to pre_home on completion. I assumed this would strip off the end of the url on redirection to home, however it does not...
has title: Remove # and #_=_ from returning social auth url - Django
downvote count: 0
has comment: http://stackoverflow.com/comment/80455252
tagged with: facebook-authentication
favorite count: 0
tagged with: google-authentication
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
upvote count: 3
linked to: http://stackoverflow.com/q/5283395
tagged with: django-authentication
type: Question

http://stackoverflow.com/q/46807337
tagged with: dictionary
has title: Merge python dicts with same key in another dict
has body: Ex: Alias, Speed, Duplex: Alias, Speed, Duplex are dicts with form {key: val} but in some cases Alias or Speed or Duplex may be null So my problem is that if I use: dd = defaultdict(list) for d in (Alias, Speed, Duplex): for key, value in d.items(): dd[key].append(value) I will have a result with {key: [aliasVal, speedVal, duplexVal]} but as I already told you if Alias is null I will have {key: [speedVal, duplexVal]}. So I need to replace list with dict. Final result should be: {key: {"aliasVal": aliasVal, "speedVal": speedVal, "duplexVal": duplexVal }} And now we know keys and value if those exists
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/46824096
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80561939
has comment: http://stackoverflow.com/comment/80562216
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/a/46895801
has comment: http://stackoverflow.com/comment/80738669
upvote count: 4
answers question: http://stackoverflow.com/q/46895696
has body: You can iterate over set or use hashing from itertools import permutations, combinations perm = set(permutations('AABB', 4)) for i in perm: print(i) #Output ('A', 'A', 'B', 'B') ('A', 'B', 'A', 'B') ('A', 'B', 'B', 'A') ('B', 'A', 'A', 'B') ('B', 'B', 'A', 'A') ('B', 'A', 'B', 'A') Using dictionary: from itertools import permutations, combinations dicta = {} perm = permutations('AABB', 4) for i in list(perm): if i in dicta: dicta[i] += 1 else: dicta[i] = 1 print([i for i in dicta.keys()])
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/q/46749402
accepted answer: http://stackoverflow.com/a/46809257
has comment: http://stackoverflow.com/comment/80445812
score: 0
tagged with: regression
has comment: http://stackoverflow.com/comment/80446064
tagged with: scipy
answer count: 1
tagged with: matlab
has comment: http://stackoverflow.com/comment/80445733
has comment: http://stackoverflow.com/comment/80491168
has title: Curve Fitting in Python for extrapolation, Regression analysis
has comment: http://stackoverflow.com/comment/80446128
has body: This question is regarding curve fitting in python. First, I would say that I do not know the curve fit function to insert into "curve_fit" function in the scipy library; therefore, I am trying to use a polyfit which is OK if I am interested in interpolation but my goal is to predict values at future points, in other words extrapolation. I have attached a screenshot of a raw signal, smoothed and its polyfit result. It has the correct poly order but still fails at extrapolation. My conclusion is that poly fit is not the right approach here, but I can not estimate the curve function. What are you thoughts? Please note that this is not a distribution since the y values may keep slowly decreasing infinitely, even below 0. I'd say the function looks like an exponential Gaussian but again it's not a distribution so dont want to do that. My last thought was to split the plot into two, the first model can certainly be modeled as a polynomial and the second as an exponential. (values are different than first png cuz it's of a different signal). Then, maybe combine the two. What do you think about this? Attached is a screenshot of this too.
has answer: http://stackoverflow.com/a/46809257
type: AnsweredQuestion
type: Question
tagged with: curve-fitting
tagged with: python

http://stackoverflow.com/a/46757738
has comment: http://stackoverflow.com/comment/80460719
has body: If z is Series then need only: L = z.index[:3].tolist() EDIT by comment: It seems you get DataFrame and index is column: print (type(z)) &lt;class 'pandas.core.frame.DataFrame'&gt; #set index with column index z = z.set_index('index') #select values by position and convert to list L = z.index[:3].tolist() print (L) [155, 2, 1445] If index is column is possible select column and then get first N values by position with Series.iloc: L = z['index'].iloc[:3].tolist() Better is use DataFrame.iloc, but need position of index column too by get_loc: L = z.iloc[:3, df.columns.get_loc('index')].tolist()
answers question: http://stackoverflow.com/q/46757698
score: 0
type: Answer

http://stackoverflow.com/a/46829338
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46829102
type: Answer
has body: If your checks grow, it might be easier to create a function that contains the checks: def get_recommendation(text): if re.match('Dropship',str(text)): return('DROPSHIP') elif re.search('Dispatch',str(text)): return('DISPATCH') elif re.search('Dispatch',str(text)): return('DISPATCH') else: return('OTHERS') You can then use apply() to use the function: dt['Recommend'] = dt['Text'].apply(lambda x: get_recommendation(x))

http://stackoverflow.com/a/46836837
type: Answer
has comment: http://stackoverflow.com/comment/80646401
has comment: http://stackoverflow.com/comment/80648462
has body: This looks like you're running into this bug filed on the official Python bug tracker: https://bugs.python.org/issue14847 The comments there suggest that the issue might be related to one of two things: Installing packages with distribute, due to a bug known to exist at least in distribute 0.6.26. If your "daily execution" relies on installing with this bugged version of distribute, that may explain your issue. Do you know if you do this? And can you update the version of distribute used in your environment, or perhaps use virtual environments to avoid it? Some other way of manipulating sys.modules such that codecs is not found and gives None instead. Does your code do anything like this in some kind of fancy test setup? Judging by the trace, you've modified your code for brevity, but in a way that might not completely capture the original logic. The UnboundLocalError suggests that your assignment of driver was skipped, and you didn't return right away: try: caps = DesiredCapabilities.FIREFOX caps["wires"] = True # This line raises an AttributeError deep inside a standard python lib: driver = webdriver.Firefox(capabilities=caps) driver.maximize_window() self.log("Selenium driver created for %s" % browser) except Exception, e: # The driver variable was never actually created or assigned due to the # AttributeError above. self.log("Error when creating selenium driver") self.log(traceback.format_exc()) # Some omitted code... # The driver variable does not exist past the try if the exception happened # before assignment to driver. So this raises the UnboundLocalError: return self.STATUS.PASS, driver You can fix UnboundLocalError pretty easily by doing the return inside the except, or pre-assigning driver to None or something, but that won't fix the underlying issue creating the driver. That sounds like an issue with your execution environment. Maybe something in your run infrastructure is doing something fancy (what are you using as your test runner?) or perhaps there's…
score: 0
answers question: http://stackoverflow.com/q/46836336

http://stackoverflow.com/comment/80749548
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46901021
score: 0
has text: If you installed the translate package with pip, there may be an executable in `/opt/local/Library/Frameworks/Python.framework/Versions/2.7/‌bin` that does what you want. Though it should have been installed in `/opt/local/bin`, next to your `/opt/local/bin/python`, so check there as well.

http://stackoverflow.com/comment/80589875
type: QuestionComment
has text: This was just a toy example, but I wanted a dictionary comprehension where the value increments without skipping numbers to index the keys. The answers below both provide good ways of implementing what I needed.
comment on: http://stackoverflow.com/q/46821106
score: 0
type: Comment

http://stackoverflow.com/comment/80637094
score: 0
comment on: http://stackoverflow.com/q/46844603
has text: Sure, I've isolated the values from around the time where the problem occurs. The print statements tell you the order of the variables as printed.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46767816
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/80488226
upvote count: 1
answers question: http://stackoverflow.com/q/46767724
has comment: http://stackoverflow.com/comment/80487919
accepted answer of: http://stackoverflow.com/q/46767724
has comment: http://stackoverflow.com/comment/80487971
has body: I think you need change: for group in df_all.groupby("filename") to: for i, group in df_all.groupby("filename"): plot = sns.regplot(data = group, x = "Dem-Dexc", y = "frame") for unpack tuples. Or select second value of tuple by [1]: for group in df_all.groupby("filename"): plot = sns.regplot(data = group[1], x = "Dem-Dexc", y = "frame") You can check tuple output by: for group in df_all.groupby("filename"): print (group) ('Traces_exp22_tif_pair16.txt', Dem-Dexc Aem-Dexc Aem-Aexc S E fit frame \ 0 18150.0595 18548.2451 15263.7451 0.7063 0.5054 0.879 1.0 1 596.9286 7161.7353 1652.8922 0.8244 0.9231 0.879 2.0 2 93.2976 3112.3725 2632.6667 0.5491 0.9709 0.879 3.0 3 1481.1310 4365.4902 769.3333 0.8837 0.7467 0.879 4.0 4 583.1786 6192.6373 1225.5392 0.8468 0.9139 0.879 5.0 filename 0 Traces_exp22_tif_pair16.txt 1 Traces_exp22_tif_pair16.txt 2 Traces_exp22_tif_pair16.txt 3 Traces_exp22_tif_pair16.txt 4 Traces_exp22_tif_pair16.txt ) vs: for i, group in df_all.groupby("filename"): print (group) Dem-Dexc Aem-Dexc Aem-Aexc S E fit frame \ 0 18150.0595 18548.2451 15263.7451 0.7063 0.5054 0.879 1.0 1 596.9286 7161.7353 1652.8922 0.8244 0.9231 0.879 2.0 2 93.2976 3112.3725 2632.6667 0.5491 0.9709 0.879 3.0 3 1481.1310 4365.4902 769.3333 0.8837 0.7467 0.879 4.0 4 583.1786 6192.6373 1225.5392 0.8468 0.9139 0.879 5.0 filename 0 Traces_exp22_tif_pair16.txt 1 Traces_exp22_tif_pair16.txt 2 Traces_exp22_tif_pair16.txt 3 Traces_exp22_tif_pair16.txt 4 Traces_exp22_tif_pair16.txt If want save output to pictures png: for i, group in df_all.groupby("filename"): plot = sns.regplot(data = group, x = "Dem-Dexc", y = "frame") fig = plot.get_figure() fig.savefig("{}.png".format(i.split('.')[0]))
type: AcceptedAnswer

http://stackoverflow.com/q/46750355
score: 2
downvote count: 0
has title: How scikit learn initializes the weight vector for MLPClassifier
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46750392
type: Question
upvote count: 2
answer count: 1
tagged with: neural-network
tagged with: scikit-learn
has body: I want to know how sklearn.neural_network.MLPClassifier initializes the weight vector. In the documentation page, there is nothing mentioned about how the weight vector is initialized by default. Thanks.
has answer: http://stackoverflow.com/a/46750392
tagged with: python
favorite count: 0

http://stackoverflow.com/a/46817070
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46817044
has body: Keyword arguments are only evaluated at the time, the function is defined. You have to use a mark, and check it, to do the additional calculation: def myFun1(a, b, c=None): if c is None: c = myFun2(a, b) d = a + b + c return d
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/46817044

http://stackoverflow.com/comment/80543178
comment on: http://stackoverflow.com/q/46798077
score: 0
type: QuestionComment
type: Comment
has text: You install Anaconda then have a cup of tea. It sorts this for you.

http://stackoverflow.com/q/46784028
has comment: http://stackoverflow.com/comment/80514693
upvote count: 11
has answer: http://stackoverflow.com/a/46784414
has comment: http://stackoverflow.com/comment/80514767
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33863550
score: 11
type: Question
tagged with: python-2.7
downvote count: 0
has body: I am trying to adjust the length of edge between two nodes by following code. But apparently it didn't work. Could anyone guide me where I am making mistake: Please note that I already look at this thread (How to specify edge length in Networkx for calculating shortest distance?) but didn't solve my issue import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_nodes_from([1,2]) G.add_edge(1,2, length = 10) # I also replaced length with len but no luck nx.draw(G,with_labels=True) plt.show() # display
favorite count: 0
has answer: http://stackoverflow.com/a/75822611
has answer: http://stackoverflow.com/a/57802298
answer count: 3
has title: edge length in networkx
tagged with: python

http://stackoverflow.com/comment/80760034
comment on: http://stackoverflow.com/a/46898111
score: 0
type: Comment
has text: Yes, you are correct I have merged two columns using lit(','). I have edited th question. Could you kindly look at it again.
type: AnswerComment

http://stackoverflow.com/q/46827196
tagged with: tkinter-entry
has body: I just started Tkinter a week ago and I am trying to link the GUI to an automatic code generation script written in Python. I have covered almost all cases with great help from this forum but this particular one has me stumped. I need 2 Entry Widgets and calculate their relationship to each other as soon as they are entered (i.e. no Button widget to trigger a function). I realize it must be done with events so after some trying I have come up with the following that works but it feels like I am not being 'pythonic' about it. from Tkinter import * root = Tk() root.title("Test") def OnValidate(S): if S.isdigit(): return True else: return False def insert_text_widg(widg,msg): widg.delete(1.0,END) widg.insert(INSERT,msg) # Checks the required conditions def check_var1(event): try: temp1=int(var1_ent.get()) temp2=int(var2_ent.get()) except ValueError: return if(temp2 &gt; temp1): insert_text_widg(log_text,"ERROR: Var2 cannot be greater than Var1") for ent in [var1_ent,var2_ent]: ent.configure(bg='indian red',fg='white') elif ((temp1 - temp2) % 2) == 1: insert_text_widg(log_text,"ERROR: Difference cannot be odd") for ent in [var1_ent,var2_ent]: ent.configure(bg='indian red',fg='white') else: log_text.delete(1.0,END) for ent in [var1_ent,var2_ent]: ent.configure(bg='white',fg='black') # Duplicate of check_var1 def check_var2(event): try: temp2=int(var2_ent.get()) temp1=int(var1_ent.get()) except ValueError: return if(temp2 &gt; temp1): for ent in [var1_ent,var2_ent]: ent.configure(bg='indian red',fg='white') insert_text_widg(log_text,"ERROR: Var2 cannot be greater than Var1") elif ((temp1 - temp2) % 2) == 1: for ent in [var1_ent,var2_ent]: ent.configure(bg='indian red',fg='white') insert_text_widg(log_text,"ERROR: Difference cannot be odd") else: log_text.delete(1.0,END) for ent in [var1_ent,var2_ent]: ent.configure(bg='white',fg='black') # App Configuration vcmd = (root.register(OnValidate),'%S') var1_lab = Label(root,text='Var1 :') var1_lab.pack() var1_ent = Entry(root,v…
tagged with: tkinter
type: AnsweredQuestion
downvote count: 0
has title: Tkinter - Trigger an event when two Entry Widgets are written into,regardless of order
accepted answer: http://stackoverflow.com/a/46849830
score: 1
has comment: http://stackoverflow.com/comment/80602637
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/46849830
has comment: http://stackoverflow.com/comment/80601978
answer count: 1
favorite count: 0
tagged with: events
tagged with: python

http://stackoverflow.com/comment/81272894
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46919545
has text: It works in the way you said. But it doesn't work when the batch is created like this `bs.add(session.prepare('insert into test.test(test_type, test_desc) values (?, ?)'), ['hello1', 'hello1'])`

http://stackoverflow.com/q/46760494
has comment: http://stackoverflow.com/comment/80466884
has comment: http://stackoverflow.com/comment/80466910
has title: Python : For loop to read a text file is not executing properly for all text file records
answer count: 1
has answer: http://stackoverflow.com/a/46760661
has comment: http://stackoverflow.com/comment/80466558
favorite count: 0
has comment: http://stackoverflow.com/comment/80466443
has comment: http://stackoverflow.com/comment/80466545
tagged with: python
has comment: http://stackoverflow.com/comment/80466671
has comment: http://stackoverflow.com/comment/80466522
has comment: http://stackoverflow.com/comment/80466564
type: AnsweredQuestion
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/80466523
type: Question
has comment: http://stackoverflow.com/comment/80466549
has body: i am having a doubt regarding the below code. i am trying to take a txt file as an input which will have the data as below aaaaaaaaaa bbbbbbbbbb cccccccccc and pass it to the searchForJob function to perform a search in different file but my for loop of input file is not executing properly it is not taking all the three lines of input file. It is only picking either the second line ( bbbbbbbb ) or third line ( ccccccccc ). Can someone pls help me on this. I am new to python language. def searchForJob(job): with open('some location/Jls.txt',"U") as lines: for line in lines: if line.find(job)!=-1: print(job + ' : Found') break; return jobNames = open('some location/JNames.txt') try: for job in jobNames: print(job) searchForJob(job) finally: jobNames.close()
accepted answer: http://stackoverflow.com/a/46760661
score: -1

http://stackoverflow.com/comment/80487754
has text: Well, add the first four (from what ever source they come) and the fifth will be `4863101420 - your_sum`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46771142

http://stackoverflow.com/comment/94017797
type: Comment
has text: Totally get it, you are so right, I just wanted to give the answer that worked for me since we are dealing with an isolated somewhat buggy and badly documented program meant to help people learn but confusing them in the process. I'd tried 50 different variations and once something flew, I wasn't going to ask questions. My Programming Lab is terrible. Your warning is valid.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53562301

http://stackoverflow.com/a/46848654
score: 3
has comment: http://stackoverflow.com/comment/80644712
upvote count: 3
answers question: http://stackoverflow.com/q/46848614
has body: You need to put the x.append(xn) inside the while loop. Otherwise only the last xn will be appended to x. x0 = 100 p = 5 N = 4 i = 0 x = [] while i &lt;=N: i += 1 xn = ((1 + (p/100))**i)*x0 x.append(xn) print(x)
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80644623

http://stackoverflow.com/comment/80594169
type: Comment
has text: Question: Why a text area? If all the fields are there, why not make individual textboxes?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46779416

http://stackoverflow.com/q/46812673
score: 2
downvote count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46812775
has title: Filtering values in pandas Dataframe by condition on index column
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/46812720
has body: Given that I have the following pandas DataFrame: arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']), np.array([0.01, 0.2, 0.3, -0.5, 0.6, -0.7, -0.8, 0.9])] tuples = list(zip(*arrays)) df_index = pd.MultiIndex.from_tuples(tuples, names=['A', 'B', 'measure']) df = pd.DataFrame(np.random.randn(8, 4), index=df_index) print(df) How can I filter all the values where for example the measure column (which is part of the index) is greater than 0.2? I have tried: df.loc[:,:,0.1:0.9] (and other variations of this, but I get the error "IndexingError: Too many indexers" Thanks, Gerald
has answer: http://stackoverflow.com/a/46812720
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/46812775
has answer: http://stackoverflow.com/a/46813279
has answer: http://stackoverflow.com/a/46812857
answer count: 4
favorite count: 0

http://stackoverflow.com/q/46858874
tagged with: amazon-s3
type: UnansweredQuestion
tagged with: boto3
has answer: http://stackoverflow.com/a/46935426
downvote count: 0
has title: boto3 S3: get_object error handling
has body: What is the best way to do error handling when getting an object from S3 using Python boto3? My approach: from botocore.exceptions import ClientError import boto3 s3_client = boto3.client('s3') try: s3_object = s3_client.get_object("MY_BUCKET", "MY_KEY") except ClientError, e: error_code = e.response["Error"]["Code"] # do error code checks here I am not sure if ClientError is the best Exception to use here. I know there is a Boto3Error class, but I do not think you can do error code checks similarly to ClientError.
favorite count: 0
score: 9
type: Question
tagged with: python
tagged with: error-handling
answer count: 1
upvote count: 9

http://stackoverflow.com/a/46872344
answers question: http://stackoverflow.com/q/46872094
type: AcceptedAnswer
has body: I think you need to set the right path export PATH=~/anaconda/bin:$PATH
has comment: http://stackoverflow.com/comment/80838347
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/46872094

http://stackoverflow.com/a/46776031
has comment: http://stackoverflow.com/comment/80498288
answers question: http://stackoverflow.com/q/46775666
downvote count: 0
type: Answer
score: 1
has body: Found it through an XPath: courtCases = driver.find_elements_by_xpath('//td[2]/font[@size="1"]') for courtCase in courtCases: print(courtCase.text) Notice how all court cases are on font size 1. If you were to leave out this attribute, you'd get the time as well.
upvote count: 1
has comment: http://stackoverflow.com/comment/80498064

http://stackoverflow.com/comment/80701356
comment on: http://stackoverflow.com/a/46877206
score: 0
type: Comment
has text: @user2357112 That wont work. If `var = B()`, `not isinstance(var, A)` returns `False`.
type: AnswerComment

http://stackoverflow.com/q/46814684
type: Question
has comment: http://stackoverflow.com/comment/80576733
favorite count: 0
has comment: http://stackoverflow.com/comment/80576866
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/80576808
has answer: http://stackoverflow.com/a/46817811
downvote count: 4
upvote count: 0
has title: Try to convert non whole number with $ sign to a float number in python
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/46814737
has body: I have this number: $13.96 and I want to make it 13.96 in python. like this: $13.96 >> 13.96
has comment: http://stackoverflow.com/comment/80576775

svd
type: Tag
tags question: http://stackoverflow.com/q/46774779
tag name: svd

http://stackoverflow.com/comment/80684513
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46860036
has text: hehe no need to be upset. `a + b` results in `error`. "What is the solution?" is not understandable.. I see. Well this is the python community, not used to that yet. You were even not the only one not understanding it. I guess python people think different
score: 0

http://stackoverflow.com/q/46752152
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: subtracting 4 columns of one csv file to another csv file and want output in Text file -Python
has answer: http://stackoverflow.com/a/46755107
type: Question
score: 0
answer count: 1
has body: I have two csv file both have same number of COULMN and ROW in same format...As showed below.. CSV 1 Row0 Row1 Row2 Row3 Row4 Row5 Row6 Row7 NIFTY 20170901 9.08 9937.65 9937.65 9937.65 9937.65 55600 NIFTY 20170901 9.16 9938.1 9938.1 9916.7 9917.5 58 NIFTY 20170901 9.17 9917.85 9919.2 9916 9917.6 58 NIFTY 20170901 9.18 9918.35 9918.75 9914.45 9915.3 58 NIFTY 20170901 9.19 9914.3 9914.8 9910.1 9910.55 58 CSV 2 Row0 Row1 Row2 Row3 Row4 Row5 Row6 Row7 NIFTY_F1 20170901 9.16 9945.3 9954.85 9941.8 9942.1 132300 NIFTY_F1 20170901 9.17 9942.5 9945.45 9942.5 9944.75 60300 NIFTY_F1 20170901 9.18 9944.6 9944.85 9942.05 9943.5 41625 NIFTY_F1 20170901 9.19 9943.3 9943.3 9937.55 9938.2 46425 NIFTY_F1 20170901 9.20 9938.75 9945.9 9938.75 9945.4 28650 NIFTY_F1 20170901 9.21 9945.9 9965 9945.9 9958.55 143250 So I want to do like this , c3=Row3(CSV2) - Row3(CSV1) ,c4= Row4(CSV2) - Row4(CSV1) , c5=Row5(CSV2) - Row5(CSV1) , c6=Row6(CSV2) - Row6(CSV1) ..... do this and make new text file which has Row0 , Row1 , Row2, C3, C4 ,C5 , C6 ,Row7 Row0,Row1,Row2 can be from anyone nd Row7 has to be from CSV2. How to do this?? don't know how to start and do this in python.

http://stackoverflow.com/q/46835119
has comment: http://stackoverflow.com/comment/80620141
type: AnsweredQuestion
score: 3
tagged with: list
has body: I have the following list: lst = ['AAAAAABB', 'AAAAAABA', 'AAAAAAAB', 'AAAAABAA', 'AAAAABAB', 'AAAAABBA'] And I'm getting this: lst = ['AAAAAAAB', 'AAAAAABA', 'AAAAAABB', 'AAAAABAA', 'AAAAABAB', 'AAAAABBA'] But I want something like this: lst = ['AAAAAAAB', 'AAAAAABA', 'AAAAABAA', 'AAAAAABB', 'AAAAABAB', 'AAAAABBA'] It means, I want to sort my list by Python considering the sequences of A and B in each list item. Actually, I want that all the combinations with 7*A should appear first. After that should come the combinations with more than one B.
has comment: http://stackoverflow.com/comment/80620190
possible better answer: http://stackoverflow.com/a/46835175
upvote count: 3
has answer: http://stackoverflow.com/a/46835175
accepted answer: http://stackoverflow.com/a/46835157
type: Question
tagged with: sorting
has comment: http://stackoverflow.com/comment/80619086
has comment: http://stackoverflow.com/comment/80620528
has comment: http://stackoverflow.com/comment/80620757
has comment: http://stackoverflow.com/comment/80620212
answer count: 2
linked to: http://stackoverflow.com/q/36139
downvote count: 0
has comment: http://stackoverflow.com/comment/80617921
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/46835157
has comment: http://stackoverflow.com/comment/80619487
tagged with: python
has title: Sorting list of AB strings based on the whole string

http://stackoverflow.com/q/46835221
accepted answer: http://stackoverflow.com/a/46858975
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80622888
has body: My old anaconda installation behaved strangely (updating didn't work properly but conda list did work fine). So I decided to reinstall Anaconda, that's where the problems started. After uninstalling the old Anaconda version via the Win10 remove programs tool, I downloaded the installer from the website and installed it. After Installation, no navigator was available, conda listsays the command conda is misspelled or missing, and when opening the anaconda prompt is just says anaconda3\scripts\activate.bat is misspelled or missing. The installed Python 3.6.2 version works just fine (confirmed via python --version). I tried reinstalling multiple times, with reboots in between each step, and even on different drives. Nothing worked. If someone has an idea what is causing this strange behavior I'd be very thankful.
possible better answer: http://stackoverflow.com/a/47003648
has title: Anaconda 5.0.0 Installation on Windows 10 not working properly
type: Question
has answer: http://stackoverflow.com/a/46858975
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/80624003
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47003648
favorite count: 0
has comment: http://stackoverflow.com/comment/80622979
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/80627352

http://stackoverflow.com/comment/80660611
type: AnswerComment
score: 0
type: Comment
has text: `df[df.applymap(np.isreal).values]` may be a bit more concise.
comment on: http://stackoverflow.com/a/46856468

http://stackoverflow.com/q/46841117
has comment: http://stackoverflow.com/comment/80630836
tagged with: pandas
has title: Data Periodicity - How to normalize?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80630155
type: UnansweredQuestion
score: 0
has body: I have a data set which contains 12 years of weather data. For first 10 years, the data was recorded per day. For last two years, it is now being recorded per week. I want to use this data in Python Pandas for analysis but I am little lost on how to normalize this for use. My thoughts Convert first 10 years data also into weekly data using averages. Might work but so much data is lost in translation. Weekly data cannot be converted to per day data. Ignore daily data - that is a huge loss Ignore weekly data - I lose more recent data. Any ideas on this?
has answer: http://stackoverflow.com/a/46842124
tagged with: periodicity
has comment: http://stackoverflow.com/comment/80630517
has comment: http://stackoverflow.com/comment/80630212
type: Question

http://stackoverflow.com/comment/80531954
score: 0
type: QuestionComment
type: Comment
has text: The uploaded file is an image in png format. Will renaming the uploaded file to logo.png solve the problem?
comment on: http://stackoverflow.com/q/46792270

http://stackoverflow.com/a/46848585
answers question: http://stackoverflow.com/q/46848323
has comment: http://stackoverflow.com/comment/80924265
score: 2
upvote count: 5
has comment: http://stackoverflow.com/comment/80644658
downvote count: 3
has comment: http://stackoverflow.com/comment/80647853
has body: after installing pandas datareader with: pip install pandas-datareader You can request the stock prices with this code: import pandas_datareader as pdr from datetime import datetime appl = pdr.get_data_yahoo(symbols='AAPL', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1)) print(appl['Adj Close'])
has comment: http://stackoverflow.com/comment/80966440
has comment: http://stackoverflow.com/comment/80646283
has comment: http://stackoverflow.com/comment/80644613
has comment: http://stackoverflow.com/comment/80649115
type: Answer
has comment: http://stackoverflow.com/comment/80645210

http://stackoverflow.com/comment/80523148
type: Comment
type: QuestionComment
has text: Ok sorry, maybe I should have added more details, but I wanted to keep the question as simple as possible... So I take from your answers that this is not possible? No I don't want to use a file because I want to call python commands from an external program by invoking a system command and I do not know in advance the order of the calls. I will edit the post to make it more clear what I want to do.
comment on: http://stackoverflow.com/q/46788266
score: 0

http://stackoverflow.com/comment/80636575
score: 0
type: Comment
has text: Since this only happens for pandas plots, I would guess that the pandas plotting wrapper for some reason thinks it needs to set the ticks invisible. Do you need to know the exact position in the pandas code where this goes wrong?
type: AnswerComment
comment on: http://stackoverflow.com/a/46829514

http://stackoverflow.com/comment/80627620
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46839593
has text: def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Course,self).save(*args,**kwargs)
score: 0

pathos
tags question: http://stackoverflow.com/q/46856313
tags question: http://stackoverflow.com/q/46899862
tag name: pathos
tags question: http://stackoverflow.com/q/46791359
type: Tag

http://stackoverflow.com/comment/80729950
comment on: http://stackoverflow.com/a/46890545
type: Comment
has text: Finally, I uninstalled both `django` versions and installed the newest and it's working!
score: 0
type: AnswerComment

http://stackoverflow.com/a/46787289
answers question: http://stackoverflow.com/q/46787178
type: Answer
upvote count: 1
has body: The Python script is expecting parameters, in particular dataset_name table_name and source. You are not passing any parameters to the script. I notice you've tried hard coding these parameters. So, in that case, just remove the cli params if you don't need them or mark them optional.
downvote count: 0
score: 1

http://stackoverflow.com/a/47138806
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46848095
answers question: http://stackoverflow.com/q/46848095
has body: The issue was that numpy was not being included properly with this setup.py file and workflow. I fixed this by changing it to be such that the cython extension is cythonized in it's own directory with it's own setup.py file into a .c file and that file is then added as a C extension in the package's setup.py file. This also has the benefit that people installing your module don't need cython as you can distribute the generated .c file with the package. I have created this complete, but simple, example on my github here.
score: 0

http://stackoverflow.com/comment/80525836
comment on: http://stackoverflow.com/a/46789564
type: AnswerComment
score: 0
type: Comment
has text: @chepner Edited to give both options the same value. I try to avoid basing my answers on personal preferences but sometimes they slip in.

matplotlib
tags question: http://stackoverflow.com/q/46879764
tags question: http://stackoverflow.com/q/46751667
tags question: http://stackoverflow.com/q/46765518
tags question: http://stackoverflow.com/q/46785782
tags question: http://stackoverflow.com/q/46867474
tags question: http://stackoverflow.com/q/46768859
tags question: http://stackoverflow.com/q/46824234
tags question: http://stackoverflow.com/q/46770903
tags question: http://stackoverflow.com/q/46792334
tags question: http://stackoverflow.com/q/46870672
tags question: http://stackoverflow.com/q/46751153
tags question: http://stackoverflow.com/q/46797357
tags question: http://stackoverflow.com/q/46790520
tags question: http://stackoverflow.com/q/46898063
tags question: http://stackoverflow.com/q/46798030
tag name: matplotlib
tags question: http://stackoverflow.com/q/46772500
tags question: http://stackoverflow.com/q/46791215
tags question: http://stackoverflow.com/q/46887520
tags question: http://stackoverflow.com/q/46863224
tags question: http://stackoverflow.com/q/46801187
tags question: http://stackoverflow.com/q/46856663
tags question: http://stackoverflow.com/q/46844655
tags question: http://stackoverflow.com/q/46810018
tags question: http://stackoverflow.com/q/46851963
tags question: http://stackoverflow.com/q/46793587
tags question: http://stackoverflow.com/q/46840152
tags question: http://stackoverflow.com/q/46756457
tags question: http://stackoverflow.com/q/46902190
tags question: http://stackoverflow.com/q/46885876
tags question: http://stackoverflow.com/q/46874689
tags question: http://stackoverflow.com/q/46755563
tags question: http://stackoverflow.com/q/46775615
tags question: http://stackoverflow.com/q/46890371
tags question: http://stackoverflow.com/q/46749763
tags question: http://stackoverflow.com/q/46901622
tags question: http://stackoverflow.com/q/46801285
tags question: http://stackoverflow.com/q/46768028
tags question: http://stackoverflow.com/q/46826089
tags question: http://stackoverflow.com/q/46762633
tags question: http://stackoverflow.com/q/46819664
tags question: http://stackoverflow.com/q/46862861
tags question: http://stackoverflow.com/q/46809103
tags question: http://stackoverflow.com/q/46877437
tags question: http://stackoverflow.com/q/46796451
tags question: http://stackoverflow.com/q/46846831
tags question: http://stackoverflow.com/q/46791559
tags question: http://stackoverflow.com/q/46842173
tags question: http://stackoverflow.com/q/46806318
tags question: http://stackoverflow.com/q/46795504
tags question: http://stackoverflow.com/q/46855458
tags question: http://stackoverflow.com/q/46808528
tags question: http://stackoverflow.com/q/46821227
tags question: http://stackoverflow.com/q/46812671
tags question: http://stackoverflow.com/q/46792386
tags question: http://stackoverflow.com/q/46788624
tags question: http://stackoverflow.com/q/46898492
tags question: http://stackoverflow.com/q/46790600
tags question: http://stackoverflow.com/q/46888623
tags question: http://stackoverflow.com/q/46834347
tags question: http://stackoverflow.com/q/46870095
tags question: http://stackoverflow.com/q/46797494
tags question: http://stackoverflow.com/q/46869328
tags question: http://stackoverflow.com/q/46889668
tags question: http://stackoverflow.com/q/46901475
tags question: http://stackoverflow.com/q/46886014
tags question: http://stackoverflow.com/q/46841396
tags question: http://stackoverflow.com/q/46769026
tags question: http://stackoverflow.com/q/46816400
tags question: http://stackoverflow.com/q/46796099
tags question: http://stackoverflow.com/q/46778712
tags question: http://stackoverflow.com/q/46793448
tags question: http://stackoverflow.com/q/46889189
tags question: http://stackoverflow.com/q/46825924
tags question: http://stackoverflow.com/q/46828689
tags question: http://stackoverflow.com/q/46812811
tags question: http://stackoverflow.com/q/46886226
tags question: http://stackoverflow.com/q/46825504
tags question: http://stackoverflow.com/q/46780845
tags question: http://stackoverflow.com/q/46827915

http://stackoverflow.com/comment/80559761
type: QuestionComment
comment on: http://stackoverflow.com/q/46806311
score: 2
has text: Possible duplicate of [Add SUM of values of two LISTS into new LIST](https://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list)
type: Comment

http://stackoverflow.com/comment/80682364
type: Comment
comment on: http://stackoverflow.com/a/46867111
score: 0
type: AnswerComment
has text: Comprehensions are cool, but they're a little hard to read sometimes. Especially the last example here with the ternary expression--you probably wouldn't want to do that in production code.

http://stackoverflow.com/a/46787507
has comment: http://stackoverflow.com/comment/80521515
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80521265
has comment: http://stackoverflow.com/comment/80521337
accepted answer of: http://stackoverflow.com/q/46787468
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80521686
has comment: http://stackoverflow.com/comment/80521707
answers question: http://stackoverflow.com/q/46787468
has comment: http://stackoverflow.com/comment/80521675
has body: I now understand based on your edit: (bought|sold).*?(\d+)@(\d+) The trick here is that, in your example, ".*" matches as many characters as possible, leaving only one digit matched by the subsequent "\d+". Adding the '?' makes it ungreedy, so it'll match as few characters as possible.
type: Answer

http://stackoverflow.com/a/62839445
upvote count: 83
answers question: http://stackoverflow.com/q/46844263
has body: I don't know if anyone is still attempting to use this thread, but I was attempting to upload a JSON to s3 trying to use the method above, which didnt quite work for me. Boto and s3 might have changed since 2018, but this achieved the results for me: import json import boto3 s3 = boto3.client('s3') json_object = 'your_json_object here' s3.put_object( Body=json.dumps(json_object), Bucket='your_bucket_name', Key='your_key_here' )
downvote count: 0
has comment: http://stackoverflow.com/comment/127614302
has comment: http://stackoverflow.com/comment/115627719
type: Answer
score: 83

http://stackoverflow.com/q/46793587
tagged with: python
has answer: http://stackoverflow.com/a/46795736
has comment: http://stackoverflow.com/comment/80533939
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80533977
tagged with: function
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80533883
score: -1
has body: I am new to python so I understand that this may be a stupid question, but I am having issues animating this. I can't see what the error is. I get this error TypeError: f() missing 1 required positional argument: ' I want to use matplotlib when animating, because I have not downloaded scitools. Any help at all would be very much appriciated import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style x = np.linspace(-6, 6) tmax = 1 tmin = -1 t = np.linspace(-1, 1) def f(x, t): term = (np.exp(-1*(x-3*t)**2))*np.sin(3*np.pi*(x-t)) return term max_f = f(x[-1], t[-1]) plt.ion() y = f(x, tmax) lines = plt.plot(x, y) plt.axis([x[0], x[-1], -0.1, max_f]) plt.xlabel('x') plt.ylabel('f') counter = 0 for ts in t: y = f(x, t) lines[0].set_ydata(y) plt.legend(['ts=%4.2f' % ts]) plt.draw() plt.savefig('tmp_%04d.png' % counter) counter += 1 fig = plt.figure() anim = animation.FuncAnimation(fig, f, interval = 1000, blit=True) fig = plt.figure() plt.axis([x[0], x[-1], -0.1, max_f]) lines = plt.plot([], []) plt.xlabel('x') plt.ylabel('f') plt.show() EDIT, full traceback: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 1699, in call return self.func(*args) File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 745, in callit func(*args) File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 370, in idle_draw self.draw() File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 351, in draw FigureCanvasAgg.draw(self) File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw self.figure.draw(self.renderer) File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\ma…
has title: Python, animate a function with two arguments
upvote count: 0
has comment: http://stackoverflow.com/comment/80534050
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: animation

http://stackoverflow.com/comment/80858650
has text: Thank you mrry. Nope this is the exact code I tried. After your comment, I tried the same code on my home desktop with with tf1.2 and, like you, i found that it works. So I think this is a problem with google ml-engine. When I install tensorflow1.3.0 in my local environment, the code works. But when I install tensorflow1.2.0 I run into the problem described above. I have also tried running this on the cloud ml-engine and that doesnt work either. Can you please help?Ive edited the tags to google cloud. please let me know if you need any clarifications
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46854474
score: 0

http://stackoverflow.com/a/46787348
has comment: http://stackoverflow.com/comment/80522514
accepted answer of: http://stackoverflow.com/q/46784964
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103743460
answers question: http://stackoverflow.com/q/46784964
has comment: http://stackoverflow.com/comment/96085682
score: 8
type: Answer
has comment: http://stackoverflow.com/comment/94554485
has comment: http://stackoverflow.com/comment/80523691
has comment: http://stackoverflow.com/comment/109772311
downvote count: 0
has comment: http://stackoverflow.com/comment/80574774
upvote count: 8
has comment: http://stackoverflow.com/comment/96012424
has body: Usually done by attempting to import cython and adjusting extensions to either Build pyx files with cython if cython is present Build C files if cython is not present For example: try: from Cython.Distutils.extension import Extension from Cython.Distutils import build_ext except ImportError: from setuptools import Extension USING_CYTHON = False else: USING_CYTHON = True ext = 'pyx' if USING_CYTHON else 'c' sources = glob('my_module/*.%s' % (ext,)) extensions = [ Extension(source.split('.')[0].replace(os.path.sep, '.'), sources=[source], ) for source in sources] cmdclass = {'build_ext': build_ext} if USING_CYTHON else {} setup(&lt;..&gt;, ext_modules=extensions, cmdclass=cmdclass) The source.split stuff is needed as cythonized extension names need to be in the form my_module.ext while glob requires path names like my_module/ext. See this repository for a real-world example. You should, however, include .c files in your git repo as well as the distributable otherwise when it comes time to build a distribution the .c files will be re-built and may or may not be the same files as were built on your machine. They may be built by another version of cython, for example, or on a different platform, producing different code. Cython is a static compiler - it's recommended to commit the files it produces to repository. It is strongly recommended that you distribute the generated .c files as well as your Cython sources, so that users can install your module without needing to have Cython available. See Cython documentation on distributing modules.
has comment: http://stackoverflow.com/comment/80570951
has comment: http://stackoverflow.com/comment/95979396
has comment: http://stackoverflow.com/comment/80529117

http://stackoverflow.com/a/46820924
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46820715
answers question: http://stackoverflow.com/q/46820715
has comment: http://stackoverflow.com/comment/80589566
has body: When parsing a text file, you'll almost always want to skip empty lines. Here's an idomatic pattern for this: for line in file: line = line.strip() if not line: continue # process line If your file format depends on whitespace on the non-empty lines, you can join lines 2 and 3 to if not line.strip().

http://stackoverflow.com/comment/80666720
comment on: http://stackoverflow.com/q/46859511
has text: You might want to use a tuple instead.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80715617
has text: Anything can be in the other cells
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46884151

http://stackoverflow.com/comment/80586156
has text: Actually there is an issue with `j`. `j.shape` returns `17` when there are actually `6` columns in `t`. How would you resolve this?
type: Comment
comment on: http://stackoverflow.com/a/46812514
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80601074
type: AnswerComment
type: Comment
has text: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
score: 0
comment on: http://stackoverflow.com/a/46826725

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/46826093
tags question: http://stackoverflow.com/q/46759730

http://stackoverflow.com/q/46795836
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80572012
answer count: 1
tagged with: interpolation
has comment: http://stackoverflow.com/comment/80545086
tagged with: python
linked to: http://stackoverflow.com/q/46812804
has comment: http://stackoverflow.com/comment/80543553
type: AnsweredQuestion
has title: How to interpolate numpy.polyval and numpy.polyfit python
has comment: http://stackoverflow.com/comment/80544516
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46892377
has comment: http://stackoverflow.com/comment/80544404
has body: I did a numpy.polyfit() for latitude, longitude, &amp; altitude data for a satellite orbit and interpolated (50 points) with numpy.polyval(). Now, I want to just take a window (0-4.5 degrees longitude) and do a higher resolution interpolation (6,000 points). I think that I need to use the fit coefficients from the first low res fit in order to interpolate for my longitude window, and I am not quite sure how to do this. Inputs: lat = [27.755611104020687, 22.50661883405905, 17.083576087905502, 11.53891099628959, 5.916633366002468, 0.2555772624429494, -5.407902834141322, -11.037514984810027, -16.594621304857206, -22.03556688048686, -27.308475759820045, -32.34927891621322, -37.07690156937186, -41.38803163295967, -45.15306971601912, -48.21703193866987, -50.41165326774015, -51.58419672864487, -51.63883932997542, -50.57025116952513, -48.46557920053242, -45.47329014246061, -41.76143266388077, -37.48707787049647, -32.782653540783, -27.754184631685046, -22.48503337048438, -17.041097574740743, -11.475689837873944, -5.833592289780744, -0.1543286595142316, 5.525119007560692, 11.167878192881306, 16.73476477885508, 22.18160021405449, 27.455997555900108, 32.493386953033685, 37.21222272985329, 41.508824407948275, 45.25350232626601, 48.291788915858554, 50.45698534747271, 51.59925055739275, 51.62660832560593, 50.53733379179681, 48.420673231121725, 45.42531420150485, 41.71819693220144, 37.45473807165676, 32.76569228387106] lon = [-109.73105744378498, -104.28690174554579, -99.2435132929552, -94.48533149079628, -89.91054414962821, -85.42671400689177, -80.94616150449806, -76.38135021210172, -71.6402674905218, -66.62178379632216, -61.21120467960157, -55.27684029674759, -48.66970878028004, -41.23083703244677, -32.813881865289346, -23.332386757370532, -12.832819226213942, -1.5659455609661785, 10.008077792630402, 21.33116444634303, 31.92601575632583, 41.51883213364072, 50.04498630545507, 57.58103957109249, 64.26993028992476, 70.2708323505337, 75.73441871754586, 80.7944079829813, 85.5673481304…
has comment: http://stackoverflow.com/comment/80544616
tagged with: arrays
has comment: http://stackoverflow.com/comment/80544181
has answer: http://stackoverflow.com/a/46892377

http://stackoverflow.com/a/46781740
upvote count: 1
has comment: http://stackoverflow.com/comment/80509821
has comment: http://stackoverflow.com/comment/80509888
answers question: http://stackoverflow.com/q/46781708
has comment: http://stackoverflow.com/comment/80509840
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46781708
type: Answer
has body: you can use the following code to achieve this: with open(title.text, 'w', encoding='UTF-8') as f: json.dump(data, f, ensure_ascii=False)
score: 1

http://stackoverflow.com/a/46857390
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46857132
has body: I ran the integral on wolfram alpha and it says it doesn't converge (the computation takes a while, so unless you have a wolfram premium account it might not complete): Try out an integral you know converges. So try out something like import sympy as sp sp.init_printing(wrap_line=False, no_global=True) a = sp.Symbol('a') I = sp.integrate(a**3,a) You should get a**4/4
score: 0

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/46779708
tags question: http://stackoverflow.com/q/46842508

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/46904135
tags question: http://stackoverflow.com/q/46818429
tags question: http://stackoverflow.com/q/46788179
tags question: http://stackoverflow.com/q/46863602
tags question: http://stackoverflow.com/q/46834421
tags question: http://stackoverflow.com/q/46832727
type: Tag

http://stackoverflow.com/q/46816012
has body: I've successfully deployed locally trained TF model to ML-engine however upon invoking test command for prediction: gcloud ml-engine predict --model=$modelname --text-instances=test.txt I got this error: { "error": "Prediction failed: Error processing input: Expected float32, got u'0.18189938740640676506643558241194 … 0.23270735134367070973127056277008' of type 'unicode' instead." } The model expects an input of shape (28, 28, 1) If someone could clarify what I'm doing wrong or could provide an example of correct format for input .txt or .json for this kind of data? Thanks in advance!
tagged with: tensorflow-serving
downvote count: 0
tagged with: gcloud
favorite count: 0
has title: gcloud ml-engine predict error "Expected float32 got unicode"
linked to: http://stackoverflow.com/q/46216095
tagged with: python
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: google-cloud-ml-engine
type: Question
score: 3
has comment: http://stackoverflow.com/comment/80580756

http://stackoverflow.com/a/46774305
score: 2
answers question: http://stackoverflow.com/q/46774069
upvote count: 2
has body: Check type of your numbers before converting them to strings. It seems that they are floats, rather than integers. If this is the case, convert your numbers to integers: df = pd.DataFrame([123.0, 456.0]) df = df.apply(int, axis=1) 0 123 1 456 Then, convert it into strings: df = df.apply(str) print(df.iloc[1]) '456'
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80679241
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46865478
has text: The problem is that, if the answer is wrong and I want to return to the question it is going to return to the beginning where I defined logic_ques() and the script is way under, so basically the program ends.
type: Comment

http://stackoverflow.com/q/46806711
has title: Parsing http return broken link
answer count: 1
has body: I'am trying to parse image from some Telegram channel, as example https://t.me/versusbattlerus, the image is on this block "img class="tgme_page_photo_image" src="https://... " but every time method returns different and not working links, why this happens? I'am using python 3.6, urllib, beautifulsoup4 Method import urllib.request from bs4 import BeautifulSoup def get_html(url): response = urllib.request.urlopen(url) return response.read() def parse(html): soup = BeautifulSoup(html, 'lxml') image = soup.find('img', class_="tgme_page_photo_image") print(image) #return image def main(): parse(get_html('https://t.me/versusbattlerus')) if __name__ == '__main__': main()
tagged with: parsing
favorite count: 0
tagged with: beautifulsoup
tagged with: telegram
upvote count: 2
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/46807392
has comment: http://stackoverflow.com/comment/80563894
downvote count: 1
type: Question

http://stackoverflow.com/comment/80490560
comment on: http://stackoverflow.com/q/46772012
has text: Right please [edit] your question to reflect that. Are you sure you're activating your virtual environment and what does `boto3.__file__` show you?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46835349
type: AnsweredQuestion
upvote count: 1
tagged with: excel
type: Question
accepted answer: http://stackoverflow.com/a/46838788
has body: def test(sheet, row=2): writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl') df1 = pd.DataFrame(['Title'], index=[0]) df2 = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 'income': [40000, 50000, 42000]}) df1.to_excel(writer, sheet, startrow=0, startcol=0, header=None, \ index=False) df2.to_excel(writer, sheet, startrow=row, index=False) writer.save() writer.close() test('aaa') In the moment, this little function creates a single Excel worksheet. Description : Assume that Excel sheet exists. I want to write something else below the existing lines with the following code. In [1]: import pandas as pd In [2]: writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl') In [4]: from openpyxl import load_workbook In [5]: book = load_workbook("testing.xlsx") In [6]: df3 = pd.DataFrame({'amount': ['Chest', 'Bras', 'Braa'], ...: 'income': [40000, 50000, 42000]}) ...: In [8]: writer.book = book In [9]: ws = book.get_sheet_by_name('aaa') In [10]: writer.book Out[10]: <openpyxl.workbook.workbook.Workbook at 0x7f9add4e3048> In [12]: writer.book.sheetnames Out[12]: ['aaa'] In [13]: row = ws.max_row In [14]: row Out[14]: 6 In [15]: df3.to_excel(writer, "aaa", startrow=row + 2, index=False) In [16]: writer.save() This code worked almost how I wanted. It creates a new worksheet aaa1, and put the content of df at the 8th line as it should normally be. Instead of creating the new sheet aaa1, I want the content of aaa1 be below the content of aaa. How could I fix that so that it works?
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has title: Displaying below an existing content worksheet
has answer: http://stackoverflow.com/a/46838788
tagged with: python

http://stackoverflow.com/comment/80675190
type: QuestionComment
has text: No i don't know
score: 0
comment on: http://stackoverflow.com/q/46863879
type: Comment

http://stackoverflow.com/comment/80661007
type: QuestionComment
comment on: http://stackoverflow.com/q/46856620
has text: Oh, okay, i didnt know that this is not for begginers also. Thanks anyway, i will try your suggestion.
score: 0
type: Comment

http://stackoverflow.com/q/46830624
has answer: http://stackoverflow.com/a/46830725
accepted answer: http://stackoverflow.com/a/46830749
has comment: http://stackoverflow.com/comment/80608670
has title: converting list to dictionary and adding values to them
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80608950
has comment: http://stackoverflow.com/comment/80608669
has answer: http://stackoverflow.com/a/46830749
type: Question
has body: I have a list I want to convert to dictionary and add corresponding random values to them, tried the previous answers here nothing seemed to work. This is the list: wordlist = ["apple","durian","banana","durian","apple","cherry", "cherry","mango","apple","apple","cherry","durian","banana", "apple","apple","apple","apple","banana","apple"] Any answer with simple syntax will be appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/80609845
score: 0
has comment: http://stackoverflow.com/comment/80609483
answer count: 2
possible better answer: http://stackoverflow.com/a/46830725

http://stackoverflow.com/a/46783217
downvote count: 0
has body: You'll have to output the variables' content somehow. You're spawning a new process which will not propagate the environment variables back, so your python app will not see those values. You could either make the script echo those to some file, or to the standard output if possible. (Technically, it would be possible to stop the process and extract the values if you really wanted to hack that, but it's a bad idea.)
accepted answer of: http://stackoverflow.com/q/46783161
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46783161
type: AcceptedAnswer

http://stackoverflow.com/a/46884420
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46883868
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/46883868
has body: As you have 90 tasks to run, you may need to increase the number of threads and if they are calculation sensitive, you should also use ProcessPoolExecutor: from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor from apscheduler.schedulers.background import BackgroundScheduler executors = { 'default': ThreadPoolExecutor(90), # max threads: 90 'processpool': ProcessPoolExecutor(20) # max processes 20 } scheduler = BackgroundScheduler(executors=executors) scheduler will use default executor default, and you can specify executor by scheduler.add_interval_job(triggerTask, interval_time, executor="&lt;executor's name&gt;").
has comment: http://stackoverflow.com/comment/80716658
upvote count: 8
has comment: http://stackoverflow.com/comment/80717586
has comment: http://stackoverflow.com/comment/80716309

http://stackoverflow.com/a/46888198
answers question: http://stackoverflow.com/q/46888033
score: 1
type: Answer
upvote count: 2
has body: Use __setattr__ and __delattr__ on your class.
downvote count: 1

http://stackoverflow.com/comment/80744604
type: Comment
comment on: http://stackoverflow.com/a/46897363
score: 0
type: AnswerComment
has text: Your solution explains one of the many problems with OP's code, but it doesn't solve much.

http://stackoverflow.com/comment/80445585
type: QuestionComment
has text: Have you tried using a DateInput widget for your date fields? https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#timeinput
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46749405

http://stackoverflow.com/a/46896537
score: 2
downvote count: 0
has body: That's because it short-circuits and returns "Yeah" on the first logical evaluation: &gt;&gt;&gt; False or True or True True &gt;&gt;&gt; False or 'exit' 'exit' &gt;&gt;&gt; bool(False or 'exit') True &gt;&gt;&gt; I recommend doing this: if Exit.lower() in ('yeah', 'y', 'yes'): print("okay") elif Exit.lower() in ('no', 'nah', 'n'): print ("Terminating Program") else: print ("Terminating Program")
answers question: http://stackoverflow.com/q/46896512
upvote count: 2
type: Answer

http://stackoverflow.com/q/46801449
has comment: http://stackoverflow.com/comment/80551541
downvote count: 0
answer count: 1
favorite count: 0
has body: I'm experiencing extremely slow inserts in a MongoDB (roughly 200 sec/insert) and I'm not at all sure why. I have a CSV file of anonymised usernames (ints), anonymised comment id (ints), and comments. All of this is read in as strings, but the first two fields could be cast to ints without any issue. The database contains collection of 100M records, and right now am trying to build a mapping users with their comment IDs, which is written into another collection. There are roughly 60K users on which the 100M comments are distributed. That is build user_id = [comment_id0,...,comment_idN] for each user and insert that into the database for quicker fetching of all of a users comments. def save_user_comments(dataset): usrs = defaultdict(list) updatebar = tqdm(total = 100000000, desc = 'Generating user-comment map', leave = False) pool = mp.Pool() for i, (user_id, comment_id, _) in enumerate(dataset): usrs[str(user_id)].append(comment_id) updatebar.update(1) prev = 0 keys, vals = list(usrs.keys()), list(usrs.values()) results = pool.map_async(write_user, zip(keys, vals)).get() progbar = tqdm(total = 67377, desc = 'Users Inserted', leave = False ) def write_user(itempair): usr, comments = itempair db = MongoClient(host = some_ip, port = some_port).GenderSpectrum table = db.user if db.user.find_one({'user_id': str(usr)}): progbar.update(1) return u_obj = {} obj = db.data.find_one({'user_id': str(usr)}) u_obj['comment_ids'] = comments u_obj['_id'] = str(usr) u_obj['is_female'] = obj['is_female'] u_obj['user_id'] = str(usr) db.user.insert_one(u_obj) progbar.update(1) return 1 The only things I can see in this code that would slow it down is that a new connection is created for each insert. However, having tried with batches of 500 documents to be inserted using one connection (using both single and multi document insert) is even slower. So is running this code sequentially. Does someone have a better suggestion? MongoDB Version: v3.4.9 PyMongo Version: 3.5.1 Python Version: 3…
has title: PyMongo Insert excruciating slow data base with ~ 100M records
upvote count: 1
tagged with: python
tagged with: pymongo-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80581346
score: 1
tagged with: pymongo
type: Question
has answer: http://stackoverflow.com/a/46805479
accepted answer: http://stackoverflow.com/a/46805479
tagged with: mongodb

http://stackoverflow.com/comment/80641047
comment on: http://stackoverflow.com/a/46846713
has text: @navre3 this will replace the first occurrence of `'***TITLE***'` with the first item in `t` and so on.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/46862693
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46862549
type: Answer
has body: Use break and anyway stop using print for debugging for row in contents: print('begin loop') if username == row[4]: print("Username found") if password == row[3]: print("Password found") main() break else: print("not found")
upvote count: 1

http://stackoverflow.com/q/46774399
tagged with: pandas
has answer: http://stackoverflow.com/a/46775152
has comment: http://stackoverflow.com/comment/80495561
favorite count: 0
upvote count: 2
tagged with: python
tagged with: vectorization
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46775152
has comment: http://stackoverflow.com/comment/80494997
possible better answer: http://stackoverflow.com/a/46774705
has body: I am very new to Python, so I assume this is probably a basic question. I found a few solutions online but could not find the exact thing I was looking for. Currently I am searching for a way to find the "low median" over 3 columns of data. If only 2 values of the 3 columns are populated then I would like to take the lower value. Here is what I have found so far df['median']=np.nanmedian(df'val1','val2','val3', axis=1) The above was not a workable solution as I did not see any information on an argument to take the low median when there are an even number of values. Additionally I found that there is a function that does what I am looking for statistics.median_low() However, I am unsure how to apply it over multiple columns without using some sort of function that calculates each median row-wise one at a time (ie. a loop or apply function). Ideally, I would like a vectorized solution using this function which will calculate the medians simultaneously. Thank you for your assistance.
has answer: http://stackoverflow.com/a/46774705
has comment: http://stackoverflow.com/comment/80495551
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/80494809
downvote count: 0
has title: Efficiently finding the low median over multiple columns
tagged with: statistics

http://stackoverflow.com/q/46857968
has body: i just started a graphics lecture and wanted to play around with python2.7 since we will need this for our lecture. We were instructed to install the miniconda distribution from https://conda.io/miniconda.html and then install further libraries using conda now ive got the following imports: import math import numpy as np import mayavi.mlab as mlab import pickle and this funcion: def trimesh(F, V, new_figure=True): x = V[:,0] y = V[:,1] z = V[:,2] mlab.triangular_mesh(x, y, z, F) if new_figure: mlab.figure() as for now it seems that the line mlab.triangular_mesh() is giving me an issue. I get the following error in my PyCharm console: Traceback (most recent call last): File "/Users/ronaldbrenner/PycharmProjects/untitled/transformation.py", line 50, in &lt;module&gt; trimesh(F, V) File "/Users/ronaldbrenner/PycharmProjects/untitled/transformation.py", line 26, in trimesh mlab.triangular_mesh(x, y, z, F) File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/helper_functions.py", line 37, in the_function return pipeline(*args, **kwargs) File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/helper_functions.py", line 77, in __call__ scene = tools.gcf().scene File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/figure.py", line 113, in gcf engine = get_engine() File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/engine_manager.py", line 101, in get_engine return self.new_engine() File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/engine_manager.py", line 146, in new_engine check_backend() File "/Users/ronaldbrenner/miniconda2/lib/python2.7/site-packages/mayavi/tools/engine_manager.py", line 49, in check_backend ''') ImportError: Could not import backend for traits _______________________________________________________________________________ Make sure that you have either the TraitsBackendWx or the TraitsBackendQt projects installed. If you i…
has comment: http://stackoverflow.com/comment/80674003
has comment: http://stackoverflow.com/comment/80698628
tagged with: mayavi
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80664169
has title: ImportError on mayavi.mlab function
tagged with: conda
type: Question
has comment: http://stackoverflow.com/comment/80670075
has comment: http://stackoverflow.com/comment/80664333
has comment: http://stackoverflow.com/comment/80664598
has comment: http://stackoverflow.com/comment/80665699
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80663876
has comment: http://stackoverflow.com/comment/80676682
tagged with: python

http://stackoverflow.com/a/46810378
has comment: http://stackoverflow.com/comment/80568087
accepted answer of: http://stackoverflow.com/q/46810334
score: 0
answers question: http://stackoverflow.com/q/46810334
type: AcceptedAnswer
type: Answer
has body: Your variable is called structure, remove the s {{ structure.name }} About the SA password protected entry checker I found this thread, it doesn't seems to be django but the antivirus or some browser extension.

http://stackoverflow.com/comment/80478422
type: QuestionComment
type: Comment
has text: Python strings are basically immutable list, you can just use slice i think, test[splitat:splitat+3] for exemple.
score: 0
comment on: http://stackoverflow.com/q/46766530

http://stackoverflow.com/comment/80621002
comment on: http://stackoverflow.com/a/46835859
has text: again it's wrong the first solution where len(c) was 69 was the closest but it needed to continue to 1002 this one gets most values wrong look how c is [0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46776280
linked to: http://stackoverflow.com/q/6864994
has answer: http://stackoverflow.com/a/46957839
has comment: http://stackoverflow.com/comment/80741752
has comment: http://stackoverflow.com/comment/80610823
has comment: http://stackoverflow.com/comment/80786589
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80740623
favorite count: 0
has title: Finding shapes using Modified Hausdorff Distance
accepted answer: http://stackoverflow.com/a/46957839
has comment: http://stackoverflow.com/comment/80741600
tagged with: python
tagged with: computer-vision
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24073127
tagged with: pattern-recognition
upvote count: 3
downvote count: 3
has body: I have 2 images that have same shapes present in them but are arranged at different places. I want to match those images correctly. Steps performed... Get contour from Source Image. Get contours from target Image. Compare contours from source to target using Modified Hausdorff Distance. Get the smallest value as the match. def modified_hausdorff(A,B): D = cdist(A,B) #euclidean distance fhd = np.mean(np.min(D,axis=0)) rhd = np.mean(np.min(D,axis=1)) return max(fhd,rhd) Source image. Target image.
tagged with: image-processing
type: Question

http://stackoverflow.com/q/46749969
has body: I am trying to create a simple class that inputs a list then appends to the list with a function called "add" which is also defined in the same class. I keep getting this error: 'list' object has no attribute 'a' class try1: def __init__(self, a=[]): self.a = a print(a) return def add(self, b=None): self.a.append(b) print(a) return if __name__ == "__main__": c=try1(['a', 'b', 'c']) d = ['d', 'e', 'f'] try1.add(d)
answer count: 2
has answer: http://stackoverflow.com/a/46750054
has comment: http://stackoverflow.com/comment/80445963
linked to: http://stackoverflow.com/q/1132941
favorite count: 0
has comment: http://stackoverflow.com/comment/80445976
tagged with: class
has title: List not passing between methods inside a class definition
possible better answer: http://stackoverflow.com/a/46750054
tagged with: python
accepted answer: http://stackoverflow.com/a/46750031
upvote count: 2
downvote count: 1
type: AnsweredQuestion
score: 1
tagged with: methods
type: Question
has answer: http://stackoverflow.com/a/46750031

http://stackoverflow.com/a/46778014
score: 0
has comment: http://stackoverflow.com/comment/80594447
answers question: http://stackoverflow.com/q/46766174
has comment: http://stackoverflow.com/comment/80594330
has comment: http://stackoverflow.com/comment/80594470
has body: MongoDB will execute the aggregation stages (in most cases) in the exact order you specify. The $match operator does not give any guarantee of the output order. So you would want to put your $match at the start of your pipeline (followed by the $sort) which is a good idea for performance reasons anyway.
has comment: http://stackoverflow.com/comment/80587262
type: Answer

http://stackoverflow.com/comment/80634831
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46843694
score: 0
has text: What is the error you are seeing ?

linux
tags question: http://stackoverflow.com/q/46789568
tags question: http://stackoverflow.com/q/46815141
tags question: http://stackoverflow.com/q/46815585
tags question: http://stackoverflow.com/q/46898963
tags question: http://stackoverflow.com/q/46756380
tags question: http://stackoverflow.com/q/46819085
tags question: http://stackoverflow.com/q/46780385
tags question: http://stackoverflow.com/q/46867014
type: Tag
tags question: http://stackoverflow.com/q/46882028
tags question: http://stackoverflow.com/q/46826969
tags question: http://stackoverflow.com/q/46750654
tags question: http://stackoverflow.com/q/46788908
tags question: http://stackoverflow.com/q/46870447
tags question: http://stackoverflow.com/q/46800494
tags question: http://stackoverflow.com/q/46887939
tags question: http://stackoverflow.com/q/46749871
tag name: linux
tags question: http://stackoverflow.com/q/46836916
tags question: http://stackoverflow.com/q/46888359
tags question: http://stackoverflow.com/q/46901815
tags question: http://stackoverflow.com/q/46891422
tags question: http://stackoverflow.com/q/46865153
tags question: http://stackoverflow.com/q/46790295
tags question: http://stackoverflow.com/q/46795927
tags question: http://stackoverflow.com/q/46833006
tags question: http://stackoverflow.com/q/46854305
tags question: http://stackoverflow.com/q/46875981
tags question: http://stackoverflow.com/q/46758555
tags question: http://stackoverflow.com/q/46831246
tags question: http://stackoverflow.com/q/46897967
tags question: http://stackoverflow.com/q/46869343
tags question: http://stackoverflow.com/q/46768006
tags question: http://stackoverflow.com/q/46837914
tags question: http://stackoverflow.com/q/46869530
tags question: http://stackoverflow.com/q/46813448
tags question: http://stackoverflow.com/q/46769620
tags question: http://stackoverflow.com/q/46752279

http://stackoverflow.com/comment/80487733
comment on: http://stackoverflow.com/q/46770939
score: 0
has text: I'm unable to understand the query output. Can you please add the formatted result in the question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80653205
has text: Have you given the right process id ? Which command are you talking about ?
type: AnswerComment
comment on: http://stackoverflow.com/a/46852262
score: 0
type: Comment

http://stackoverflow.com/comment/80661645
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46856979
has text: what is the final purpose for `self.csvFileArray`? should all the rows be saved to a new file?
score: 0

http://stackoverflow.com/a/46778793
answers question: http://stackoverflow.com/q/46778617
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80505885
has body: Regarding part 2 str(v) output of a float v shows the shortest representation for which v == float(str(v)) is true. Python docs say: Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display &gt;&gt;&gt; 0.1 0.1000000000000000055511151231257827021181583404541015625 That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead &gt;&gt;&gt; 1 / 10 0.1 Just remember, even though the printed result looks like the exact value of 1/10, the actual stored value is the nearest representable binary fraction. Regarding part 3, Python docs say: The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, Decimal('3.00000') records all five zeros even if the context precision is only three
downvote count: 0

http://stackoverflow.com/q/46878755
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84670503
favorite count: 0
type: Question
tagged with: python
tagged with: asynchronous
tagged with: tws
tagged with: python-3.x
upvote count: 2
has title: Python: Wait for asynchronous callback to finish
has body: I am currently working with the TWS Brokerage API For requesting market data, they have asynchronous function calls. So for example to get the data for a stock you would call reqMKtData(..) as below. self.reqMktData(1003, ContractSamples.AAPLStock(), "", False, False, []) Then you would asynchronously receive the price data with another function called tickPrice. def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib): super().tickPrice(reqId, tickType, price, attrib) print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:", price, "CanAutoExecute:", attrib.canAutoExecute, "PastLimit", attrib.pastLimit) I want to call reqMktData and then have the stock price available on the next line of code. How would I do this? self.reqMktData(1003, ContractSamples.AAPLStock(), "", False, False, []) aaplPrice = # Wait for tickPrice to execute, then assign the price value from tickPrice to aaplPrice
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94113015

http://stackoverflow.com/q/46782048
tagged with: python
has comment: http://stackoverflow.com/comment/80512728
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/80518811
tagged with: wagtail
has body: I'm working on a Django/Wagtail app and I'm trying to create generic, reusable components in my models. I'm trying to follow the way the built-in Image classes work since they can be attached to any other object type. However I keep getting an error: Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f78b26ad8c8&gt; Traceback (most recent call last): File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/core/management/commands/runserver.py", line 114, in inner_run self.validate(display_num_errors=True) File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/core/management/base.py", line 469, in validate return self.check(app_configs=app_configs, display_num_errors=display_num_errors) File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/core/management/base.py", line 482, in check include_deployment_checks=include_deployment_checks, File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/.../runtime/lib/python3.4/site-packages/wagtail/wagtailadmin/checks.py", line 64, in get_form_class_check edit_handler = cls.get_edit_handler() File "/.../runtime/lib/python3.4/site-packages/wagtail/utils/decorators.py", line 55, in __call__ return self.value File "/.../runtime/lib/python3.4/site-packages/Django-1.8.14-py3.4.egg/django/utils/functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/.../runtime/lib/python3.4/site-packages/wagtail/utils/decorators.py", line 51, in value return self.fn(self.cls) File "/.../runtime/lib/python3.4/site-packages/wagtail/wagtailadmin/edit_handlers.py", line 824, in get_edit_handler return EditHandler.bind_to_model(cls) File "/…
score: 0
has comment: http://stackoverflow.com/comment/80534888
has title: Django/Wagtail trying to create generic child classes
tagged with: django

ipython
tags question: http://stackoverflow.com/q/46880699
tags question: http://stackoverflow.com/q/46792595
tag name: ipython
tags question: http://stackoverflow.com/q/46823747
tags question: http://stackoverflow.com/q/46852426
tags question: http://stackoverflow.com/q/46846860
type: Tag
tags question: http://stackoverflow.com/q/46809103
tags question: http://stackoverflow.com/q/46844378
tags question: http://stackoverflow.com/q/46824287
tags question: http://stackoverflow.com/q/46902362
tags question: http://stackoverflow.com/q/46790850
tags question: http://stackoverflow.com/q/46879926
tags question: http://stackoverflow.com/q/46895616
tags question: http://stackoverflow.com/q/46898382

http://stackoverflow.com/comment/80564608
comment on: http://stackoverflow.com/q/46806552
has text: try to connect to database by `./manage.py dbshell` and then run your select.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/56420231
answers question: http://stackoverflow.com/q/46773854
type: Answer
downvote count: 0
score: 1
has body: Your generator is doing a lot of unnecessary work. It checks all primes up to n when it only needs to check primes up to the square root of n. Here is a modified version of your generator function with the unnecessary work removed: from time import time t = time() def gen_primes(): primes = [] yield 2 n = 3 while True: is_prime = True upper_limit = n ** .5 for p in primes: if n % p == 0: is_prime = False break elif p &gt; upper_limit: break if is_prime: primes.append(n) yield n n += 2 # only need to check divisibility by odd numbers sum = 0 for prime in gen_primes(): if prime &gt; 2_000_000: break else: sum += prime print("time:", time() - t) print(sum) This takes 2.3 seconds on my computer. The version without the generator takes 4.8 seconds on my computer. If you're interested in a much more efficient algorithm for finding prime numbers, check out the Sieve of Eratosthenes. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
upvote count: 1

http://stackoverflow.com/q/46903282
has title: Python 3. Trying to create a dictionary using 3 lists
score: 1
has comment: http://stackoverflow.com/comment/80753315
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80753425
has body: I'm currently working on a school project and I'm have difficulties on the very end of my program. def index_district(): dist = input("Please enter district: ") district=[dist] candidates = [] var1 = 1 while var1: var1 += 1 candidates_names = input('Enter name of candidate for the district. Hit enter again to end ') if candidates_names == '': break candidates.append(candidates_names) votes = [] var2 = 1 while var2: var2 += 1 candidates_votes = input('Enter number of votes for the district. Hit enter again to end ') if candidates_votes == '': break votes.append(candidates_votes) parties = [] var3 = 1 while var3: var3 += 1 candidates_parties = input('Enter parties for the district. Hit enter again to end ') if candidates_parties == '': break parties.append(candidates_parties) canidate_parties = dict(zip(parties, candidates)) party_votes = dict(zip(parties, votes)) dic = dict(zip(district, zip(canidate_parties, party_votes))) print(dic) index_district() And my output is Please enter district: qwe Enter name of candidate for the district. Hit enter again to end as Enter name of candidate for the district. Hit enter again to end ds Enter name of candidate for the district. Hit enter again to end xc Enter name of candidate for the district. Hit enter again to end Enter number of votes for the district. Hit enter again to end 123 Enter number of votes for the district. Hit enter again to end 234 Enter number of votes for the district. Hit enter again to end 345 Enter number of votes for the district. Hit enter again to end Enter parties for the district. Hit enter again to end rrr Enter parties for the district. Hit enter again to end eee Enter parties for the district. Hit enter again to end www Enter parties for the district. Hit enter again to end {'qwe': ('rrr', 'rrr')} Process finished with exit code 0 however my end code is supposed to look something like this (Im using the example provided by the prof): {’Name ’: ’Humboldt ’, ’Candidates ’: {’LIB ’: ’Elliott ’, ’NDP…
answer count: 1
has answer: http://stackoverflow.com/a/46903559
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/46856642
has body: Hi I would like to know how I can have my code below return the following given the input split_sentence("doghellomeyayahell") return ["dog","hellomeyayahell",""] instead of ['dog', 'hellomeyayahel', 'l'] I know the problem is that since the thing cannot find the 'hello' string it returns the -1 index. If possible how would I make it so the above would work? def split_sentence(s): lst = [] first = s.find('hello') firsts = s[0:first] third = s.find('hello', first +2, len(s)) thirds = s[third:len(s)] second = s[first:third] lst.append(firsts) lst.append(second) lst.append(thirds) return lst
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/46857011
has title: Returning something other than -1 index
tagged with: list
upvote count: 2
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80661180
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80661599

http://stackoverflow.com/a/47054421
has body: I believe now that Chromium supports this feature (as you linked to the bug ticket), it falls to the chromedriver team to add support for the feature. There is an open ticket here, but it does not appear to have a high priority at the moment. Please, everyone who needs this feature, go give it a +1!
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46878471

http://stackoverflow.com/a/46757987
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46757986
upvote count: 2
has body: When the conditional functions get long, the above approach gets a bit messy. What you can do is to define a lambda expression outside the conditional. Note that the following does not work in the Python interactive REPL, where it results in ValueError: Operation 'cond_14/Merge' has been marked as not fetchable.. It does work when you put the code into a python file and run in the normal way. import tensorflow as tf sess = tf.InteractiveSession() a = tf.zeros(0) fn = lambda: tf.argmax(a) res = tf.cond( tf.equal(tf.size(a), tf.constant(0)), lambda: tf.constant(-1, dtype=tf.int64), fn ).eval() print(res) res2 = tf.cond( tf.equal(tf.size(a), tf.constant(0)), lambda: tf.constant(-1, dtype=tf.int64), lambda: tf.add(fn(), tf.constant(1, dtype=tf.int64)) ).eval() print(res2) # Output: # -1 # -1
type: Answer

http://stackoverflow.com/q/46758848
has comment: http://stackoverflow.com/comment/80465128
accepted answer: http://stackoverflow.com/a/46760294
has comment: http://stackoverflow.com/comment/80464991
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: dataframe
linked to: http://stackoverflow.com/q/46748369
linked to: http://stackoverflow.com/q/46784707
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80539251
has body: I have a csv file(or dataframe) like below : Text Location State A Florida, USA Florida B NY New York C D abc And a dictionary with key value pair as : stat_map = { 'FL': 'Florida', 'NY': 'NewYork', 'AR': 'Arkansas', } How may I delete row 3rd and 4th i.e. row with Text C &amp; D so that my dataframe contains only those rows for which i have value in dictionary. The final output should look like : Text Location State A Florida, USA Florida B NY New York Please help.
has answer: http://stackoverflow.com/a/46760294
has title: Python: Check if dataframe cell value exists in Dictionary. If exists replace dataframe value with dictionary key
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80464761
tagged with: python

mfcc
type: Tag
tags question: http://stackoverflow.com/q/46801713
tag name: mfcc
tags question: http://stackoverflow.com/q/46822073

http://stackoverflow.com/q/46858584
type: AnsweredQuestion
tagged with: list
type: Question
has body: I'm trying to parse a log file for certain occurrences. As the log file can be quiet big it is necessary to filter out the lines that are of no interest for the application we need it for. the idea was that I make one list with the 4 or 5 strings that I want to look for and then loop over the lines in an other list that contains the lines that I have retained of the log file. The log file is the log of a proxy and is used to get a view of where requests come from The first reduction was easy by looking for "GET /" in the line and only store the ones that do have that in it. with open('logfile', 'r') as f: for line in f: if "GET /" in line: lines.append(line) The list 'lines' needs then to be reduce to the lines that contain one of a number of strings in the url l1 = ['/Treintickets/aankopen', '/booking/Tickets', '/Acheter/Billets', ...] I tried list comprehension but that did not work: result = [l for l in lines if l1 in l] Is there a way to get this to work without having to loop over the big list lines for each member of 'l1'?
has title: Check if any element in a list is present in the elements of a list in python
tagged with: list-comprehension
answer count: 2
has comment: http://stackoverflow.com/comment/80664880
has answer: http://stackoverflow.com/a/46858607
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80664874
favorite count: 0
accepted answer: http://stackoverflow.com/a/46858607
possible better answer: http://stackoverflow.com/a/46858638
upvote count: 2
has answer: http://stackoverflow.com/a/46858638
tagged with: python

http://stackoverflow.com/comment/80668321
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46860323
score: 0
has text: I have to say this is very easy to understand!Thanks to you.

http://stackoverflow.com/a/46777561
has comment: http://stackoverflow.com/comment/80502916
has body: Remove the trailing slash before the $ in your url regex or use a ? before the $. urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^chart_data$', views.chart_data, name='chart_data') ] You can also refer it by name in templates as {% url 'app:url_name' %} You'll also need to pass csrf token along with your post data. {% csrf_token %} &lt;script&gt; var timeArray = [0,10,20,30,40,50,60]; var dataArray = [0,0,0,0,0,0,0]; $.ajax({ var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); url: {% url 'headstation:chart_data' %}, type:"POST", data: { 'data': 'temperature', 'csrfmiddlewaretoken': csrftoken, }, dataType: 'json', success: function (data) { if (data) { timeArray = data.x; dataArray = data.y; alert("recieved"); } } }); &lt;/script&gt;
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80503628
type: Answer
accepted answer of: http://stackoverflow.com/q/46776746
answers question: http://stackoverflow.com/q/46776746
has comment: http://stackoverflow.com/comment/80502586
has comment: http://stackoverflow.com/comment/80503711
has comment: http://stackoverflow.com/comment/80502629
has comment: http://stackoverflow.com/comment/80503614
score: 4
has comment: http://stackoverflow.com/comment/80502652
has comment: http://stackoverflow.com/comment/80503580
upvote count: 4

http://stackoverflow.com/comment/80447581
type: AnswerComment
score: 0
type: Comment
has text: Glad it helped!
comment on: http://stackoverflow.com/a/46750726

http://stackoverflow.com/comment/80676528
comment on: http://stackoverflow.com/a/46859903
type: AnswerComment
has text: @Joehan No, the question has been closed already. I'd really appreciate if you could open a new question. Thank you :-)
score: 0
type: Comment

http://stackoverflow.com/comment/80444978
comment on: http://stackoverflow.com/a/46748956
type: Comment
has text: @AshishRanjan It should be pointed out to a newbie that he does need the 'for' loop.
score: 1
type: AnswerComment

http://stackoverflow.com/q/46874594
has comment: http://stackoverflow.com/comment/80696839
tagged with: algorithm
tagged with: math
has comment: http://stackoverflow.com/comment/80697011
has comment: http://stackoverflow.com/comment/80697601
type: Question
has comment: http://stackoverflow.com/comment/80696294
has comment: http://stackoverflow.com/comment/80697837
has comment: http://stackoverflow.com/comment/80696885
answer count: 1
has comment: http://stackoverflow.com/comment/80696245
has comment: http://stackoverflow.com/comment/80696471
has answer: http://stackoverflow.com/a/46875306
has body: i need help to think the idea of programming for this problem. The program is to create estimated time arrival. The car have this rule: When 0km &lt; x &lt;= 6km , Velocity is 24KM/H When 6km &lt; x &lt;= 10km, Velocity is 33KM/H When x&gt;10km, Velocity is 30KM/H Input : 45.0 10:30 Output : 12:28 The first input is distance and second input is time departured. The output is time arrival Time format used (24-Hour) &amp; Velocity format used (Metric) Explanation The car velocity is changed at specific distance, so example the distance is 45 KM, so when at first 6KM the velocity is 24KM/H, when the car at 7KM the velocity is changed to 33KM/H until 10KM, and more than 10KM the velocity is 30KM/H until 45KM I really confused when the '12.28' come from, so i can't write the program if i even don't know. I already did calculate of average speed like 6*24 = 144, 4*33=132, 35*30 = 1050. Average speed : (144+132+1050)/45 = 29,467 KM/H. But when i used calculator online to estimated speed of 12:28-10:30 = 1:58. The speed is distance/time ==> 45/1.966666666666667 = 22.88135593220339 KM/H. My result so far from calculator. Simple sketch :
score: 0
has comment: http://stackoverflow.com/comment/80696364
has comment: http://stackoverflow.com/comment/80696950
has comment: http://stackoverflow.com/comment/80696191
has comment: http://stackoverflow.com/comment/80696797
has comment: http://stackoverflow.com/comment/80696283
type: UnansweredQuestion
tagged with: physics
has title: Time arrival program with velocity change
has comment: http://stackoverflow.com/comment/80696253
tagged with: python
has comment: http://stackoverflow.com/comment/80696743
has comment: http://stackoverflow.com/comment/80696620
has comment: http://stackoverflow.com/comment/80696524

http://stackoverflow.com/comment/80490312
has text: @Harman - got another error of - pandas-0.20.3-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform.
type: Comment
comment on: http://stackoverflow.com/a/46771534
score: 0
type: AnswerComment

http://stackoverflow.com/q/46779891
tagged with: opencv
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80518768
has answer: http://stackoverflow.com/a/48515371
has body: I have been trying to get the openCV 2.4.13 python27 face Detection from images please help.The error that I get is: Traceback (most recent call last): File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 36, in &lt;module&gt; profile = getProfile(id) File "C:\Users\sam_o\Desktop\Alrehman\Attendance.py", line 19, in getProfile profile = none NameError: global name 'none' is not defined The code I wrote is as follows: import cv2,os import numpy as np from PIL import Image import pickle import sqlite3 recognizer = cv2.createLBPHFaceRecognizer() cascadePath = "Classifiers/face.xml" faceCascade = cv2.CascadeClassifier(cascadePath); path = 'EmployeeRecord' def getProfile(id): conn=sqlite3.connect("Alrehman.db") cmd="SELECT * FROM Person WHERE ID="+str(id) cursor=conn.execute(cmd) profile=none for row in cursor: profile=row conn.close() return profile cam = cv2.VideoCapture(0) font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) #Creates a font while True: ret, im =cam.read() gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE) for(x,y,w,h) in faces: id, conf = recognizer.predict(gray[y:y+h,x:x+w]) cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2) profile=getProfile(id) if(profile!=None): cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[1]), (x,y+h+30),font, 255) #Draw the text cv2.cv.PutText(cv2.cv.fromarray(im),str(profile[2]), (x,y+h+60),font, 255) #Draw the text cv2.imshow('im',im) cv2.waitKey(10) Does anyone have any idea what I might be doing wrong here?
has comment: http://stackoverflow.com/comment/80558096
has title: Issue With Opencv Face Detection
has comment: http://stackoverflow.com/comment/80558630
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46781266
has comment: http://stackoverflow.com/comment/81417950
type: Question

http://stackoverflow.com/a/46777156
has body: A one-liner would be: lists = sum([[[Master_List[0], i, j, Master_List[3]] for i in Master_List[1]] for j in Master_List[2]], [])
answers question: http://stackoverflow.com/q/46776941
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80500196

http://stackoverflow.com/comment/80726488
score: 0
type: QuestionComment
has text: I am not so experienced with Django modelling, but from the error is clear that has you have renamed the model referenced by another one, then changed are not migrated as the reference isn't found anymore. Have a look at this as from your error could be solved making correct steps on not simple architecture https://stackoverflow.com/questions/25091130/django-migration-strategy-for-renaming-a-model-and-relationship-fields
type: Comment
comment on: http://stackoverflow.com/q/46889405

http://stackoverflow.com/comment/114843562
has text: I was running into this issue as well and this resolved it. Thanks!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56434301

http://stackoverflow.com/comment/80493165
comment on: http://stackoverflow.com/a/46773591
has text: thanks this is actually very close to what I needed. However, what if I have thousands of columns, can use lists in the agg dictionary e.g. .agg{my_numerical_columns_list: my_fun} ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80704414
comment on: http://stackoverflow.com/q/46878699
type: QuestionComment
has text: `print('\tStuff')`. What's the problem here?
type: Comment
score: 4

http://stackoverflow.com/comment/80545205
type: QuestionComment
comment on: http://stackoverflow.com/q/46798995
type: Comment
has text: If you can show the result for each case then people can help you. Before that check indentation (May be your print stament is outside if condition)
score: 0

http://stackoverflow.com/q/46836616
has comment: http://stackoverflow.com/comment/80982627
has comment: http://stackoverflow.com/comment/80986906
has title: Python `socket.getaddrinfo` taking 5 seconds about 0.1% of requests
has answer: http://stackoverflow.com/a/47004175
has comment: http://stackoverflow.com/comment/80621227
has comment: http://stackoverflow.com/comment/80723408
tagged with: dns
has body: Running Python on a Django project which communicates with various web-services, we have an issue that occasionally requests are taking around 5 seconds instead of their usual &lt; 100 ms. I've narrowed this down to time taken in the socket.getaddrinfo function - this is being called by requests when we connect to external services, but it also appears to effect the default Django connection to the Postgres database box in the cluster. When we restart uwsgi after a deployment the first requests that come in will take 5 seconds to send a response. I also believe that our celery tasks are taking 5 seconds on a regular basis, but I've not added statsd timer tracking to them yet. I've written some code to reproduce the issue: import socket import timeit def single_dns_lookup(): start = timeit.default_timer() socket.getaddrinfo('stackoverflow.com', 443) end = timeit.default_timer() return int(end - start) timings = {} for _ in range(0, 10000): time = single_dns_lookup() try: timings[time] += 1 except KeyError: timings[time] = 1 print timings Typical results are {0: 9921, 5: 79} My colleague has already pointed to potential issues around ipv6 lookup times and has added this to the /etc/gai.conf: precedence ::ffff:0:0/96 100 This has definitely improved lookups from non-Python programs such as curl which we use, but not from Python itself. The server boxes are running Ubuntu 16.04.3 LTS and I'm able to reproduce this on a vanilla VM with Python 2. What steps can I take to improve the performance of all Python lookups so that they can take &lt; 1s?
tagged with: python-requests
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80986680
has comment: http://stackoverflow.com/comment/80986373
has answer: http://stackoverflow.com/a/47018094
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/80872157
has comment: http://stackoverflow.com/comment/80621198
has comment: http://stackoverflow.com/comment/80753269
downvote count: 0
has answer: http://stackoverflow.com/a/46963378
score: 15
has comment: http://stackoverflow.com/comment/80861078
has comment: http://stackoverflow.com/comment/80723352
answer count: 3
tagged with: sockets
has comment: http://stackoverflow.com/comment/80733155
accepted answer: http://stackoverflow.com/a/46963378
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/47004175

http://stackoverflow.com/a/46821500
answers question: http://stackoverflow.com/q/46821227
has body: If you would like using pandas df.pivot('Date','Name','Downloads').rank(method="first", ascending=False,axis=1).plot()
accepted answer of: http://stackoverflow.com/q/46821227
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46759953
score: 1
has body: You can easily get the index of the minimum value using the following: my_list.index(min(my_list))
has comment: http://stackoverflow.com/comment/80465322
upvote count: 1
has comment: http://stackoverflow.com/comment/80465419
answers question: http://stackoverflow.com/q/46759911
type: Answer
has comment: http://stackoverflow.com/comment/80465296
downvote count: 0

http://stackoverflow.com/a/46898446
downvote count: 0
answers question: http://stackoverflow.com/q/46898382
type: Answer
score: 3
upvote count: 3
has body: Are you using ipython? In ipython _i means your previous command.

http://stackoverflow.com/comment/80732192
has text: I would simply utilize the `ingredients` argument of `Pizza`: `pizza_with_onion = Pizza('onion')`. The factory function should be used if you somehow need to instantiate a pizza from something other than its ingredients. A whole new class would be needed if you decided also to make kebabs, which is different from a pizza but might still share quite a few methods.
comment on: http://stackoverflow.com/a/46892206
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80658172
type: QuestionComment
comment on: http://stackoverflow.com/q/46853377
score: 0
has text: NoSuchFrameException: no such frame>>>>this is the error that i am getting..
type: Comment

http://stackoverflow.com/q/46849343
tagged with: django
upvote count: 7
has body: I noticed that this Django Rest Framework commit broke my project when upgrading from 3.6.3 to 3.7.0. Here's the relevant part of the model that is now broken: class MarketingPlan(models.Model): promotion = models.ForeignKey(Promotion, null=True) class MarketingPlanSerializer(serializers.ModelSerializer): promotion = serializers.CharField( source='fk_promotion.id', read_only=False, allow_null=True) class Meta: model = MarketingPlan fields = ('promotion',) Accessing the data attribute of this serializer, when the Promotion foreign key is None &gt;&gt; mp = MarketingPlan.objects.first() &gt;&gt; MarketingPlanSerializer(mp).data rest_framework/fields.py", line 100, in get_attribute instance = getattr(instance, attr) AttributeError: 'NoneType' object has no attribute 'id' So whereas get_attribute used to skip None, now it goes searching for the .id attribute of the related field promotion in my particular case, even when it's None. What's the workaround for this?
type: Question
accepted answer: http://stackoverflow.com/a/46849429
score: 7
answer count: 2
has answer: http://stackoverflow.com/a/62910225
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
possible better answer: http://stackoverflow.com/a/62910225
has answer: http://stackoverflow.com/a/46849429
tagged with: python
has title: DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
type: AnsweredQuestion

http://stackoverflow.com/a/46784242
has comment: http://stackoverflow.com/comment/102300649
answers question: http://stackoverflow.com/q/46784184
downvote count: 0
has comment: http://stackoverflow.com/comment/80559283
has body: You may refer to this nice tutorial : https://github.com/guillaume-chevalier/seq2seq-signal-prediction It can find pattern of sinewave and generate future values.
type: Answer
has comment: http://stackoverflow.com/comment/80550357
has comment: http://stackoverflow.com/comment/102324954
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80550478

http://stackoverflow.com/comment/80755434
has text: thanks so much. posted the wrong df indeed. the original is in decimal. anyway. got it now thanks to you.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46904307
type: Comment

http://stackoverflow.com/comment/80485763
comment on: http://stackoverflow.com/q/46768859
score: 1
has text: The source code for `set_palette` [can be found here](https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py#L468). Due to helper functions, there is quite a lot of code that would be required to reproduce `set_palette`'s *exact* behavior without seaborn. But if you only want a subset of that behavior, you may find what you need in the source code. Or explain what subset of behavior you are looking for (a specific use case, your python version and matplotlib version), and maybe we can help you.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80446193
type: Comment
type: QuestionComment
has text: I'm using Python 3.6
comment on: http://stackoverflow.com/q/46750071
score: 0

http://stackoverflow.com/a/46782362
answers question: http://stackoverflow.com/q/46780576
downvote count: 0
has body: As per the URL configuration you have stated in mysite.url and secondapp.url you link would be localhost:8000/calc/calc/ which IMO would be confusing, if I am correct, URL you want is localhost:8000/calc/ For that you have to change the url you have defined in secondapp.url to from django.conf.urls import url from secondapp.views import CalcPage urlpatterns = [ url(r'$', CalcPage.as_view(), name='calc'), ] This would make the ClacPage accessible on localhost:8000/calc/ See / is very important when defining URLs.
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/46898519
favorite count: 0
has body: I'd appreciate it very much if anyone could give me pointers on what I need to fix. I'm new to TensorFlow and I have no idea what is going wrong. The code: from PIL import ImageFont, Image, ImageDraw import tensorflow as tf import random import numpy as np x = tf.placeholder(tf.float32, [None,48,48,1]) y = tf.placeholder(tf.float32, [None,26]) def initW(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01)) w1 = initW([5,5,1,32]) w2 = initW([5,5,32,64]) w3 = initW([64*12*12,26]) keep_prob = tf.placeholder(tf.float32) saver = tf.train.Saver() def model(x,w1,w2,w3,keep_prob): l1c = tf.nn.relu(tf.nn.conv2d(x, w1, strides = [1,1,1,1], padding = "SAME")) l1p = tf.nn.max_pool(l1c, ksize = [1,2,2,1], strides = [1,2,2,1], padding = "SAME") l2c = tf.nn.relu(tf.nn.conv2d(l1p, w2, strides = [1,1,1,1], padding = "SAME")) l2p = tf.nn.max_pool(l2c, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") l2r = tf.reshape(l2p,[-1,64*12*12]) l2d = tf.nn.dropout(l2r, keep_prob) l3f = tf.matmul(l2d,w3) return l3f model = model(x,w1,w2,w3,keep_prob) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = model)) op = tf.train.AdamOptimizer(0.000002).minimize(cost) def imgData(char): img = Image.new("L", (48, 48), color=255) f = ImageFont.truetype("Arial.ttf", 50) ImageDraw.Draw(img).text((25 - f.getsize("W")[0] / 2, 0), "W", font=f) return np.reshape(img.getdata(),[48,48,1]) def oneHot(C,reshape=False): arr = [0] * 26 arr[charToInt(C)] = 1 if reshape: return np.reshape(arr,[1,26]) else: return arr def charToInt(C): return ord(C) - ord("A") def accuracy(): alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") testSet = np.array([imgData(C) for C in alphabet]) testLabels = np.array([oneHot(C) for C in alphabet]) accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(model,1),tf.argmax(y,1)),tf.float32)) print (sess.run(accuracy,feed_dict={x:testSet,y:testLabels,keep_prob:1.0})) def predict(char): probabilities = sess.run(model, feed_dict= {x:[imgData(char)], …
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/46899427
answer count: 1
accepted answer: http://stackoverflow.com/a/46899427
has title: I have no idea what's wrong with my TensorFlow program

http://stackoverflow.com/a/46805631
score: 1
upvote count: 1
has body: Windows inherited backslashes as a path separator from Microsoft DOS. DOS initially didn't support subdirectories and opted to use the (on US keyboards) easily typed slash / character for command line switches. When they did introduce subdirectories in DOS 2, either slash / or backslash \ worked as a path separator, but to use slashes on the command line you had to reconfigure the switch character, a feature they later removed entirely. Thus the command line for certain commands that look for switches without space in front (like dir/w) is the one place you can't use forward slashes (this has to do with the command line being passed as a single string, unlike POSIX which passes distinct arguments in a list). That, and poorly written code that tries things like splitting on backslash, not knowing that slash is also a path separator. It's also sometimes complicated by either character having other meanings, such as \ being the escape character in string literals; that's why you use \\ unless you use a raw string r'foo\bar'. The other path separator I know of is classic Mac OS, which uses colon :. Python handles these differences by including reasonable routines in os.path or pathlib.
answers question: http://stackoverflow.com/q/46805462
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80560019

http://stackoverflow.com/comment/80448157
type: QuestionComment
comment on: http://stackoverflow.com/q/46751001
type: Comment
score: 1
has text: What is the value of `TEMPLATE_DIRS` in your `settings.py` file?

http://stackoverflow.com/comment/80533314
score: 4
has text: "Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise." - Just look at the answers: "I prefer this, I think, my personal..."
comment on: http://stackoverflow.com/q/46792993
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80709729
has text: Consider importing csvs into datasets (Stata/SAS, R dataframes, even Python pandas dataframes) or databases (SQLite/MS Access are file-level dbms) and merge/join the two for new assigned columns. No loops needed.
score: 0
comment on: http://stackoverflow.com/q/46880644
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80616694
type: AnswerComment
comment on: http://stackoverflow.com/a/46834523
type: Comment
score: 1
has text: @Bharathshetty when I using `apply` I always make all perpetration process outside the `lambda` , Cause I know I will messed up ...

http://stackoverflow.com/a/70833226
answers question: http://stackoverflow.com/q/46751336
score: 0
type: Answer
has body: It can even happen if no output is specified in graphene.Mutation inheriting class. But that is not case for DevilWarior.
has comment: http://stackoverflow.com/comment/125344072

http://stackoverflow.com/a/46802086
has body: Shapely already has libraries for this specific problem. PostGIS stores the geometries as HEX values. Use Shapely's loads function to load this with the parameter of hex=True. Specifically... geom = shapely.wkb.loads(hex_geom[0], hex=True) Don't use PostGIS ST_Union, cause you have to dump and load over and over for this to work. Shapely has that configured as well with linemerge
upvote count: 8
answers question: http://stackoverflow.com/q/46801838
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46801838
type: Answer
score: 8
downvote count: 0

http://stackoverflow.com/q/46795315
possible better answer: http://stackoverflow.com/a/53970268
score: 1
type: Question
answer count: 2
has body: Importing Qt from PyQt5 gives a segmentation fault. $ python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from PyQt5 import Qt [1] 7667 segmentation fault (core dumped) python Running using GDB gives some more information. $ gdb -ex r --args python -c "from PyQt5 import Qt" ... Starting program: /usr/bin/python -c from\ PyQt5\ import\ Qt [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Program received signal SIGSEGV, Segmentation fault. strlen () at ../sysdeps/x86_64/strlen.S:106 106 ../sysdeps/x86_64/strlen.S: No such file or directory. EDIT: For versioning reasons, I had to compile PyQt5 from source. Here is the full output from PyQt's configuration script. Below is an abbreviated version. $ python configure.py --verbose --qmake=/home/jeff/Qt/5.9.2/gcc_64/bin/qmake Querying qmake about your Qt installation... Determining the details of your Qt installation... /home/jeff/Qt/5.9.2/gcc_64/bin/qmake -o cfgtest_QtCore.mk cfgtest_QtCore.pro Info: creating stash file /home/jeff/Downloads/PyQt5_gpl-5.9/.qmake.stash make -f cfgtest_QtCore.mk g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I../../Qt/5.9.2/gcc_64/include -I../../Qt/5.9.2/gcc_64/include/QtCore -I. -I../../Qt/5.9.2/gcc_64/mkspecs/linux-g++ -o cfgtest_QtCore.o config-tests/cfgtest_QtCore.cpp g++ -Wl,-O1 -Wl,-rpath,/home/jeff/Qt/5.9.2/gcc_64/lib -o cfgtest_QtCore cfgtest_QtCore.o -L/home/jeff/Qt/5.9.2/gcc_64/lib -lQt5Core -lpthread ./cfgtest_QtCore cfgtest_QtCore.out This is the GPL version of PyQt 5.9 (licensed under the GNU General Public License) for Python 2.7.12 on linux2. Type 'L' to view the license. Type 'yes' to accept the terms of the license. Type 'no' to decline the terms of the license. Do you accept the terms of the license? yes Found the license file pyqt-gpl.sip. Chec…
upvote count: 1
has comment: http://stackoverflow.com/comment/80578526
tagged with: pyqt
has comment: http://stackoverflow.com/comment/80537623
has answer: http://stackoverflow.com/a/46815731
has comment: http://stackoverflow.com/comment/80576625
downvote count: 0
accepted answer: http://stackoverflow.com/a/46815731
tagged with: segmentation-fault
has title: pyqt5 segmentation fault on import
favorite count: 0
has comment: http://stackoverflow.com/comment/80538432
has comment: http://stackoverflow.com/comment/80537217
has answer: http://stackoverflow.com/a/53970268
has comment: http://stackoverflow.com/comment/80537714
tagged with: python
has comment: http://stackoverflow.com/comment/80541302
has comment: http://stackoverflow.com/comment/80542023
tagged with: pyqt5
tagged with: qt
type: AnsweredQuestion

http://stackoverflow.com/comment/80682122
type: QuestionComment
has text: `word_tokenize` takes a string as an argument not a list of strings. Call `word_tokenize` on each element in `your_list` not on `your_list` itself.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46866525

http://stackoverflow.com/comment/80694776
type: QuestionComment
has text: And another consent - `super(Avatar, self).create_default_photoset` it's a call for parent class, but I don't think that Model has such method. Anyway, please explain "does not work" in more details, e.g. traceback of error
comment on: http://stackoverflow.com/q/46873618
score: 0
type: Comment

http://stackoverflow.com/a/46875756
upvote count: 10
type: Answer
has body: You can either allow the user to pass the value to the function via the URL, or you can call Random inside Help: @app.route('/help/&lt;random&gt;') def Help(random): return render_template("help.html", PassingRandom=random) Or, by calling the function Random in Help: @app.route('/help') def Help(): PassingRandom = Random() return render_template("help.html", PassingRandom=PassingRandom)
accepted answer of: http://stackoverflow.com/q/46875697
answers question: http://stackoverflow.com/q/46875697
score: 10
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46901860
has body: IIUC, you can use str.extractall to get the groups of 5 digits, clean up the columns, and then join: In [168]: r = df.REFNUMS.str.extractall("(\d{1,5})").unstack() In [169]: r.columns = r.columns.droplevel(0) In [170]: df.join(r) Out[170]: ITEM REFNUMS 0 1 2 3 4 5 6 7 8 9 1 299 0036701923024762922029229294652954429569295832... 00367 01923 02476 29220 29229 29465 29544 29569 29583 2 2 655 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 24 1791 00016027123076000158004563065131972 00016 02712 30760 00158 00456 30651 31972 None None None 25 1805 00016027123076000158004563065131972 00016 02712 30760 00158 00456 30651 31972 None None None 26 1813 00016027123076000158004563065131972 00016 02712 30760 00158 00456 30651 31972 None None None 27 1821 00016027123076000158004563065131972 00016 02712 30760 00158 00456 30651 31972 None None None 28 1937 0142530521316303164702509000510012201310027820... 01425 30521 31630 31647 02509 00051 00122 01310 02782 0
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80780531
accepted answer of: http://stackoverflow.com/q/46901721
type: Answer
answers question: http://stackoverflow.com/q/46901721
score: 1
upvote count: 1

http://stackoverflow.com/comment/80596185
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46771636
has text: @Mangohero1 Is it like we cannot access items like this in dictionary??

http://stackoverflow.com/q/46868452
tagged with: python
type: AnsweredQuestion
upvote count: 1
has title: lazy Filtering QTreeview with QsortFIlterProxymodel
type: Question
tagged with: pyqt4
has answer: http://stackoverflow.com/a/46869233
has body: I want to extend a question I asked earlier with a filter. In my previous question I got help in lazy loading the treeview, parents first and only adding the parent's children when the user clicks on the node more or less as follows from PyQt4 import QtGui class Widget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.mytreeview = QtGui.QTreeView(self) self.setLayout(QtGui.QVBoxLayout()) self.layout().addWidget(self.mytreeview) self.model = QtGui.QStandardItemModel(self.mytreeview) self.mytreeview.setModel(self.model) self.mytreeview.clicked.connect(self.update_model) self.initialise_model() def initialise_model(self): for text in ["parent1", "parent2", "parent3"]: item = QtGui.QStandardItem(text) self.model.appendRow(item) def update_model(self, index): parent = self.model.itemFromIndex(index) for text in ["children1", "children2", "children3"]: children = QtGui.QStandardItem("{}_{}".format(parent.text(), text)) parent.appendRow(children) self.mytreeview.expand(index) I now want to extend and make use of a filter for the treeview, so that a user can type in the name of a parent node and the treeview will filter itself down to the appropriate relevant nodes. I still want to keep the ability for the user to click on a parent node and even when filtered only then would the child nodes be added to the parent. How can i adapt the following to do so? I have set the treeview up as follows proxyModel = QSortFilterProxyModel(treeView) proxyModel.setSourceModel(self.model) # set model treeView.setModel(proxyModel); treeView.setSortingEnabled(true) def update_model(self, index): parent = self.model.itemFromIndex(index) ##not sure about this now in the light of the proxyModel for text in ["children1", "children2", "children3"]: children = QtGui.QStandardItem("{}_{}".format(parent.text(), text)) parent.appendRow(children) self.mytreeview.expand(index)#not sure about this either as the index is of the proxyModel I have two main questions …
linked to: http://stackoverflow.com/q/46778623
tagged with: pyqt
downvote count: 0
answer count: 1
score: 1
tagged with: qtreeview
favorite count: 0
tagged with: qsortfilterproxymodel
accepted answer: http://stackoverflow.com/a/46869233

http://stackoverflow.com/a/46868807
downvote count: 1
answers question: http://stackoverflow.com/q/46868730
type: Answer
upvote count: 0
score: -1
has body: problem is that you're not fetching the query in the variable "dropname" you should replace dropname = cur.fetchall() return render_template('form_names.html', dropname=dropname) by data = dropname.fetchall() return render_template('form_names.html', dropname=data) then in your HTML to call it, you do {{ dropname[n] }} where n is the column's index

http://stackoverflow.com/a/46899304
score: 2
has body: Option 1 str.split with expand=True, followed by stack + groupby. This returns groups. g = df.lake.str.split(',\s*', expand=True).stack()\ .to_frame(name='lake').reset_index(level=1, drop=1).groupby('lake') for i, k in g: print(k, '\n') lake zip 10002 Erie 10003 Erie lake zip 10001 Huron 10002 Huron lake zip 10003 Superior Option 2 str.get_dummies, my preferred method. This does not return your result in groups, but the get_dummies implicitly creates OHEs which you can translate into groupings. g = df.lake.str.get_dummies(sep=r', ') for c in g.columns: print('{}: {}'.format(c, g[c][g[c] &gt; 0].index.tolist())) Erie: [10002, 10003] Huron: [10001, 10002] Superior: [10003]
accepted answer of: http://stackoverflow.com/q/46899145
answers question: http://stackoverflow.com/q/46899145
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/46786847
has comment: http://stackoverflow.com/comment/80522317
score: -1
tagged with: numpy
upvote count: 0
has body: I want to read single-channel 32-bit integer image saved as ssv file. I have tried so far(see the following code) but without much success. Here is the code Please let me know if you have any idea of what is missing?
answer count: 1
has answer: http://stackoverflow.com/a/46792308
favorite count: 0
accepted answer: http://stackoverflow.com/a/46792308
has title: How can I read single-channel 32-bit integer images with python?
tagged with: python
tagged with: text-files
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80529477
downvote count: 1
tagged with: import
type: Question

http://stackoverflow.com/a/46872306
has comment: http://stackoverflow.com/comment/80692088
has comment: http://stackoverflow.com/comment/80691906
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46872265
has comment: http://stackoverflow.com/comment/80692107
has comment: http://stackoverflow.com/comment/80691890
answers question: http://stackoverflow.com/q/46872265
score: 1
has body: Simple one liner using looping constructs: result = ", ".join(["'" + i + "'" for i.strip() in myString.split(",")]) What we are doing here is we are creating a list that contains all substrings of your original string, with the quotes added. Then, using join, we make that list into a comma delimited string. Deconstructed, the looping construct looks like this: resultList = [] for i in myString.split(","): resultList.append("'" + i.strip() + "'") Note the call to i.strip(), which removes extraneous spaces around each substring. Note: You can use format syntax to make this code even cleaner: New syntax: result = ", ".join(["'{}'".format(i.strip()) for i in myString.split(",")]) Old syntax: result = ", ".join(["'%s'" % i.strip() for i in myString.split(",")])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80692130
downvote count: 0

http://stackoverflow.com/comment/80696524
has text: @MichaelButscher the difference is not 10-7 but 7,8,9,10 which is 4. or in another way like 6km to 7km is 33 Km/h i think. My comment 'More like when 6.2/6.5/6.7 is always 24km/h' is false then. Because the speed 24km/h is until 6km. More than that like 6.2/6.4 is changed to 33km/h
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46874594
score: 0

http://stackoverflow.com/a/46757763
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46757362
answers question: http://stackoverflow.com/q/46757362
has comment: http://stackoverflow.com/comment/80471510
type: AcceptedAnswer
downvote count: 0
has body: You can write and update statement and keep appending it with existing value. Assuming v_input is what you get from user input and for v_userid UPDATE words SET inputs = CONCAT(inputs, v_input) WHERE userid =v_userid
has comment: http://stackoverflow.com/comment/80470544
has comment: http://stackoverflow.com/comment/80470972
type: Answer
has comment: http://stackoverflow.com/comment/80470920

http://stackoverflow.com/comment/80659524
has text: Which IDE are you using? Or are you running this in terminal? The thing is, that noone else can probably reproduce this, so there must be something specific to your way of running things.
comment on: http://stackoverflow.com/q/46834347
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80726300
score: 0
has text: `parse_pgrammar` is the class in `fixesNLTK3`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46877535

http://stackoverflow.com/comment/80509187
type: AnswerComment
type: Comment
score: 0
has text: I didn't even see your edit until after I figured it out. Either way amazing description, thanks!
comment on: http://stackoverflow.com/a/46776167

http://stackoverflow.com/a/47103482
has comment: http://stackoverflow.com/comment/81434568
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/81453301
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46850735
answers question: http://stackoverflow.com/q/46850735
has body: With this solution you can edit &amp; debug 3rd party packages in PyCharm. Prerequisites: Fork &amp; clone the repo you want to edit on your host. Say to /on-your-host/path/to/3rd-party In your Vagrantfile, configure your synced_folder from /on-your-host/path/to/3rd-party to /vagrant/3rd-party In Terminal: ssh into your vagrant Activate the project's virtualenv, if any pip install -e /vagrant/3rd-party In PyCharm: Set your Project Interpreter > Gear icon > Add Remote > Vagrant Create a run/debug configuration for your needs Run/debug it Add breakpoints inside the 3rd party package You should be able to edit and use the debugger on this code now Notes: Pip install in edit mode docs Forking is optional. If you just want to play around, without contributing, then skip forking and just clone the original repo on your host. You may need to refresh PyCharm external libraries. In my case was enough to right click on the 3rd party package name (from the breadcrumbs) and delete it Then Settings > Project Interpreter: click gear icon > More > click edit icon > OK, OK, OK
type: AcceptedAnswer

continue
tags question: http://stackoverflow.com/q/46872104
type: Tag
tag name: continue

http://stackoverflow.com/q/46855255
has answer: http://stackoverflow.com/a/46855571
score: 0
has comment: http://stackoverflow.com/comment/80658042
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/80658084
has comment: http://stackoverflow.com/comment/80658299
has comment: http://stackoverflow.com/comment/80658101
has comment: http://stackoverflow.com/comment/80658270
has title: How to find if english words exist in string
has comment: http://stackoverflow.com/comment/80658353
tagged with: python
tagged with: parsing
has comment: http://stackoverflow.com/comment/80658189
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80658165
has body: I am trying to parse some web domains (tens of thousands) to see if they contain any English words. It is easy for me to parse the domains to grab the main part of the domain with tldextract and then I tried to use enchant to see if they exist in the English dictionary. The problem is I do not know how to split the domains in to multiple words to check, i.e. latimes returns as False but times would return as True. Does anyone know a clever way to do look if there is an english word contained at all in the strings? Thanks!
type: Question
tagged with: dataframe

http://stackoverflow.com/a/46831283
answers question: http://stackoverflow.com/q/46831228
downvote count: 0
type: Answer
has body: You can utilize zip and dictionary comprehension to solve this: list_a = [1,2,3] list_b = ['a','b','c'] list_c = [4,5,6] final_dict = {a:{b:c} for a, b, c in zip(list_a, list_b, list_c)} Output: {1: {'a': 4}, 2: {'b': 5}, 3: {'c': 6}}
upvote count: 9
accepted answer of: http://stackoverflow.com/q/46831228
score: 9
type: AcceptedAnswer

http://stackoverflow.com/q/46867481
has answer: http://stackoverflow.com/a/46867523
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51372063
score: 1
has comment: http://stackoverflow.com/comment/80682335
has title: How to return three tuples in python involving an if statement
type: Question
downvote count: 0
has body: I am trying to write a program that will print three tuples, but I only succeed in returning only two. I am suppose to return, in a tuple: The character, the ordinal value, and the the type of the char: "letter", "number" or "punctuation". I have written the if/elif/else to check for these three values, but don't now how to return them in a tuple, as the third value. Here is my code: def character_info(char): ord_value = ord(char) ord_result = ord_value if char.isdigit(): "number" elif char.isalpha(): "letter" else: "punctuation" return (char,ord_result) print character_info("t") print character_info("3") print character_info("-") Practical output: ('t', 116) ('3', 51) ('-', 45) Expected output ('t', 116, letter) ('3', 51, number) ('-', 45, punctuation)
favorite count: 0
tagged with: tuples
answer count: 3
has answer: http://stackoverflow.com/a/46867513
tagged with: python
has comment: http://stackoverflow.com/comment/80682351

http://stackoverflow.com/comment/80458939
type: QuestionComment
has text: Of course! This was it - thanks a lot :)
score: 0
comment on: http://stackoverflow.com/q/46756709
type: Comment

http://stackoverflow.com/a/46797503
has body: By using pd.cut R=list(range(100, 225,25)) R=[0]+R+[np.inf] label=[0]+list(np.arange(1.0,2.25,0.25)) pd.cut(df.value,R,labels=label,right=False) Out[16]: 0 0.00 1 1.00 2 1.00 3 1.00 4 1.25 5 1.25 6 1.50 7 1.75 8 1.75 9 2.00 10 2.00 11 2.00 12 2.00 13 1.75 14 1.50 15 1.25 16 1.00 17 1.00 18 0.00
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46797176
type: Answer

http://stackoverflow.com/comment/80448041
comment on: http://stackoverflow.com/q/46751044
type: Comment
type: QuestionComment
score: 0
has text: your `else` case is empty and in some cases not properly indented (it should be aligned with the `if`)

http://stackoverflow.com/comment/80687618
comment on: http://stackoverflow.com/q/46870140
type: Comment
type: QuestionComment
has text: Scroll down to find python code.
score: 0

http://stackoverflow.com/comment/80633270
has text: Have you checked your error log? A good idea is also to turn `display_errors` on in your local PHP environment. Read more here: [How do I get PHP errors to display?](http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46842767

http://stackoverflow.com/comment/80666328
comment on: http://stackoverflow.com/q/46859257
has text: [Valuable read](https://cs.stackexchange.com/questions/9199/best-random-permutation-employing-only-one-random-number).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46789761
has comment: http://stackoverflow.com/comment/80528505
tagged with: python
upvote count: 4
tagged with: coding-style
has body: I hope this question does not get closed/downvoted, as it really takes a good portion of the time I spend coding. As a developer more focused on Python, I try to follow PEP8 standard, but for some variable names it becomes really tricky to me. Let's say the word TEMPERATURE. If I want to have a variable to store a list of temperatures, I would name it: temperature_list = [] However, as the code gets more complex, let's say I have to call a function with the temperature_list as an argument: calling_function(variable_with_long_name, temperature_list, another_long_name_variable) You can clearly see where it leads... So I decide to rename temperature_list to temp_list. Which can sound as a good choice, right? Except... If I also want to store TEMPORARY FILES in a list, I may occur to have: temp_list = [] temp_file_list = [] It may come to the point where my variables start messing around and turning the code a bit tricky to follow. What is the convention and what other actions do programmers do when face such situation? Is there any reference to follow for such cases, like a casebook of good variable names for certain nouns? -- edit If you vote for closing it, at least explain why! --'
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80527473
has title: What is the best standard for shortening words in the code?
has comment: http://stackoverflow.com/comment/80527688
type: Question
tagged with: standards
score: 4
has comment: http://stackoverflow.com/comment/80528255
has comment: http://stackoverflow.com/comment/80527626
has answer: http://stackoverflow.com/a/46790103
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80526652
has comment: http://stackoverflow.com/comment/80525971

http://stackoverflow.com/q/46809445
has body: Hi I am using Python to sort my GPS data based on the timestamps and also I would like to add the function of error if the location is same but different timestamp is not possible. I found that my data set is a bit weird. If you can can you suggest new data set type? So far I have this... dic_loc = {'latitude': [], 'longitude': [], 'timestamp': []} def make_timestamped_loc(La, Lng, TS): dic_loc['latitude'].append(La) dic_loc['longitude'].append(Lng) dic_loc['timestamp'].append(int(TS)) make_timestamped_loc(37.481236, 126.952733, 1483196400) make_timestamped_loc(37.310045, 127.101255, 1408323255) make_timestamped_loc(37.383065, 126.672596, 1508322531) make_timestamped_loc(37.383065, 126.672596, 1444999230) def sort_locs(dictSorting): # sortedByTime = sorted(dictSorting.items(), key = lambda i:i[1]) # print(sortedByTime) dictSorting.sort() # print(dic_loc) sort_locs(dic_loc['timestamp']) print(dic_loc) This code only sort the timestamp values. But I would like my other keys to follow the order of timestamp's value.
has comment: http://stackoverflow.com/comment/80567120
accepted answer: http://stackoverflow.com/a/46809526
possible better answer: http://stackoverflow.com/a/46809630
has comment: http://stackoverflow.com/comment/80566811
has comment: http://stackoverflow.com/comment/80567055
has answer: http://stackoverflow.com/a/46809526
score: 0
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46810152
has comment: http://stackoverflow.com/comment/80566966
has answer: http://stackoverflow.com/a/46809630
has comment: http://stackoverflow.com/comment/80566893
type: Question
has answer: http://stackoverflow.com/a/46810104
has title: Sorting dictionary by value
has comment: http://stackoverflow.com/comment/80566735
type: AnsweredQuestion

http://stackoverflow.com/comment/80673465
score: 0
type: AnswerComment
has text: Have to appear there otherwise you never would be able to add a note to any notebook. This is also out of scope of the question.
type: Comment
comment on: http://stackoverflow.com/a/46862594

http://stackoverflow.com/q/46863537
has comment: http://stackoverflow.com/comment/80675792
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80679801
tagged with: python
has body: I am currently working for a newspaper distribution company and need to compare the customer data in our system to the customer data provided by the Newspaper publisher. Both sets of data come in the format of CSV, I need to find customers that are in one CSV and not in the other, a customer that's in our CSV but not in the publisher's CSV would mean we are delivering papers without getting paid. Which is something we obviously want to know. Both CSVs contain columns such as surname, first name, address, the number of newspaper required for each day of the day. As I mentioned above, I just need to run some sort of script to list all customers that are only in either of the CSV but not in both, as well as customers that are in both CSV but are receiving differing amount of papers(ie. receiving weekend papers only on our database but are receiving weekday papers on the other database.) I have been using excel to do this, merge both sets of data onto one page and sort by surname then manually delete the matching customers. To further complicate things, 1/10 high street and unit 1, 10 high st are the same thing, but I don't know if it's possible to have this sort of fault tolerance built in, I was thinking of ignoring the street number and only have the script look at street name, surname, and number of deliveries received. Here is a sample of our CSV: sun mon tue wed thu fri sat JACKSON JANET 3 LONG COURT 1 1 1 1 1 1 1 JACKSON NICHOLAS 26 HERITAGE Court 1 1 1 1 0 1 1 JACKSON CHRIS 36/8 POTT Circuit 0 0 0 0 1 1 1 Here is a sample of the publisher's CSV: sun mon tue wed thu fri sat JACKSON J 3 LONG CRT 1 1 1 1 1 1 1 JACKSON NICHOLAS 26 HERITAGE Crt 1 1 1 1 1 1 1 JACKSON MICHAEL 44 BRENTWICK DR 1 0 0 0 0 0 0 JACKSON CHRIS Unit 36,8 POTT Cct 0 0 0 0 1 1 1 I am hoping the script can ignore Janet and Chris even though the data don't match exactly, highlight Nicholas(due to the missing thursday paper) and Michael (due to him not being in both CSVs)
favorite count: 0
has title: compare two csv files for unique entries
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: excel
type: Question

http://stackoverflow.com/q/46872668
has comment: http://stackoverflow.com/comment/80692890
answer count: 1
has comment: http://stackoverflow.com/comment/80693686
has answer: http://stackoverflow.com/a/46874307
has comment: http://stackoverflow.com/comment/80693076
accepted answer: http://stackoverflow.com/a/46874307
score: 0
has comment: http://stackoverflow.com/comment/80693331
tagged with: python
linked to: http://stackoverflow.com/q/31834743
has comment: http://stackoverflow.com/comment/80703365
tagged with: python-3.x
tagged with: sys
tagged with: logging
has comment: http://stackoverflow.com/comment/80693554
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80693663
tagged with: stdout
has title: Redirecting (sys.)stdout to logging (python3)
has body: Overview: two scripts, one for logging (ddlog) the other uses paramiko for ssh connection and command execution (ddlogin). The logger works well and creates log files for each host that I connect to, however the handler for standard input and standard output do not trigger logging events. Currently I get the below io error. I have tried to modify logging.StreamHandler() with sys.stdout but this does not seem to work either. Error: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "ddlogin.py", line 89, in run main(host) File "ddlogin.py", line 60, in main line = sys.stdout.read().splitlines(4096) io.UnsupportedOperation: not readable ddlog: import logging fileLogger = logging.getLogger() fileLogger.setLevel(logging.DEBUG) switch_log_levels = { 'debug': fileLogger.debug, 'info': fileLogger.info, 'warning': fileLogger.warning, 'error': fileLogger.error, 'critical': fileLogger.critical } def setup( logFile): global fileLogger logFormatStr = "[%(asctime)s %(threadName)s, %(levelname)s] %(message)s" consoleFormatStr = "[%(threadName)s, %(levelname)s] %(message)s" # File Handler for log file logFormatter = logging.Formatter(logFormatStr) fileHandler = logging.FileHandler(logFile ) fileHandler.setFormatter( logFormatter ) fileLogger.addHandler( fileHandler ) # Stream Handler for stdout, stderr consoleFormatter = logging.Formatter(consoleFormatStr) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter( consoleFormatter ) consoleHandler.setLevel(logging.INFO) fileLogger.addHandler( consoleHandler ) def event( string, level='debug',print_screen=False, remove_newlines=False ): if remove_newlines: string = string.replace('\r', '').replace('\n', ' ') if print_screen: switch_log_levels[level](string) switch_log_levels[level](string) ddlogin: import argparse, ddlog, os, paramiko, sys from threading import Thread from queue…
type: Question
has comment: http://stackoverflow.com/comment/80693152
has comment: http://stackoverflow.com/comment/80692498

http://stackoverflow.com/a/46750208
accepted answer of: http://stackoverflow.com/q/46750071
answers question: http://stackoverflow.com/q/46750071
score: 0
type: AcceptedAnswer
type: Answer
has body: You need to print the question then ask for input: print("Who is Conor Mcgregor?") print("A) A Chef") print("B) A Fighter") print("C) A Doctor") answer = input('A/B/C?: ')

http://stackoverflow.com/q/46878422
has comment: http://stackoverflow.com/comment/80703976
downvote count: 1
type: Question
score: -1
upvote count: 0
has body: I’m having trouble with installation of (or is it usage of?!) the beautifulsoup4 package, with Python 3.6, on MacOS High Sierra (10.3). I experienced the problem first in PyCharm and then also had same issue from the MacOS terminal, as demonstrated below. I’ve searched high and low on Stackoverflow and on the web at large, but cannot find a post/explaination that seems to meet the very specific symptoms I’m experiencing. First three lines of my Python 3 code file called “main.py”…. import numpy as np import matplotlib.pyplot as plt import beautifulsoup4 as bs When I execute it, I get the following error, seemingly indicating that the beautifulsoup4 package is not installed….. DangerZone:test09-playwithnumpyandscipy bruce$ python3 main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import beautifulsoup4 as bs ModuleNotFoundError: No module named 'beautifulsoup4' Yet, when I request a "list" of installed modules from pip3, i get the following.... DangerZone:test09-playwithnumpyandscipy bruce$ pip3 list beautifulsoup4 (4.6.0) certifi (2017.7.27.1) chardet (3.0.4) cycler (0.10.0) idna (2.5) inflection (0.3.1) matplotlib (2.0.2) more-itertools (3.2.0) numpy (1.13.1) pandas (0.20.3) pip (9.0.1) pyparsing (2.2.0) python-dateutil (2.6.1) pytz (2017.2) Quandl (3.2.0) requests (2.17.3) scikit-learn (0.19.0) scipy (0.19.1) setuptools (28.8.0) six (1.10.0) sklearn (0.0) urllib3 (1.21.1) Seems that beautifulsoup4 is installed, so why the earlier error? What am I doing wrong?
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46878515
type: UnansweredQuestion
tagged with: python
has title: For Python3, installing beautifulsoup4, on MacOS, unable to import within code?

http://stackoverflow.com/comment/80753712
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46883194
has text: Check your spelling. As pointed out above, it is send_keys and not send_Keys.
score: 0

http://stackoverflow.com/comment/80521667
comment on: http://stackoverflow.com/q/46787651
has text: Not sure why you think the class needs to be in your code. Django models are converted into table names using the pattern `<app_name>_<model_name>`, so you presumably have a Connectors app with a TestEx1 model.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46791642
has comment: http://stackoverflow.com/comment/80529771
linked to: http://stackoverflow.com/q/2612802
downvote count: 1
has comment: http://stackoverflow.com/comment/80529783
has title: In python why is a list not the same as list[:]?
favorite count: 0
has comment: http://stackoverflow.com/comment/80532485
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80532675
has answer: http://stackoverflow.com/a/46791711
has comment: http://stackoverflow.com/comment/80530217
tagged with: python
has comment: http://stackoverflow.com/comment/80529759
answer count: 4
has body: I have a list, ls = [0 1 2 3 4] and I am running the following: print(ls is ls[:]) I am getting the output as False. Why are they not the same list? When I print both versions I get the same list printed.
tagged with: list
score: 1
duplicate of: http://stackoverflow.com/q/132988
has comment: http://stackoverflow.com/comment/80529794
has comment: http://stackoverflow.com/comment/80535189
type: Question
has answer: http://stackoverflow.com/a/46791713
has answer: http://stackoverflow.com/a/46791768
has comment: http://stackoverflow.com/comment/80530010
linked to: http://stackoverflow.com/q/2988017
has answer: http://stackoverflow.com/a/46791750
has comment: http://stackoverflow.com/comment/80530687
upvote count: 2
linked to: http://stackoverflow.com/q/132988

http://stackoverflow.com/q/46752200
type: AnsweredQuestion
tagged with: list
tagged with: numbers
upvote count: 3
has comment: http://stackoverflow.com/comment/80450293
tagged with: sum
has body: So let's say I have a list, [23, 62, 82, 41, 12] How would I check to see if a number, say 115, is the sum of any of those numbers and how would I get the said numbers that add up to it? in this case the answer would be: [41, 12, 62] How would I do this?
type: Question
accepted answer: http://stackoverflow.com/a/46752487
score: -2
downvote count: 5
has answer: http://stackoverflow.com/a/46752487
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/17434070
has title: Python How to know if numbers in a list equal to a number
tagged with: python
has comment: http://stackoverflow.com/comment/80450233
has comment: http://stackoverflow.com/comment/80450492
has comment: http://stackoverflow.com/comment/80450228
has comment: http://stackoverflow.com/comment/80450224

http://stackoverflow.com/comment/80666852
comment on: http://stackoverflow.com/a/46859562
type: AnswerComment
has text: The result is missing a row with index `2011-01-11`
type: Comment
score: 0

http://stackoverflow.com/q/46831705
has answer: http://stackoverflow.com/a/46831790
tagged with: function
answer count: 1
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/46831790
tagged with: return
type: AnsweredQuestion
has title: how to return the value of an input parameter in a for loop
has comment: http://stackoverflow.com/comment/80610960
tagged with: loops
type: Question
has body: I have the following function in python def find_new_similar(tfidf_matrix2, index, tfidf_matrix, top_n = 1): cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten() related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index] return [(index, cosine_similarities[index]) for index in related_docs_indices][0:top_n] where upon calling this I get something like: &gt;&gt;&gt; find_new_similar(tfidf_matrix2, 40, tfidf_matrix) ([(260816, 0.55759049663331683)]) which is the index of related_docs_indices and the result of cosine_similarities for the index given as an input to my function. I would also like to return the intial index i that I pass to the function. I have tried : def find_new_similar(tfidf_matrix2, index, tfidf_matrix, top_n = 1): cosine_similarities = linear_kernel(tfidf_matrix2[index:index+1], tfidf_matrix).flatten() related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index] return [(index, cosine_similarities[index]) for index in related_docs_indices][0:top_n], index i.e. just adding ,index to the end of the return command. but this outputs: &gt;&gt;&gt; find_new_similar(tfidf_matrix2, 40, tfidf_matrix) ([(260816, 0.55759049663331683)], 0) but I am actually expecting ([(260816, 0.55759049663331683)], 40) Thanks in advance

http://stackoverflow.com/comment/80671637
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46862018
score: 0
has text: See [What's perfect counterpart in Python for "while not eof"](//stackoverflow.com/q/15599639)

http://stackoverflow.com/q/46783974
has body: Recently I am studying Dimension Reduction methods and I found that the python package "sklearn.feature_selection" seems pretty useful, but the problem is the method SelectPercentile.fit doesn't explain how it calculates the score function. link Does anyone know how it works? For instance, if I select "SelectFdr" for "SelectPercentile", and the SelectFdr method's criterion is depending on each p-value of each feature. How do I know which ways does "SelectFdr" sets hypothesis or defines error rates? SelectFdr method which subscription is "Select features based on an estimated false discovery rate." So it must be using some classification methods at first, so it can calculate the false discovery rate, my problem is what classification method is in "SelectPercentile".
answer count: 1
tagged with: data-mining
tagged with: scikit-learn
tagged with: dimensionality-reduction
favorite count: 0
has answer: http://stackoverflow.com/a/46784267
has comment: http://stackoverflow.com/comment/80514670
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 1
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/46784267
downvote count: 1
type: Question
has title: How does the SelectPercentile score function work?

http://stackoverflow.com/q/46888976
tagged with: arrays
score: -1
has comment: http://stackoverflow.com/comment/80725952
answer count: 2
has comment: http://stackoverflow.com/comment/80726249
favorite count: 0
has comment: http://stackoverflow.com/comment/80726068
has answer: http://stackoverflow.com/a/46889691
upvote count: 2
has comment: http://stackoverflow.com/comment/80726081
has comment: http://stackoverflow.com/comment/80725666
possible better answer: http://stackoverflow.com/a/46889056
has comment: http://stackoverflow.com/comment/80726413
tagged with: python
has answer: http://stackoverflow.com/a/46889056
accepted answer: http://stackoverflow.com/a/46889691
has comment: http://stackoverflow.com/comment/80725958
type: AnsweredQuestion
tagged with: math
downvote count: 3
has comment: http://stackoverflow.com/comment/80725512
type: Question
has title: How to replace all elements of Python NumPy Array that are greater than a several values?
tagged with: numpy
has body: I know that I can replace all elements of Python NumPy Array that are greater than some value: np.putmask(A, A&gt;0.5, 5) Where A&gt;0.5 is the threshold and 5 the new replacement. However, how can I do it for more conditions? for example for: if x.all &lt;0: return 00.1 elif x.all &gt;0: return 1 Where x is an array. I tried to: np.putmask(x, x&lt;0, 00.1) and np.putmask(x, x&gt;0, 1) However, I would like to do it in a single line. Any idea of how to do this type of replacements in just a single line with putmask or any other method?

http://stackoverflow.com/comment/80722808
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46887589
has text: First of all Thank you very much to correct my code that was great Second i have try what you suggested but also i get the same result CSV file in one Column Can you please try this code with your SAME Enviroment to know if the problem from the code or there are Aconfigration must i do with MS Exel 2016
type: AnswerComment

http://stackoverflow.com/comment/80749637
has text: Could I not have simply done `df['rand_index'] = np.random.permutation(len(df))` for the first line?
score: 3
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46848375

http://stackoverflow.com/q/46842732
has answer: http://stackoverflow.com/a/46842844
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80633286
has comment: http://stackoverflow.com/comment/80646677
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/46842844
has body: I have just started out with Python, I am trying to get a way to get a shortcut on my Start menu or taskbar that I can click on and it will cause Command Prompt or PowerShell to start my Python file
tagged with: python
score: -2
answer count: 1
tagged with: command-prompt
has title: How to create a powershell shortcut for my python file
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/46881507
downvote count: 0
has title: Python install requests
answer count: 1
has comment: http://stackoverflow.com/comment/80710271
favorite count: 0
linked to: http://stackoverflow.com/q/19292957
upvote count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80710253
has answer: http://stackoverflow.com/a/46881675
type: Question
has body: I am very new to programming and I am trying to install the package requests to python. In the terminal on my mac I am entering pip install requests. I am getting the following error message. Could not find platform independent libraries &lt;prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'encodings' Current thread 0x00007fff9e4ac3c0 (most recent call first): Abort trap: 6 I would appreciate suggestions.
has comment: http://stackoverflow.com/comment/80710334

http://stackoverflow.com/q/46859043
has body: I am doing a cryptography assignment in python and I need to: - split a string - replace the letters - rejoin it so that it is one word. This is the full code but I am stuck on the for loop under def encode(plain). """ crypto.py Implements a simple substitution cypher """ alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" def menu(): print("Secret decoder menu") print("0) Quit") print("1) Encode") print("2) Decode") print("What do you want to do?") response = input() return response def encode(plain): for i in range(len(plain)): plain = plain.upper() x = plain[i:i+1] y = alpha.index(x) z = key[y:y+1] plain[x] = z return plain def main(): keepGoing = True while keepGoing: response = menu() if response == "1": plain = input("text to be encoded: ") print(encode(plain)) elif response == "2": coded = input("code to be decyphered: ") print (decode(coded)) elif response == "0": print ("Thanks for doing secret spy stuff with me.") keepGoing = False else: print ("I don't know what you want to do...") return main main() menu()
has comment: http://stackoverflow.com/comment/80665740
type: Question
has comment: http://stackoverflow.com/comment/80665746
has comment: http://stackoverflow.com/comment/80665803
has comment: http://stackoverflow.com/comment/80665794
tagged with: replace
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46859089
tagged with: string
has comment: http://stackoverflow.com/comment/80665752
has comment: http://stackoverflow.com/comment/80665723
has comment: http://stackoverflow.com/comment/80665704
tagged with: python
possible better answer: http://stackoverflow.com/a/46859166
has answer: http://stackoverflow.com/a/46859166
type: AnsweredQuestion
has title: python how to split a string and rejoin it
accepted answer: http://stackoverflow.com/a/46859089

http://stackoverflow.com/q/46755445
type: Question
has answer: http://stackoverflow.com/a/46756260
has body: I would like to wirte a small program, which automatically takes a screenshot of a video, when a certain amount of pixel (say 100 ) "pixel_change" change. I also have a subRib file, which holds the transcript of the video file. I would like to kind of make a image book, where I have the images of the slide, and on the bottom the transcript for the appropriate slides. Automatically extract all slides from videos with timestamb. Read subRib file Assign the slides according to their timestambs to each text block from the subRib file Export Textblock and accosciated slides as one image How can I do it ? Thanks for any help !!
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has title: Python _ Automatic screenshot taker_with transcript
has comment: http://stackoverflow.com/comment/80456311
tagged with: windows
tagged with: python
tagged with: video

http://stackoverflow.com/comment/80610823
comment on: http://stackoverflow.com/q/46776280
score: 0
type: Comment
type: QuestionComment
has text: And what's the problem exactly?

http://stackoverflow.com/comment/107390150
type: Comment
comment on: http://stackoverflow.com/a/60284493
has text: This also worked for me. Here's another resource that agrees with this answer: https://www.shanelynn.ie/pandas-csv-error-error-tokenizing-data-c-error-eof-inside-string-starting-at-line/
type: AnswerComment
score: 0

http://stackoverflow.com/q/46839861
has answer: http://stackoverflow.com/a/46843346
has comment: http://stackoverflow.com/comment/80627720
tagged with: scrapy
has comment: http://stackoverflow.com/comment/80627732
has body: I'm learning scrapy (with splash) and building a spider to scrape results from js enabled pages. My spider works and does return results for js pages. However, it does not return price from this link https://www.zara.com/us/en/bejewelled-appliqu%C3%A9-dress-p07854034.html?v1=4818592&amp;v2=733885 xpath used: //*[contains(concat( " ", @class, " " ), concat( " ", "_product-price", " " ))]//span/text() The above xpath does return results in the browser but does not return results when invoked via scrapy. Here's my spider call yield scrapy.Request(url, callback=self.parse_page, dont_filter=True, meta={'splash': {'args': {'wait': 5,},'endpoint': 'render.html',}}) Can you please help figure out why price from the site is not returned? Thanks!
tagged with: javascript
has answer: http://stackoverflow.com/a/46839982
accepted answer: http://stackoverflow.com/a/46843346
type: AnsweredQuestion
score: 3
has title: Scrapy splash not returning results
downvote count: 0
tagged with: scrapy-splash
favorite count: 0
possible better answer: http://stackoverflow.com/a/46839982
type: Question
tagged with: python
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/80656100
type: AnswerComment
has text: So, ideally speaking, if I change the delay to 1, they should perform the same but I might face problems as mentioned (intercept oscillation). Right? @TomDLT
score: 0
comment on: http://stackoverflow.com/a/46850955
type: Comment

http://stackoverflow.com/q/46860986
has body: As a somewhat novice starting to create some python modules, I have to ask what needs to be inside __init__.py to make the modules or program better and feel more professional? I know that __init__.py doesn't really need anything inside it to work but looking at some professionally made python modules and packages, there seems to be a lot inside it? Can you please tell me what needs to be there? Or is it just optional to actually put anything in there other than a docstring explaining what the module does. Not the '__init__' function, but the file __init__.py
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/80669455
type: Question
upvote count: 2
tagged with: init
duplicate of: http://stackoverflow.com/q/625083
has title: What needs to be inside of __init__.py
tagged with: python-2.7
linked to: http://stackoverflow.com/q/625083
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/80670352
has comment: http://stackoverflow.com/comment/80669952
tagged with: python
tagged with: module

http://stackoverflow.com/a/46836788
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: You'll want to remove the empty line between While True: and move = input Python cares about every bit of indentation. Also, make sure while is lowercase.
answers question: http://stackoverflow.com/q/46836735

http://stackoverflow.com/q/46810996
favorite count: 0
type: Question
tagged with: python
has body: I wrote an custom kernel op in tensorflow for reading csv format data. It works fine in the TestCase with the sess object return by test_session() function. When I turn to normal codes, the reader op returns the same result every time. Then I put some debug printing at the beginning of the MyOp:Compute function. It seems like after the first run, the sess.run(myop) never calls the MyOp:Compute function at all. Then I return to my test cases, if I replace the session object with an tf.Session() instead of self.test_session(), it failed the same way. Anyone has any idea about this? to share more details, here's my mini demo codes: https://github.com/littleDing/mini_csv_reader in the test case: def testSimple(self): input_data_schema, feas, batch_size = self.get_simple_format() iter_op = ops.csv_iter('./sample_data.txt', input_data_schema, feas, batch_size=batch_size, label='label2') with self.test_session() as sess: label,sign = sess.run(iter_op) print label self.assertAllEqual(label.shape, [batch_size]) self.assertAllEqual(sign.shape, [batch_size, len(feas)]) self.assertAllEqual(sum(label), 2) self.assertAllEqual(sign[0,:], [7,0,4,1,1,1,5,9,8]) label,sign = sess.run(iter_op) self.assertAllEqual(label.shape, [batch_size]) self.assertAllEqual(sign.shape, [batch_size, len(feas)]) self.assertAllEqual(sum(label), 1) self.assertAllEqual(sign[0,:], [9,9,3,1,1,1,5,4,8]) for normal call: def testing_tf(): path = './sample_data.txt' input_data_schema, feas, batch_size = get_simple_format() with tf.device('/cpu:0'): n_data_op = tf.placeholder(dtype=tf.float32) iter_op = ops.csv_iter(path, input_data_schema, feas, batch_size=batch_size, label='label2') init_op = [tf.global_variables_initializer(), tf.local_variables_initializer() ] with tf.Session() as sess: sess.run(init_op) n_data = 0 for batch_idx in range(3): print '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; before run batch', batch_idx ## it should be some debug printing here, but nothing come out when batch_i…
upvote count: 1
has comment: http://stackoverflow.com/comment/80569134
has title: Why do custom read op only works on test_session
answer count: 1
has answer: http://stackoverflow.com/a/46892223
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/80603258
has comment: http://stackoverflow.com/comment/80603265
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/46892223
has comment: http://stackoverflow.com/comment/80573134
score: 1

http://stackoverflow.com/comment/80519940
has text: @CodeNoob, Check my answer, if it does not work then let me know I can post another solution to this
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46786613

http://stackoverflow.com/q/46853662
has comment: http://stackoverflow.com/comment/80662480
answer count: 4
tagged with: list
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/46854460
type: Question
has answer: http://stackoverflow.com/a/46853913
score: -2
has body: Hi there so I am looking to build this python function with simple things like def, find etc. so far I know how to get the first part of the code. Given a string such as "HELLODOGMEMEDOGPAPA", I will need to return a list that gives me three things: Everything before the word dog which i will denote as before_dog The word dog until dog appears again dog_todog Everything after the second time dog appears will be denoted by after_todog The list will be in the form [before_dog,dog_todog,after_todog]. so for example given ("HELLODOGMEMEDOGPAPADD") this will return the list ("HELLO","DOGMEME","DOGPAPADD") another example would be ("HEYHELLOMANDOGYDOGDADDY") this would return the list ("HEYHELLOMAN","DOGY","DOGDADDY") but if I have ("HEYHELLODOGDADDY") the output will be ("HEYHELLO","DOGDADDY","") also if dog never appears ("HEYHELLOYO") then the output will be ("HEYHELLOYO,"","") This is what I have so far: def split_list(words): # declare the list lst = [] # find the first position first_pos=words.find("DOG") # find the first_pos before_dog = words [0:first_pos] lst.append(before_dog) return lst
has title: Rearranging a string based on specific requirements
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/80654891
favorite count: 0
has answer: http://stackoverflow.com/a/46854172
has comment: http://stackoverflow.com/comment/80656194
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80662449
tagged with: python
has answer: http://stackoverflow.com/a/46853849
has comment: http://stackoverflow.com/comment/80654832

http://stackoverflow.com/a/46755031
type: Answer
accepted answer of: http://stackoverflow.com/q/46754707
score: 0
answers question: http://stackoverflow.com/q/46754707
has body: The handler function has 2 params event and context def handler_name(event, context): ... return some_value http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html
type: AcceptedAnswer

http://stackoverflow.com/q/46859511
answer count: 1
has comment: http://stackoverflow.com/comment/80666871
favorite count: 0
has answer: http://stackoverflow.com/a/46859963
tagged with: python
has title: In python, how does one make an input parameter to function immutable?
linked to: http://stackoverflow.com/q/17291791
has body: Suppose we have a function: import copy def demo_function(list_in) list_out = copy.deepcopy(list_in) list_in.append("howdy") return list_out Notice that we append to list_in instead of list_out. However, demo_function is not actually supposed to modify its input. We want to enforce this. An error should be thrown if someone accidentally modifies list_in somewhere inside the body of demo_function How can we implement this type of error checking? The following is my best attempt, but it doesn't work. The string "howdy" still ends up getting appended to list_in; no error is thrown class Frozen(object): # The Frozen class was developed by ActiveState Software Inc. def __init__(self, value): self._value = value def __getattribute__(self, name): if name == '_value': return super(Frozen, self).__getattribute__(name) v = getattr(self._value, name) return v if hasattr(v, '__hash__') else Frozen(v) def __setattr__(self, name, value): if name == '_value': super(Frozen, self).__setattr__(name, value) else: raise Exception("Can't modify frozen object {0}".format(self._value)) def const(some_function): def wrapper(fargs,*args,**kwargs): for f in fargs: f = Frozen(f) pass for a in args: a = Frozen(a) pass for k in kwargs: k = Frozen(k) pass some_function(fargs, *args, **kwargs) return wrapper @const def demo_function(list_in): list_out = copy.deepcopy(list_in) list_in.append("howdy") return list_out lisandra = [1, 2, 3, 4, 5] modified_lisandra = demo_function(lisandra) print(lisandra) Edit: I regret using a list as my example. I really want a general solution that would make a function's inputs immutable (const) no matter what their datatypes are. It is very easy to convert a python list into a tuple. However, what if the input to the function is an instance of some user-defined class? You do not know how to convert it into a tuple. Even if you do know how to convert the object into a tuple, you do not want to write a different solution for each and every datatype in your project.…
has comment: http://stackoverflow.com/comment/80688662
tagged with: constants
tagged with: immutability
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80687415
has comment: http://stackoverflow.com/comment/80666686
type: UnansweredQuestion
downvote count: 3
tagged with: parameter-passing
linked to: http://stackoverflow.com/q/21000994
has comment: http://stackoverflow.com/comment/80667110
score: -3
has comment: http://stackoverflow.com/comment/80666720
type: Question
has comment: http://stackoverflow.com/comment/80666738
upvote count: 0

http://stackoverflow.com/q/46780521
has comment: http://stackoverflow.com/comment/95787943
has comment: http://stackoverflow.com/comment/80507333
has comment: http://stackoverflow.com/comment/95787913
has comment: http://stackoverflow.com/comment/80507196
tagged with: python
has body: I am trying to install the python submodule ANCA in my mac, for which I have run the following: pip install git+https://github.com/acadev/anca.git getting the following: . . . Installing collected packages: anca Running setup.py install for anca ... done Successfully installed anca-0.1.5 I have miniconda installed in my computer, and I have checked that the module and its files and dependencies are correctly located in /usr/local/miniconda2/lib/python2.7/site-packages/anca When I import anca in my notebook it does not give me any error, but if I try to import a submodule it gives me the following error: from anca import IterativeMeansAlign ImportError: cannot import name IterativeMeansAlign It is the same with other submodules, but all of them are apparently well installed with all their files. I have also tried to install the package using Git: git clone https://github.com/acadev/anca.git sudo python setup.py install with the same result. Note: 'locate' is not able to locate the module anca unlike the rest of the python modules although I can see all the files in the right location. It is the first time this happens to me. Thanks a lot for your help, any suggestion will be very appreciated.
favorite count: 0
answer count: 0
tagged with: installation
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80507351
tagged with: git
has comment: http://stackoverflow.com/comment/80508853
score: 3
linked to: http://stackoverflow.com/q/45087711
upvote count: 3
has title: I cannot import a python submodule after successful installation of the module
type: Question
has comment: http://stackoverflow.com/comment/80507228
downvote count: 0
linked to: http://stackoverflow.com/q/54490717
has comment: http://stackoverflow.com/comment/80507139
has comment: http://stackoverflow.com/comment/80523288
linked to: http://stackoverflow.com/q/32814361

http://stackoverflow.com/q/46846194
score: 1
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/46847771
upvote count: 1
answer count: 1
tagged with: scipy
tagged with: numpy
tagged with: normalization
has title: Numpy ndarray image pixel mean for pixel values greater than zero: Normalizing image
tagged with: image
has answer: http://stackoverflow.com/a/46847771
has body: I am trying to read and normalize a 3 channel image in numpy. For each channel in the image, I want to calculate mean of the pixel values which are greater than zero. I started with: from scipy import misc img = misc.imread('test.png') print(type(img) ) #&lt;type 'numpy.ndarray'&gt; print(img.shape) #(512, 512, 3) But I am not sure first 1.) how to index out positive values preserving dimension and without flattening the array. And 2.) How to take channel wise mean of the selected positive values. My full normalization process is like: img_mean = mean(img[img &gt;0])#channel wise mean of positive pixels img_std = std(img[img&gt;0]) #channel wise std. deviation of positive pixels img_norm = (img - img_mean)/img_std img_norm[img_norm &lt; -1] = 0 #setting pixel values less than 1 to 0. Here is an example of image I am working with
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/80452563
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46753447
has text: Do you get all `NaN`s in output?
score: 0

http://stackoverflow.com/comment/80462336
type: QuestionComment
comment on: http://stackoverflow.com/q/46757906
score: 0
has text: Aha, that makes sense. Well, then in that case the only thing I would change would be `from itertools import zip_longest, islice` Then simply `zip_longest(x, islice(x, 1, None))` instead of your `pairwise`
type: Comment

http://stackoverflow.com/comment/80649250
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46850111
has text: @aLoneStrider There are multiple columns in which values are missing, for example for heavier compounds, more than half of the features have NA values, not just HFUS. The answer would have to take this into account...I cannot drop compounds for my analysis.
score: 0

http://stackoverflow.com/comment/80590116
comment on: http://stackoverflow.com/a/46819989
has text: @scharette i must admit that my example is far from ideal because over and over dictionary with mappings is recreated, but as an example of organizing conditions - it's good enough
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46769458
score: 0
type: Answer
has body: I think you are trying add two entries with Date as key and values are different. In dictionary you cant have duplicate keys. That's why after the for loop Dictionary is updated with only one Date key entry and only one responder entry
answers question: http://stackoverflow.com/q/46769257

http://stackoverflow.com/comment/80589270
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46820715
score: 0
has text: @Osprey I've created a general answer, so that the solution is easier to find.

http://stackoverflow.com/comment/122235783
has text: @user11655900 The worst case running time of quick sort is O(n^2), which depends on the dataset and pivot selection. You may want to debug through your code to see why your algorithm is performing badly.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46786424
type: Comment

http://stackoverflow.com/q/46802739
has body: For example, is there a difference between the following two? session = Session() # Session is a session maker try: # do some work session.commit() except: session.rollback() finally: session.close() and session = Session() try: # do some work session.commit() finally: session.close() The latter is what I used to do, because I assumed closing the session before committing (in case of an error) had the same effect as rolling back. But I saw the first form here.
tagged with: sql
answer count: 1
linked to: http://stackoverflow.com/q/17008441
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46803458
has comment: http://stackoverflow.com/comment/80558009
tagged with: python
type: AnsweredQuestion
tagged with: transactions
has title: Does closing a SQLAlchemy ORM Session roll back uncommitted changes?
accepted answer: http://stackoverflow.com/a/46803458
tagged with: sqlalchemy
type: Question
score: 9
upvote count: 9

http://stackoverflow.com/a/46768693
has body: Categorical variables should be handled accordingly, i.e. with one-hot encoding After that the MinMax scaler would not really change the encoded features. Answering your last question - the scaler simply stores minima ans maxima for each input feacture separatley, so it can make inverse transform. And it makes sense to scale features independently - they may be of different scale AND even nature.
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46768519
upvote count: 2

http://stackoverflow.com/comment/80492188
score: 0
type: QuestionComment
has text: These approaches have their use, but yes, generally using dynamic variables makes code harder to understand
type: Comment
comment on: http://stackoverflow.com/q/46773220

http://stackoverflow.com/a/46832159
has comment: http://stackoverflow.com/comment/80612072
answers question: http://stackoverflow.com/q/46832120
has comment: http://stackoverflow.com/comment/80611981
has comment: http://stackoverflow.com/comment/80612567
downvote count: 0
has comment: http://stackoverflow.com/comment/80612474
has comment: http://stackoverflow.com/comment/80612518
has comment: http://stackoverflow.com/comment/80612815
has comment: http://stackoverflow.com/comment/80612838
has body: You have to indent correctly: if not (userResponse =="n" or userResponse =="y") : exit('Error') You could also raise an exception to get an even more descriptive error message: userResponse = input ("n or y?") if not (userResponse =="n" or userResponse =="y") : raise ValueError('Does not work')
has comment: http://stackoverflow.com/comment/80612327
has comment: http://stackoverflow.com/comment/80612253
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80612374
has comment: http://stackoverflow.com/comment/80612639

http://stackoverflow.com/q/46880678
favorite count: 0
tagged with: cx-freeze
accepted answer: http://stackoverflow.com/a/46881003
answer count: 1
has title: CX_freeze executable will not work. _tkinter DLL load failed
tagged with: tkinter
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46881003
has body: I have the same problem as many other questions, but found no solution working yet. This is on Windows 10 64 bit, Python 3.6 32 bit. I have tried uninstalling several times, 64 bit Python, various combinations of paths and variables in the setup file. I do find it confusing that the traceback from the exe file refers to filepaths in my Python folder, not the build folder where the executable resides. I would have thought that this exe should now be "innocent" of the existence of the python folder? Output from exe file Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run module.run() File "C:\Program Files (x86)\Python36-32\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run exec(code, m.__dict__) File "main3.py", line 2, in &lt;module&gt; File "C:\Program Files (x86)\Python36-32\lib\site-packages\appJar\__init__.py", line 2, in &lt;module&gt; from appJar.appjar import gui File "C:\Program Files (x86)\Python36-32\lib\site-packages\appJar\appjar.py", line 23, in &lt;module&gt; from tkinter import * File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 36, in &lt;module&gt; import _tkinter # If this fails your Python may not be configured for Tk ImportError: DLL load failed: The specified module could not be found. My setup file for cx_freeze - from cx_Freeze import setup, Executable import os os.environ['TCL_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tk8.6' build_exe_options={ "includes": [], "packages": ["os","tkinter"], "include_files" : [r'C:\Program Files (x86)\Python36-32\DLLs\tcl86t.dll', r'C:\Program Files (x86)\Python36-32\DLLs\tk86t.dll'] } setup(name = "main" , version = "0.1" , description = "" , options={"build.exe":build_exe_options}, executables = [Executable("main3.py", base=None, targetName="hexml.exe")])
type: Question
score: 2
has comment: http://stackoverflow.com/comment/81032736
downvote count: 0

http://stackoverflow.com/comment/80473220
type: QuestionComment
type: Comment
has text: You might want to get the labels from the classifier, in the order the classifier learned them.
score: 0
comment on: http://stackoverflow.com/q/46763832

http://stackoverflow.com/a/46861662
has body: json.loads() only accepts valid JSON data. You don't have valid JSON. You can't put Python object names in there. The object hook only applies to {....} JSON objects. The term object here does not extend to the Python definition. If you want to put datetime values into JSON, you'll need to come up with a different scheme. JSON does not have any native support; usually the specific API just documents what values are supposed to be datetime values, and when reading the JSON data you handle dates on the application level, not at the decoding level. If you found "datetime.datetime(2017, 1, 1, 0, 0, 0, 0)" strings in a JSON document, then as far as the JSON parser is concerned those are just strings. The contents of the string are not processed, that's up to the application layer to do. If these strings are values inside a JSON object ({"key": "datetime.datetime(...)", ...}), then you could use the object_hook callback to inspect all such values and replace them with datetime instances: import datetime, re datetime_pat = re.compile(r'datetime\.datetime\([\d, ]+\)') def convert_datetime_values(d): for key, value in d.items(): if datetime.pat.match(value): d[key] = eval(value) return d You can't do the same for JSON arrays however.
accepted answer of: http://stackoverflow.com/q/46861647
answers question: http://stackoverflow.com/q/46861647
has comment: http://stackoverflow.com/comment/80671311
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/80670827
score: 2
has comment: http://stackoverflow.com/comment/80670816
has comment: http://stackoverflow.com/comment/80670914
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80482770
type: Comment
score: 0
type: AnswerComment
has text: Yes -- you can use precise dates, like "2017-10-16T11:00" (format dependent on your mapping, but that's the default), or if you want relative, "now/d+11h". See the [date math docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math).
comment on: http://stackoverflow.com/a/46768310

http://stackoverflow.com/comment/80610231
score: 0
type: Comment
has text: Thank you, this is even cleaner!
comment on: http://stackoverflow.com/a/46831399
type: AnswerComment

http://stackoverflow.com/comment/80486165
score: 0
type: Comment
type: QuestionComment
has text: Try adding a debug print at the beginning of your python script, to show what arguments it gets.
comment on: http://stackoverflow.com/q/46769620

http://stackoverflow.com/comment/80531858
has text: First indent your code properly
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46792586
score: 1

django-rest-framework
tags question: http://stackoverflow.com/q/46826501
tags question: http://stackoverflow.com/q/46842938
tags question: http://stackoverflow.com/q/46769751
tags question: http://stackoverflow.com/q/46798057
tags question: http://stackoverflow.com/q/46874087
type: Tag
tags question: http://stackoverflow.com/q/46885308
tags question: http://stackoverflow.com/q/46847900
tags question: http://stackoverflow.com/q/46873978
tags question: http://stackoverflow.com/q/46798413
tags question: http://stackoverflow.com/q/46903796
tags question: http://stackoverflow.com/q/46752123
tags question: http://stackoverflow.com/q/46846437
tags question: http://stackoverflow.com/q/46849343
tags question: http://stackoverflow.com/q/46786650
tags question: http://stackoverflow.com/q/46874388
tags question: http://stackoverflow.com/q/46767394
tags question: http://stackoverflow.com/q/46847165
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/46821171
tags question: http://stackoverflow.com/q/46819746
tags question: http://stackoverflow.com/q/46813883
tags question: http://stackoverflow.com/q/46887904
tags question: http://stackoverflow.com/q/46783667
tags question: http://stackoverflow.com/q/46887569
tags question: http://stackoverflow.com/q/46805662
tags question: http://stackoverflow.com/q/46755042
tags question: http://stackoverflow.com/q/46879688
tags question: http://stackoverflow.com/q/46770630
tags question: http://stackoverflow.com/q/46861252
tags question: http://stackoverflow.com/q/46860183

http://stackoverflow.com/comment/80730421
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46875336
has text: no, the data is different, I want to plot the two lines together in the same plot.

http://stackoverflow.com/a/46772499
type: Answer
answers question: http://stackoverflow.com/q/46770325
accepted answer of: http://stackoverflow.com/q/46770325
has body: You have a couple options. You can install all of the required packages and then create an image of the server with your packages installed. You can then use that AMI when you launch any new instances and those packages will be available. You can also manage it in code, by using .ebextensions. You can use this to install any packages you need when the server boots up. http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html An example of how this can work is where I replace apache with nginx for a beanstalk application: https://github.com/ricktbaker/beanstalk-nginx-php-fpm Or you can create a custom platform. This might be a little overkill for you needs, but it is an option: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/80538087
type: QuestionComment
comment on: http://stackoverflow.com/q/46795627
score: 0
has text: alrighty, then thanks for the help and i'll just accept it's (unfortunately) impossible
type: Comment

http://stackoverflow.com/comment/80554973
comment on: http://stackoverflow.com/q/46803788
has text: BTW, you aren't making any instances of that `C` class. Python classes work a little differently to C++.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/99648118
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46775606
has text: Never thought I'd have to use this 'till today, thanks for clearing it up!
type: AnswerComment

http://stackoverflow.com/comment/80541293
comment on: http://stackoverflow.com/q/46797267
has text: If it's not a valid CSV file, you'll need to write your own code to parse it, you can't use a standard library.
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/46875697
has answer: http://stackoverflow.com/a/46875769
tagged with: flask
has comment: http://stackoverflow.com/comment/80698442
possible better answer: http://stackoverflow.com/a/46875769
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/46875756
favorite count: 0
has title: Pass parameters between flask @app.route('/page')
accepted answer: http://stackoverflow.com/a/46875756
tagged with: python
tagged with: parameter-passing
upvote count: 6
type: AnsweredQuestion
has body: I am trying to pass the value i get from Random() to Help() but it returns as AttributeError: 'NoneType' object has no attribute 'app'. from flask import Flask, request, render_template from random import randint @app.route('/help') def Help(Random): PassingRandom = Random return render_template("help.html", PassingRandom=PassingRandom) def Random(): Value = randint(0,100) return Value MyValue = Random() if __name__ == "__main__": Help(MyValue) app.run(debug=True) Is their a way within flask to pass in the parameter without returning the error, preferably without using globals.
score: 6
type: Question

http://stackoverflow.com/comment/80749901
has text: @Zero So friggin obvious... unstack/stack. You could create an answer... and I can mark it.
comment on: http://stackoverflow.com/q/46901513
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80730490
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46889644
has text: An interesting point -- to make sure that your manual migration accounts for ALL of your model-changes, after creating and saving your custom migration file, run `python manage.py makemigrations`. That will make a migration with all the changes that your custom migration did not account for. Good for bookkeeping and double-checking.

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/46903492
tag name: kivy-language
tags question: http://stackoverflow.com/q/46856516

http://stackoverflow.com/comment/80452692
comment on: http://stackoverflow.com/a/46753470
has text: thank you sir, but i got an other erorr: AttributeError: '_csv.writer' object has no attribute 'write'
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46815555
upvote count: 7
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81795229
type: Question
has title: Stop Pandas ExcelWriter() creating extra column
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46815665
has comment: http://stackoverflow.com/comment/80578439
tagged with: pandas
has body: How to I stop Pandas to_excel() function creating an extra column with the indexes in? If I run the following: import pandas as pd df = pd.read_excel('in.xlsx') #do some stuff to the dataframe writer = pd.ExcelWriter('out.xlsx') df.to_excel(writer) writer.save() .. the newly created file (out.xlsx) has an additional column which I don't want. I just want the columns identified in df.columns outputting without the additional indexes column. This is a small step in a larger process so i can't just manually delete the column. Also, i don't want to use any other Excel writing packages such as XlsxWriter Many thanks!
tagged with: python
accepted answer: http://stackoverflow.com/a/46815665
has comment: http://stackoverflow.com/comment/94480692
score: 6

http://stackoverflow.com/q/46768822
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I'm a Python beginner. I'm trying to return a list from a list of lists into a new list of lists. I've looked extensively at similar questions, but cannot find the answer. l1 = [['a','b','c','d'],['b','c','d','f'],['b','c','a','f']] I would like to loop over l1 to check if 'a' is in a list, and when true then add that list to a new list of lists l2. I got this far (not very far): l2 = [] for selector in l1: if 'a' in selector: l2.append(*#I don't know this part*) What i would like is this result: l2 = [['a','b','c','d'],['b','c','a','f']] Any help would be much appreciated.
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/46768853
has comment: http://stackoverflow.com/comment/80482844
type: Question
score: -2
has title: Python return list out of list of lists when variable in list is found
tagged with: for-loop
upvote count: 0
accepted answer: http://stackoverflow.com/a/46768853

http://stackoverflow.com/a/46781643
type: Answer
answers question: http://stackoverflow.com/q/46781563
has body: I have tried to visit the url you given, you can add header to your request to avoid this problem (the minimum information you need to provide is User-Agent, I think you can use more header information as you can): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} response = requests.get(url, headers=headers) The stats.nba.com website need your 'User-Agent' header information. You can get your request header information from Network tab in the browser. Take chrome as example, when you press F12, and visit url you given, you can find the relative request information, the most useful information is request headers.
accepted answer of: http://stackoverflow.com/q/46781563
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/80548720
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80536749

http://stackoverflow.com/comment/80495120
comment on: http://stackoverflow.com/q/46774127
score: 0
type: QuestionComment
has text: a is a constant numpy array of size 100000000, I'm creating a tensorflow variable b and set it equal to a, and call variables_initializer() to initialize b. a itself is 762 MB, so is b, what I don't understand is how TF ends up using 4GB memory.
type: Comment

http://stackoverflow.com/a/46809084
type: Answer
has body: The both function are shown below. The set function works fine and I catch the exception but in the get function I crashed. def get_uid_light_state(): log("get_uid_light_state") try: state_string = subprocess.check_output("cat /sys/class/gpio/gpio482/value", shell=True) except subprocess.CalledProcessError: log("Get state failed.") return "integer", "0" if state_string == "1\n": return "integer", "2" elif state_string == "0\n": return "integer", "1" def set_uid_light_state(snmptype, state): if snmptype != "integer": return "wrong-type" if state == "1": cmd_set_state = "echo 0 &gt; /sys/class/gpio/gpio482/value" elif state == "2": cmd_set_state = "echo 1 &gt; /sys/class/gpio/gpio482/value" else: log("Invalid value for set uid light state") return "wrong-value" try: subprocess.check_output(cmd_set_state, shell=True) except subprocess.CalledProcessError: log("Set state failed.") return "not-writable" return "DONE"
answers question: http://stackoverflow.com/q/46807093
score: 0

http://stackoverflow.com/comment/80568264
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46810380
score: 0
has text: Meaning it still blocks? Not sure how unless all resources on the machine are consumed by `get_rates()` because they run in completely different process space. But you can't have the join() in their, or it will not work in parallel.

http://stackoverflow.com/comment/80733302
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46892631
has text: Why are you connecting to the serial on every loop?

http://stackoverflow.com/q/46899011
answer count: 3
has answer: http://stackoverflow.com/a/46899181
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46899156
has answer: http://stackoverflow.com/a/46899092
has body: here is my current code: # Imports random import random def game(): """This holds the function for the game""" # Sets score to 0 intially score = 0 wrong = 0 # Questions questions = [{"question": "What is the price of a motorcycle?", "answers": ["$1000", "$5000", "$10000", "$15000"], "correct": "2"}, {"question": "How much is this toaster?", "answers": ["$2", "$5", "$7"], "correct": "2"}, {"question": "What is the price of a dog?", "answers": ["$1", "$5000", "$100", "$70"], "correct": "3"}, {"question": "How much is this electric pooper scooper?", "answers": ["$200000", "$90", "$72.99"], "correct": "3"}, {"question": "What is the price of apple sauce?", "answers": ["$.50", "$5", "$3", "$1"], "correct": "4"}, {"question": "is this lamborghini worth $100,000?", "answers": ["True", "False"], "correct": "1"}, {"question": "What is the price of a lifesize manaquin of batman?", "answers": ["$2,530", "$500", "$100", "$45"], "correct": "1"}, {"question": "How much is this 1 night vacation in idaho?", "answers": ["$400", "$1000", "$95"], "correct": "3"}, {"question": "What is the price of a honda Accord?", "answers": ["$1000", "$9500", "$6000", "$18000"], "correct": "4"}, {"question": "is this gold plated microwave worth over $2,000?", "answers": ["True", "False"], "correct": "1"}] # Shuffles questions random.shuffle(questions) print("Welcome to the price is right!") # loop for questions for question in questions: print(question["question"]) for i, choice in enumerate(question["answers"]): print(str(i + 1) + ". " + choice) answer = input("Choose an answer: ") if answer == question["correct"]: print("That is correct!") score = score + 1 else: print("That answer is incorrect!") wrong = wrong + 1 # Score + Thank you message print() print() print("Your total score is:", score, "right, and", wrong, "wrong.") print("Thanks for playing the price is right!") print() main() def main(): """Calls all options""" while True: print("Welcome to the Price is Right! I'm your host, Python! Wh…
has comment: http://stackoverflow.com/comment/80746519
type: Question
has title: RePromting User After Invalid Input
score: 0

http://stackoverflow.com/q/46751395
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80452889
answer count: 0
has comment: http://stackoverflow.com/comment/80453308
type: UnansweredQuestion
has title: Pandas: How do I access other elements in a row if I only know an element in a row of a DataFrame
tagged with: indexing
has body: For example in the data frame: Gyroscope 448083 -0.05965481 -0.26418558 -0.017044231 Gyroscope 448338 -0.033023197 -0.18002969 -0.011717909 Gyroscope 448340 -0.052197956 -0.17470336 -0.049002163 Gyroscope 448341 -0.03834952 -0.16937704 -0.034088463 I know elements in the second column, but I want to pull out the last three elements. Interval is a tuple where I know the timestamp to start and end at, but those values may not be in the data frame. If my interval[0] variable was 448075 and my interval[1] variable was 448345, how do I access all the elements from the 3rd, 4th, and 5th columns of the rows with column 1 values between interval[0] and interval[1]? I try to find the closest values to interval[0] and interval[1] in the actual DataFrame. start = np.abs(merge.iloc[:, 1] - i[0]).argmin() end = np.abs(merge.iloc[:, 1] - i[1]).argmin() for j in range(start, end): gyro.append((merge.iloc[:, j][2], merge.iloc[:, j][3], merge.iloc[:, j][4])) if merge.iloc[:, j][0] == 'Gyroscope' \ else acc.append((merge.iloc[:, j][2], merge.iloc[:, j][3], merge.iloc[:, j][4])) Then, using the range of numbers in the interval, I attempt to pull out the last three entries in each row. gyro and acc are the lists I'm appending the last three entries in the relevant rows to. merge.head() returns Gyroscope 448083 -0.05965481 -0.26418558 -0.017044231 0 Gyroscope 448338.0 -0.033023 -0.180030 -0.011718 1 LinearAcceleration 448339.0 -0.048183 -0.427365 -0.019752 2 Gyroscope 448340.0 -0.052198 -0.174703 -0.049002 3 LinearAcceleration 448340.0 0.168791 -0.166547 -0.136918 4 Gyroscope 448341.0 -0.038350 -0.169377 -0.034088 Basically, I want to index based on the range of second column values and iterate through that.
type: Question
score: 0

http://stackoverflow.com/a/46854110
has comment: http://stackoverflow.com/comment/80661681
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89986195
has body: Not sure if this is relevant or not but are you getting the UserProfile correctly in your def get_full_name(self): Here you have: a=UserProfile.objects.get(email_id=self.id) however I don't see email_id specified in your Class UserProfile. You have email specified and the class is sub-classed from models.Model which, by default, I would expect to only have an id column not email_id unless you have changed it. Just a thought.
answers question: http://stackoverflow.com/q/46853692

http://stackoverflow.com/a/46805392
downvote count: 0
score: 1
has body: It is possible to see the source code of LinearRegression but not directly from the command line as you are trying to do. LinearRegression is a class and its code is located in base.py (see below the link for this). The source code of a function(in general) can be found in the sklearn documentation website/github. For the LinearRegression the documentation is here: http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html. The source code is here starting from line 405: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/linear_model/base.py#L405. Finally, you may also find the source code in: scikit-learn/sklearn/linear_model/base.py Hope this helps
has comment: http://stackoverflow.com/comment/80593952
type: Answer
accepted answer of: http://stackoverflow.com/q/46804912
answers question: http://stackoverflow.com/q/46804912
upvote count: 1
has comment: http://stackoverflow.com/comment/80593286
type: AcceptedAnswer

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/46816957
tags question: http://stackoverflow.com/q/46848209
tags question: http://stackoverflow.com/q/46854408
type: Tag
tags question: http://stackoverflow.com/q/46770939
tags question: http://stackoverflow.com/q/46887098
tags question: http://stackoverflow.com/q/46796985
tags question: http://stackoverflow.com/q/46825760
tags question: http://stackoverflow.com/q/46903654
tags question: http://stackoverflow.com/q/46863079
tags question: http://stackoverflow.com/q/46807680
tags question: http://stackoverflow.com/q/46808533
tags question: http://stackoverflow.com/q/46820888
tag name: csv
tags question: http://stackoverflow.com/q/46780577
tags question: http://stackoverflow.com/q/46902801
tags question: http://stackoverflow.com/q/46806715
tags question: http://stackoverflow.com/q/46875194
tags question: http://stackoverflow.com/q/46785199
tags question: http://stackoverflow.com/q/46779930
tags question: http://stackoverflow.com/q/46846329
tags question: http://stackoverflow.com/q/46854137
tags question: http://stackoverflow.com/q/46880644
tags question: http://stackoverflow.com/q/46821341
tags question: http://stackoverflow.com/q/46855313
tags question: http://stackoverflow.com/q/46862549
tags question: http://stackoverflow.com/q/46845477
tags question: http://stackoverflow.com/q/46776588
tags question: http://stackoverflow.com/q/46870929
tags question: http://stackoverflow.com/q/46761053
tags question: http://stackoverflow.com/q/46825978
tags question: http://stackoverflow.com/q/46867009
tags question: http://stackoverflow.com/q/46753628
tags question: http://stackoverflow.com/q/46797412
tags question: http://stackoverflow.com/q/46777600
tags question: http://stackoverflow.com/q/46859470
tags question: http://stackoverflow.com/q/46819090
tags question: http://stackoverflow.com/q/46855867
tags question: http://stackoverflow.com/q/46787428
tags question: http://stackoverflow.com/q/46858780
tags question: http://stackoverflow.com/q/46762939
tags question: http://stackoverflow.com/q/46790718
tags question: http://stackoverflow.com/q/46761691
tags question: http://stackoverflow.com/q/46880968
tags question: http://stackoverflow.com/q/46858848
tags question: http://stackoverflow.com/q/46808538
tags question: http://stackoverflow.com/q/46752152
tags question: http://stackoverflow.com/q/46873637
tags question: http://stackoverflow.com/q/46760039
tags question: http://stackoverflow.com/q/46774656
tags question: http://stackoverflow.com/q/46753479
tags question: http://stackoverflow.com/q/46855183
tags question: http://stackoverflow.com/q/46778249
tags question: http://stackoverflow.com/q/46758865
tags question: http://stackoverflow.com/q/46789023
tags question: http://stackoverflow.com/q/46778899
tags question: http://stackoverflow.com/q/46856979
tags question: http://stackoverflow.com/q/46869275
tags question: http://stackoverflow.com/q/46752943
tags question: http://stackoverflow.com/q/46760188
tags question: http://stackoverflow.com/q/46863537
tags question: http://stackoverflow.com/q/46756907
tags question: http://stackoverflow.com/q/46870844
tags question: http://stackoverflow.com/q/46850687
tags question: http://stackoverflow.com/q/46867675
tags question: http://stackoverflow.com/q/46868555
tags question: http://stackoverflow.com/q/46827087
tags question: http://stackoverflow.com/q/46802152
tags question: http://stackoverflow.com/q/46869323
tags question: http://stackoverflow.com/q/46784832
tags question: http://stackoverflow.com/q/46872643
tags question: http://stackoverflow.com/q/46811978
tags question: http://stackoverflow.com/q/46888995
tags question: http://stackoverflow.com/q/46870841
tags question: http://stackoverflow.com/q/46775963
tags question: http://stackoverflow.com/q/46810479
tags question: http://stackoverflow.com/q/46856819
tags question: http://stackoverflow.com/q/46811986
tags question: http://stackoverflow.com/q/46787806
tags question: http://stackoverflow.com/q/46829489

http://stackoverflow.com/q/46892839
downvote count: 0
possible better answer: http://stackoverflow.com/a/46892982
has answer: http://stackoverflow.com/a/46893160
accepted answer: http://stackoverflow.com/a/46893160
has answer: http://stackoverflow.com/a/54433793
type: Question
has comment: http://stackoverflow.com/comment/80732914
score: 1
has comment: http://stackoverflow.com/comment/80732937
answer count: 3
upvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/46892982
tagged with: python
has body: Let's suppose that this is my data. frame.number frame.len frame.cap_len Packets_Type 1 100 100 ICMP_tt 2 64 64 UDP 3 100 100 ICMP_tt 4 87 64 ICMP_nn 5 100 100 ICMP_tt 6 87 64 ICMP_nn 7 100 100 ICMP_tt 8 87 64 ICMP_nn 9 87 64 ICMP_nn I put my data in a csv file, I want to extract rows where Packets_Type is equal to ICMP_tt import csv f = open("file.csv", "rb") reader = csv.DictReader(f, delimiter=',') writer = open("newfile.csv",'wb') writer = csv.writer(writer, delimiter=',') for row in reader: if row['Packets_Type'] == 'ICMP_tt': writer.writerow(row) By executing those lines of code, I found this error: writer.writerow(row) _csv.Error: sequence expected I would be very grateful if you could help me please.
type: AnsweredQuestion
has title: How to copy specific rows from csv file to another csv file based on specific column?

http://stackoverflow.com/comment/80532988
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/46793033
has text: This really feels like an XY Problem. And IMHO question is still unclear.

http://stackoverflow.com/q/46874472
answer count: 1
has comment: http://stackoverflow.com/comment/80697687
has comment: http://stackoverflow.com/comment/80697864
has comment: http://stackoverflow.com/comment/80698061
has comment: http://stackoverflow.com/comment/80696048
has comment: http://stackoverflow.com/comment/80696311
has comment: http://stackoverflow.com/comment/80695931
has comment: http://stackoverflow.com/comment/80696339
has comment: http://stackoverflow.com/comment/80697733
has comment: http://stackoverflow.com/comment/80697778
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80696003
has body: I got an error, MultiValueDictKeyError at /accounts/upload_save/ "'image'" . I am making file upload system.It is that if i select file and put "SEND" button,selected image is sent to model.But now,when i select no image and put "SEND" button,the error happens.I wanna make a system that if i select no image and put "SEND" button, You should select at least one photo message is shown. I wrote in photo.html {% if form.errors %} You should select at least one photo {% endif %} {% csrf_token %} File Select1 File Select2 File Select3 I wrote in views.py @login_required @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user = request.user data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/photo.html', {'form': form}) in urls.py urlpatterns = [ url(r'^upload_save/$', views.upload_save, name='upload_save'), ] in forms.py class UserImageForm(forms.ModelForm): class Meta: model = ImageAndUser fields = ('image',) in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) date = models.IntegerField(max_length=100,null=True) I really cannot understand why this error happens because I wrote if-else statement and I worte print(form.errors) in else statement .What should I do to fix this?How can I write it ?
type: Question
has comment: http://stackoverflow.com/comment/80697506
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/80697446
has comment: http://stackoverflow.com/comment/80697182
has comment: http://stackoverflow.com/comment/80696505
has comment: http://stackoverflow.com/comment/80696671
has title: MultiValueDictKeyError at /accounts/upload_save/
score: 0
has comment: http://stackoverflow.com/comment/80696959
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46875598

http://stackoverflow.com/comment/80544534
score: 0
comment on: http://stackoverflow.com/a/46798828
type: Comment
has text: for the append , we do not need assign it back right ?`nod_intervals.append((row['start'], row['end']))` enough right ?
type: AnswerComment

http://stackoverflow.com/comment/80877934
has text: It simply won't work. You cannot initialize CUDA in a parent process and expect it to work properly in a child process spawned from that parent process. Study [this sample code](http://docs.nvidia.com/cuda/cuda-samples/index.html#simpleipc) carefully. I'm reasonably confident that it would not be necessary to initialize CUDA in your parent process, with some restructuring of your code. The sample code demonstrates one possible approach.
comment on: http://stackoverflow.com/q/46904699
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/80735169
type: QuestionComment
has text: @mohammed qudah i have multiple links in one string so i can not simply return
score: 0
comment on: http://stackoverflow.com/q/46893770
type: Comment

http://stackoverflow.com/q/46768337
tagged with: set-difference
linked to: http://stackoverflow.com/q/9884132
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: set
has title: Difference operations in dictionary keys in python
has answer: http://stackoverflow.com/a/46768351
type: Question
has body: I am running some Python3 code using the IDLE and I would like to understand why for a = {'a':1,'b':2} both: a.keys()-'a' (not even sure why this one works) and a.keys()-{'a'} produce the same result. Weirdly enough, the second option seems produce different outputs once the operation is performed inside a function (and call from the IDLE) or directly run from the IDLE...
accepted answer: http://stackoverflow.com/a/46768606
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/46768606
possible better answer: http://stackoverflow.com/a/46768351
favorite count: 0

http://stackoverflow.com/q/46890864
answer count: 1
has body: I note that python3 says that: 1.1+2.2 is 3.3000000000000003. 2.2+4.4 is 6.6000000000000005. 1.1+2.3 is 3.4. 2.2+4.3 is 6.5. And so on. I realise that floating point arithmetic is not perfectly accurate, as per Is floating point math broken? so that, for instance, that 1.1 may not be perfectly represented inside the float type. However, there seems to be something about a query of the form x+2x that provokes an exceptional inaccuracy. Is there a simple intuition as to why?
has title: Floating point arithmetic and equality testing in python 3
has answer: http://stackoverflow.com/a/46890926
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/80763004
score: 2
duplicate of: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/80762928
downvote count: 0
tagged with: floating-accuracy
favorite count: 0
type: Question
tagged with: python
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/80762798

http://stackoverflow.com/q/46879508
type: Question
has comment: http://stackoverflow.com/comment/80706258
has comment: http://stackoverflow.com/comment/80706278
has comment: http://stackoverflow.com/comment/80706264
has body: Consider the following code: foo=None def bar(): print(foo, flush=True) # UnboundLocalError print('MARK') del foo print(foo) bar() #print(foo) Basically I have a function that calls del in it. However, when I run the program, I get UnboundLocalError for that 'foo' referenced before assignment. If I comment out the del line, the exception is gone. I suppose the del should be called exactly on the line it is on, so that the variable is invalidated only after that. But it doesn't seem to be the case. Is this expected behavior? (Specifically, I'm using Python 3.6.2)
has comment: http://stackoverflow.com/comment/80706279
linked to: http://stackoverflow.com/q/370357
has comment: http://stackoverflow.com/comment/80706236
upvote count: 1
has comment: http://stackoverflow.com/comment/80706296
duplicate of: http://stackoverflow.com/q/370357
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80706313
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
has title: del in Python functions deleting variable before the line?

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/46794860

http://stackoverflow.com/a/46905382
upvote count: 3
has comment: http://stackoverflow.com/comment/80757669
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46904839
type: Answer
accepted answer of: http://stackoverflow.com/q/46904839
has body: To play a sound continuously with winsound, you can combine the SND_FILENAME, SND_LOOP, SND_ASYNC constants with a bitwise OR |: SND_FILENAME|SND_LOOP|SND_ASYNC. And to stop the sound, you can just pass None as the first argument to PlaySound. import tkinter as tk from winsound import PlaySound, SND_FILENAME, SND_LOOP, SND_ASYNC class App: def __init__(self, master): frame = tk.Frame(master) frame.pack() self.button = tk.Button(frame, text='play', command=self.play_sound) self.button.pack(side=tk.LEFT) self.button2 = tk.Button(frame, text='stop', command=self.stop_sound) self.button2.pack(side=tk.LEFT) def play_sound(self): PlaySound('Sound.wav', SND_FILENAME|SND_LOOP|SND_ASYNC) def stop_sound(self): PlaySound(None, SND_FILENAME) root = tk.Tk() app = App(root) root.mainloop()
has comment: http://stackoverflow.com/comment/80757582
score: 3

http://stackoverflow.com/q/46798641
has answer: http://stackoverflow.com/a/46799212
favorite count: 0
has answer: http://stackoverflow.com/a/46798957
linked to: http://stackoverflow.com/q/41117733
has comment: http://stackoverflow.com/comment/80544203
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/46798882
answer count: 4
has title: How to only allow digits, letters, and certain characters in a string in Python?
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/80544918
has comment: http://stackoverflow.com/comment/80544424
has answer: http://stackoverflow.com/a/46798780
has comment: http://stackoverflow.com/comment/80544420
accepted answer: http://stackoverflow.com/a/46798780
type: Question
score: 1
has comment: http://stackoverflow.com/comment/80544396
has answer: http://stackoverflow.com/a/46798882
has comment: http://stackoverflow.com/comment/80544481
has body: I want to make a password checker but how do I make it so I can write an error if there are characters other than digits, upper/lowercase and (,),$,%,_/. What I have so far: import sys import re import string import random password = input("Enter Password: ") length = len(password) if length &lt; 8: print("\nPasswords must be between 8-24 characters\n\n") elif length &gt; 24: print ("\nPasswords must be between 8-24 characters\n\n") elif not re.match('[a-z]',password): print ('error')
has comment: http://stackoverflow.com/comment/80544449
upvote count: 3

http://stackoverflow.com/comment/80517717
score: 2
comment on: http://stackoverflow.com/q/46785713
has text: Please don't post your code as image. Edit your question and include relevant parts of code as text. Read more about [mcve](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80486962
score: 1
comment on: http://stackoverflow.com/q/46770574
has text: `itertools.product` evaluates its arguments eagerly: [Does itertools.product evaluate its arguments lazily?](https://stackoverflow.com/questions/45586863/does-itertools-product-lazy-evaluate-its-arguments). The size of the pool gets larger and larger as `n` increases, increasing memory use and time to compute each product.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77800240
score: 0
has body: You can use moviepy library to do that. Behind the scenes, it uses ffmpeg to merge audio and video. import moviepy.editor as mp video_path = 'Path to video file' audio_path = 'Path to audio file' output_path = 'Path to output video+audio file' video = mp.VideoFileClip(video_path) audio = mp.AudioFileClip(audio_path) video = video.set_audio(audio) video.write_videofile(output_path)
type: Answer
answers question: http://stackoverflow.com/q/46864915

http://stackoverflow.com/a/79153563
score: 0
answers question: http://stackoverflow.com/q/46786211
has body: Concatenate the whole series into one string, split it to words, and use Counter from collections: from collections import Counter Counter(df['Firm_Name'].str.cat(sep='\n').split()) Output: Counter({'Society': 3, 'Ltd': 2, 'R.X.': 1, 'Yah': 1, '&': 1, 'Co': 1, 'Big': 1, 'Building': 1, 'St': 1, "James's": 1, 'The': 1, 'Kensington': 1, 'MMV': 1, 'Oil': 1, 'Associates': 1}) It's twice as fast as the accepted answer. Optionally call .most_common() to get a sorted list of tuples [(w1, c1), (w2, c2), ...]
type: Answer

http://stackoverflow.com/a/46793308
answers question: http://stackoverflow.com/q/46792634
type: Answer
score: 1
upvote count: 1
has body: One way would be to drop duplicate values before making the cumulative count: trans_nr = (df .drop_duplicates(subset=['Customer_ID', 'date']) .set_index(['Customer_ID', 'date']) .groupby(level='Customer_ID') .cumcount() + 1 ) df.set_index(['Customer_ID', 'date'], inplace=True) df['trans_nr'] = trans_nr df.reset_index(inplace=True) To get the transaction number, you first remove rows with duplicate Customer_ID and date values. Then you set their index using Customer_ID and date (for merging later) and perform your groupby and cumcount. This produces a series whose values are the cumulative count for each Customer_ID and date. You also set the index for the original dataframe (again to allow for merging). Then you simply assign the trans_nr series to a column in df. The indices take care of the merging logic.
downvote count: 0

http://stackoverflow.com/comment/94490166
type: Comment
comment on: http://stackoverflow.com/q/46774707
type: QuestionComment
has text: Did you find a solution to this problem?
score: 0

http://stackoverflow.com/comment/80614663
has text: @WinterZ Check out the NaN solutions at the end. Use those.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46757690

http://stackoverflow.com/comment/80600034
has text: I added new information. Sorry, I wasn't sure what was too much and too little information. This will be a learning experience for me.
comment on: http://stackoverflow.com/q/46825434
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46903349
has title: Why is plt.savefig not saving any file at all?
has comment: http://stackoverflow.com/comment/80753344
favorite count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/80753314
tagged with: python
has body: I seem to be having a strange situation wherein plt.savefig seems not to save any file at all. The code is of the form of df.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig(label + "_" + "Plot_Type_Name.png", bbox_inches="tight") plt.close("all") and it is being run from a command-line and/or from PyCharm. It's not apparent to me why it's failing. Can anyone help?
has answer: http://stackoverflow.com/a/73941237
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/46905659
answer count: 2
score: 0

http://stackoverflow.com/comment/80606645
comment on: http://stackoverflow.com/q/46829568
type: Comment
type: QuestionComment
score: 2
has text: Give more code about how you have processed. Can't get the reason with data's structure alone

http://stackoverflow.com/a/46863136
answers question: http://stackoverflow.com/q/46863081
score: 0
type: Answer
has body: You're better off using the csv module since your file syntax is simple CSV. Then you can loop through the rows (each row will be an array of values). import csv def parse_csv_file(csv_file, operation, value, index): with open(csv_file, newline='') as file: reader = csv.reader(file, delimiter=',', quotechar='|') return operation(reader, value, index) def find_first_row(csv_reader, value, index): for row in csv_reader: if row[index] == value: return row return None def main(): query = input('Enter a name: ') result = parse_csv_file('file.csv', find_first_row, query, 0) if result: print(result) else: print('Nothing found!') main()
has comment: http://stackoverflow.com/comment/80673701
has comment: http://stackoverflow.com/comment/80674203

music21
type: Tag
tags question: http://stackoverflow.com/q/46893125
tag name: music21

http://stackoverflow.com/q/46852659
answer count: 1
downvote count: 1
tagged with: python
favorite count: 0
upvote count: 5
type: UnansweredQuestion
type: Question
score: 4
has title: Why does importing symbols from a module also define the module symbol?
has answer: http://stackoverflow.com/a/46884685
has body: Given a trivial Python package with an __init__.py: $ ls -R foo/ foo/: __init__.py bar.py $ cat foo/bar.py def do_stuff(): pass $ cat foo/__init__.py from .bar import * I'm surprised that foo.bar is defined: &gt;&gt;&gt; import foo &gt;&gt;&gt; foo.bar &lt;module 'foo.bar' from 'foo/bar.pyc'&gt; My understanding of from x import * is that it doesn't define x in the current scope. For example: &gt;&gt;&gt; from abc import * &gt;&gt;&gt; abc Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'abc' is not defined Why is foo.bar defined in my first example, even though I don't have import bar inside __init__.py?

http://stackoverflow.com/q/46788960
has answer: http://stackoverflow.com/a/46789354
accepted answer: http://stackoverflow.com/a/46789354
has comment: http://stackoverflow.com/comment/80524169
answer count: 1
tagged with: calculator
has comment: http://stackoverflow.com/comment/80524839
score: 0
has comment: http://stackoverflow.com/comment/80524787
tagged with: python
has comment: http://stackoverflow.com/comment/80524860
tagged with: loops
has body: Below is the code I have so far and the errors I am getting. I have tried playing but obviously I'm not understanding exactly how the loop should work I am trying to loop so that wrong inputs i.e. alphabetical and under £1000 forces an error and re-input question. I have most of it working but it loops to initial question not error question on alphabetical input but gives error message then continues when using numerical but under £1000. print ("Welcome to Trustees Investment Bank Compoud Interest Calculator") #Title print ("Interest is calculated at 3.15% per annum") while True: try: deposit2 = float(input("\nEnter initial deposit above £1000? ")) # Initial deposit amount rate = 0.0315 # interest rate if deposit2&lt;1000: deposit2 = float(input("\nEnter initial deposit above £1000? ")) #loop except ValueError: continue else: break for year in range(1,9): amount = deposit2 * (1.0 + rate) ** year print ("%4d%21.2f" % (year, amount)) This is my output Welcome to Trustees Investment Bank Compound Interest Calculator Interest is calculated at 3.15% per annum Enter initial deposit above £1000? jj Enter initial deposit above £1000? hgh Enter initial deposit above £1000? 500 Not valid amount, please enter deposit above £1000 500 1 515.75 2 532.00 3 548.75 4 566.04 5 583.87 6 602.26 7 621.23 8 640.80
type: Question
type: AnsweredQuestion
has title: Compound interest calculator loops

http://stackoverflow.com/q/46861059
has comment: http://stackoverflow.com/comment/80669616
type: Question
upvote count: 2
has title: Give time to a bomb before to explode on pygame
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/30720665
tagged with: pygame
has comment: http://stackoverflow.com/comment/80670130
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46863295
accepted answer: http://stackoverflow.com/a/46863295
has body: I am doing a kind of bomberman, and I am trying to do that the bomb explodes after a while. Sorry if this question already exists. I have been looking for any answer but I didnt find. This should be like: 1. I put a bomb somewhere 2. The bomb waits 5 seconds 3. The bomb explodes I dont know how to give the 5 seconds before to explode. class bomb(object): def __init__(self, aposX, aposY, bombRange = 5): self.posX = aposX self.posY = aposY self.bombRange = bombRange self.timeToExplode = 5000 pygame.draw.circle(ventana,(200,0,0),(self.posX,self.posY),20) def update(self): pygame.draw.circle(ventana,(200,0,0),(self.posX,self.posY),20) #Here should wait 5 seconds and then call the explde method self.explode() def explode(self): pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX+20+(40*self.bombRange),self.posY),40) pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX-20-(40*self.bombRange),self.posY),40) pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX,self.posY+20+(40*self.bombRange)),40) pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX,self.posY-20-(40*self.bombRange)),40) I hope you can help me.I am going to appreciate that.

http://stackoverflow.com/comment/80675324
type: Comment
has text: Before printing, test each line to see if it only contains a newline character or a carriage return and newline character or whitespace..
score: 0
comment on: http://stackoverflow.com/q/46863924
type: QuestionComment

http://stackoverflow.com/comment/80551007
type: Comment
type: AnswerComment
has text: They also want to reverse the list too.
comment on: http://stackoverflow.com/a/46802126
score: 0

http://stackoverflow.com/a/46822566
has body: I guess you are using Mac. OSX will automatically use all available disk space as virtual memory. So maybe you have a biiiiiiig disk? This code causes MemoryError on linux.
accepted answer of: http://stackoverflow.com/q/46822538
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/80593047
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46822538

http://stackoverflow.com/q/46900034
has body: I want my python program to output a list of the top ten most frequently used words and their associated word count. I have to use mrjob - mapreduce to created this program. I wrote a program that finds the frequency of the words and outputs them in from most to least. However I'm not sure how to output only the top ten most frequently used words. I was thinking that maybe I could put it in a list and use a second map reducer for sorting, but I'm not sure how to do this with mapreduce. I new programming with mapreduce and python. can someone give me any suggestions? from mrjob.job import MRJob from mrjob.step import MRStep import re # Word frequency from book sorted by frequency # File: book.txt # regular expression used to identify word WORD_REGEXP = re.compile(r"[\w']+") class MRWordFrequencyCount(MRJob): def steps(self): # 2 steps return [ MRStep(mapper=self.mapper_get_words, reducer=self.reducer_count_words), MRStep(mapper=self.mapper_make_counts_key, reducer=self.reducer_output_words) ] # Step 1 def mapper_get_words(self, _, line): words = WORD_REGEXP.findall(line) for w in words: yield w.lower(), 1 def reducer_count_words(self, word, values): yield word, sum(values) # Step 2 def mapper_make_counts_key(self, word, count): # sort by values yield '%04d' % int(count), word def reducer_output_words(self, count, words): # First Column is the count # Second Column is the word for word in words: yield count, word if __name__ == '__main__': MRWordFrequencyCount.run()
answer count: 1
tagged with: mrjob
type: UnansweredQuestion
tagged with: python
has title: mapreduce for word frequency in Python
tagged with: mapreduce
type: Question
tagged with: hadoop
score: 0
has answer: http://stackoverflow.com/a/46900338

http://stackoverflow.com/a/46808915
has body: Split the source string on commas. Strip off any leading or trailing whitespace from each string in the resulting list. Join the strings using ', ' as the separator. Like this: src = '11525 23 AVE, EDMONTON,\n AB\n ,\n T6J 4T3\n' print(', '.join([s.strip() for s in src.split(',')])) output 11525 23 AVE, EDMONTON, AB, T6J 4T3 If you already have a list of strings, this is even easier: address = [ '11525 23 AVE', ' EDMONTON', '\n AB\n ', '\n T6J 4T3\n' ] print(', '.join([s.strip() for s in address]))
score: 0
has comment: http://stackoverflow.com/comment/80565080
type: Answer
answers question: http://stackoverflow.com/q/46808831
has comment: http://stackoverflow.com/comment/80565337

http://stackoverflow.com/comment/80502931
type: QuestionComment
comment on: http://stackoverflow.com/q/46778443
has text: @jwodder A more formal definition perhaps. I see the documentation as the guide for using a feature, not the definition of it. PEP's for example define the reasons for a feature, how should it work and how should it not.
score: 0
type: Comment

http://stackoverflow.com/q/46801139
has body: In the process of writing an app, I've come across a bizarre python code piece that I can't understand: The Code: msg = [108878, [[314.06, 2, 4.744018], [314.03, 1, 15.9059], [314.02, 2, 79.8338531], [314, 1, 54.90047253], [313.56, 2, 1.75392219], [313.53, 2, 15.61132219], [313.5, 1, 0.554316], [313.42, 1, 1.5976], [313.27, 1, 0.43344], [313.26, 1, 62.724], [313.25, 1, 2.57518855], [313.24, 1, 0.04], [313.09, 2, 22.51784808], [312.9, 1, 40], [312.82, 1, 26.65592034], [312.7, 1, 35.53791008], [312.62, 1, 0.46912], [312.61, 1, 100], [312.6, 1, 48.33502123], [312.57, 1, 4.24547326], [312.56, 2, 0.2], [312.5, 2, 109.76863639], [312.43, 1, 100], [312.42, 1, 0.11142352], [312.4, 1, 7.815571], [314.09, 2, -3.01187461], [314.14, 1, -1.27056771], [314.39, 2, -9.31898324], [314.46, 1, -0.01930229], [314.49, 1, -0.40344], [314.5, 1, -3.40637161], [314.53, 1, -0.2], [314.54, 2, -0.46432889], [314.57, 1, -0.04200538], [314.71, 1, -0.050949], [314.84, 1, -0.02153813], [314.88, 1, -0.04200538], [314.93, 1, -68.439], [314.94, 2, -7.477782], [314.95, 1, -5], [315.1, 1, -5.97], [315.12, 1, -0.01], [315.16, 1, -40], [315.2, 1, -0.04200538], [315.22, 1, -25.7525], [315.23, 1, -78.54523718], [315.38, 1, -80], [315.42, 1, -6.65060488], [315.47, 1, -20], [315.48, 1, -5.36]]] bids = asks = {} lenbids = lenasks = 0 for order in msg[1]: if float(order[2])&gt;0: lenbids +=1 bids[order[0]]=order[2] elif float(order[2])&lt;0: lenasks+=1 asks[order[0]]=-order[2] print(len(bids),len(asks),lenbids,lenasks) Output: 50 50 25 25 It seems to me as though python is behaving properly with regards to the lenbids/lenasks actions but is executing the second part of the if statement regardless of whether the condition is met or not? I'm running Pycharm with Anaconda3 if that makes any difference. Any help greatly appreciated!
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46801166
accepted answer: http://stackoverflow.com/a/46801166
has title: Python code ignoring if statements
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80549127
type: Question
tagged with: if-statement

http://stackoverflow.com/q/46760206
tagged with: stdout
type: Question
has answer: http://stackoverflow.com/a/46763005
tagged with: hpc
has body: Refer to the following gather code: from mpi4py import MPI comm = MPI.COMM.WORLD size = comm.Get_size() rank = comm.Get_rank() stat = MPI.Status() message = (rank)**2 print "Before Gather ",rank, message message = comm.gather(message, root=0) if rank == 0: print "After Gather ",rank,message How can I use the comm.barrier() function to ensure the “After” step always comes after all the “Before” steps? If I put comm.barrier() before if condition, the results would just be in any order. I've tried flush and it doesn't work. Should I specify the send buffer and receive buffer using Gather? Or, should I try gather everything to one process, then scatter, then gather again? Any advice is more than welcome and appreciated.
tagged with: mpi4py
score: 0
answer count: 1
has title: how to print "before gather" before "after gather" in mpi python mpi4py
tagged with: mpi
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/46799456
accepted answer: http://stackoverflow.com/a/46800002
has comment: http://stackoverflow.com/comment/80547099
has comment: http://stackoverflow.com/comment/80546772
tagged with: python
has comment: http://stackoverflow.com/comment/80559777
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80547203
has answer: http://stackoverflow.com/a/46800080
tagged with: scipy
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46800002
has comment: http://stackoverflow.com/comment/80546872
possible better answer: http://stackoverflow.com/a/46800080
tagged with: arrays
has title: Python, finding all local maxima of array, adjusting for flaws in measurement
score: 0
answer count: 2
has body: i'm trying to get the maximum points in a one dimensional array, where it makes several curves. To do this i use scipy.signal.argrelextrema, along with np.greater. Give here where the array is y: argrelextrema(y, np.greater) The issue is, that this one dimensional data has inaccuracies due to the way the data for y was gathered. And so, there's a lot of "false positives" at the bottom of the curve, where there technically is a maxima at the bottom because of one value being bigger than the surrounding ones. For reference, here's y, over x which is just the index of each y value, to demonstrate the array i'm working with. The inaccuracies at the bottom is not visible. Ignore axises, used what i had in the code. Also, here's the result of me using the found maxima to calculate a value, as seen this is not wanted, as the expected result should have been a smooth falling curve. The graph was made with one point for each maxima, in an increasing order. And it's clearly wrong, as one can observe from the actual graph. So, what's the best solution to avoid shis? I failed to find something that could approximate the graph in a good enough manner for me the be able to use it. I looked into smoothening, but the methods i found, like savgol_filter from scipy.signal, was something i could not understand. The current solution was to ignore values of y that were below 5, which was roughly a bit over the bottom of the curve, but not an ideal solution at all. Update: Found out find_peaks_cwt from scipy.signal works for this too. It's a tad more complex as i have absolutely no clue how most of it works, even after reading up on it a bit. However, i managed to make a slightly better graph, i think, using: find_peaks_cwt(y, [3], noise_perc=2) However, the result seen below, is only a result of me dropping noise from 10 to 2, without really knowing how that affects the result. Edit: Here's is the 1D-array i'm working on: https://pastebin.com/GZrBBRce Sorry for bad representation, but e…

http://stackoverflow.com/comment/80649072
comment on: http://stackoverflow.com/q/46850706
score: 0
type: Comment
type: QuestionComment
has text: It looks like the function really does go round once a second, its just that the lines in the log are produced all at the same time.

http://stackoverflow.com/q/46847281
has answer: http://stackoverflow.com/a/48831464
has comment: http://stackoverflow.com/comment/80643261
score: 4
has answer: http://stackoverflow.com/a/52508125
upvote count: 4
answer count: 2
downvote count: 0
has title: Pycharm Console crash after Ctrl+C
favorite count: 0
has comment: http://stackoverflow.com/comment/80643702
type: UnansweredQuestion
tagged with: python
has body: When using the interactive Python console in Pycharm (community edition 2017.1.5), the console crashes when using a keyboard interrupt Ctrl+C. Let's say the program is stuck in a very long operation that I want to stop. When I press Ctrl+C the execution actually stops, but the console crashes if I try any other operation on the console. This is the error I am receiving: Any idea how can I solve this? I just want to continue working on the same console after a Keyboard Interrupt.
tagged with: pycharm
has comment: http://stackoverflow.com/comment/80642005
has comment: http://stackoverflow.com/comment/84666095
has comment: http://stackoverflow.com/comment/80642746
type: Question

http://stackoverflow.com/q/46770328
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50774783
answer count: 4
has answer: http://stackoverflow.com/a/53594253
type: UnansweredQuestion
tagged with: stomp.py
score: 6
has answer: http://stackoverflow.com/a/78342903
has title: ActiveMQ - STOMP+SSL with Python STOMP client
has answer: http://stackoverflow.com/a/64767610
downvote count: 0
tagged with: activemq-classic
tagged with: ssl
type: Question
tagged with: stomp
upvote count: 6
has body: Can anyone explain me how to add SSL to the Python STOMP client I'm using. I added the stomp+ssl transport connector in the ActiveMQ configuration file and my basic Python STOMP client is below: import time import sys import stomp class MyListener(stomp.ConnectionListener): def on_error(self, headers, message): print('received an error "%s"' % message) def on_message(self, headers, message): print('received a message "%s"' % message) conn = stomp.Connection() conn.set_listener('', MyListener()) conn.start() conn.connect('admin', 'password', wait=True) conn.subscribe(destination='/queue/test', id=1, ack='auto') conn.send(body=' '.join(sys.argv[1:]), destination='/queue/test') time.sleep(2) conn.disconnect() I created the key store and trust store given in the http://activemq.apache.org/how-do-i-use-ssl.html docs and added them to the SSL_OPTS environment variable in the broker but I'm unable to find how to initialize the Python STOMP client with the key store and trust store. Should I use the SSL paraments given in the stomp.Connection() method, and if yes how to do so? Can anyone please explain if there is any other way to add SSL over STOMP?

http://stackoverflow.com/comment/80474968
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46764858
score: 0
has text: Does the elasticsearch server let you query on dates, or is that not an index that is available?

http://stackoverflow.com/a/46821748
downvote count: 2
has body: You can explicitly run the pip3 script with a particular Python version, by prefixing it with the appropriate python3.x command: ldo@theon:~&gt; pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) ldo@theon:~&gt; python3.5 $(which pip3) --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.5)
upvote count: 10
score: 8
type: Answer
answers question: http://stackoverflow.com/q/46820625
has comment: http://stackoverflow.com/comment/80601167

http://stackoverflow.com/a/46894133
downvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/46892522
has comment: http://stackoverflow.com/comment/80737318
has body: The code: validDoc = {} for key in document: if key not in v.errors: validDoc[key] = document[key] print(validDoc) produces this output: {'name': 'john doe'}
upvote count: 2

http://stackoverflow.com/a/46814715
upvote count: 4
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/46814629
has body: It would appear as so in JSON: { "product": [ { "sku": "BL394D", "quantity": 4, "description": "Basketball", "price": 450 }, { "sku": "BL4438H", "quantity": 1, "description": "Super Hoop", "price": 2392 } ] } So in Python, it would be an object that has a map to product, which is an array of other objects with the properties sku, quantity, etc.

http://stackoverflow.com/a/51275655
upvote count: 3
has comment: http://stackoverflow.com/comment/122938588
score: 3
has body: You need to specify the dimensions of the input to the first layer otherwise it will give you an empty list. Compare both results from both prints the only difference is in the initialization of the shape of the input. from keras import backend as K import numpy as np from keras.models import Sequential from keras.layers import Dense # first model without input_dim prints an empty list model = Sequential() model.add(Dense(5, weights=[np.ones((3,5)),np.zeros(5)], activation='relu')) print(model.get_weights()) # second model with input_dim prints the assigned weights model1 = Sequential() model1.add(Dense(5, weights=[np.ones((3,5)),np.zeros(5)],input_dim=3, activation='relu')) model1.add(Dense(1, activation='sigmoid')) print(model1.get_weights())
downvote count: 0
answers question: http://stackoverflow.com/q/46798708
type: Answer

http://stackoverflow.com/q/46901524
score: 1
has answer: http://stackoverflow.com/a/46901612
type: Question
accepted answer: http://stackoverflow.com/a/46901612
has comment: http://stackoverflow.com/comment/80749953
has comment: http://stackoverflow.com/comment/80749959
has body: Rules in applyRules is going to be asked to users, but it does not work what it should work which is [“character1:substitution”, “character2:substitution”] When user put ['b:c','c:d'], it prints c,c. However, it should print d when char is b The function takes a single character and a set of rules as a list. And this is what I wrote so far def applyRules(char, rules): for rule_list in (rule.split(':') for rule in rules): char = char.replace(rule_list[0], rule_list[1]) return char What should I add to make it work appropriately?
possible better answer: http://stackoverflow.com/a/46901673
answer count: 2
has title: Replace multiple characters in a string using a set of rules
upvote count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/46901673
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/46785577
tagged with: python
tagged with: qcombobox
score: 1
has answer: http://stackoverflow.com/a/46802151
tagged with: pyqt5
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: qtablewidget
accepted answer: http://stackoverflow.com/a/46802151
has answer: http://stackoverflow.com/a/46791567
answer count: 2
tagged with: pyqt
possible better answer: http://stackoverflow.com/a/46791567
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80608701
has body: Here I have my Table Widget that the user will fill later: class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(238, 260) self.tableWidget = QtWidgets.QTableWidget(Form) self.tableWidget.setGeometry(QtCore.QRect(10, 10, 221, 241)) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(2) self.tableWidget.setRowCount(7) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(2, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(3, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(4, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(5, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(6, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setItem(0, 0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setItem(0, 1, item) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) And here is my Dialog window which contains a combobox: class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(281, 176) self.comboBox = QtWidgets.QComboBox(Dialog) self.comboBox.setGeometry(QtCore.QRect(90, 10, 71, 22)) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.comboBox_2 = QtWidgets.QComboBox(Dialog) self.comboBox_2.setGeometry(QtCore.QRect(10, 10, 71, 22)) self.comboBox_2.setObjectName("comboBox_2") self.comboBox_2.addItem("") self.dateTimeEdit = QtWidgets.QDateTimeEdit(Dialog) self.dateTimeEdit.setGeometry(QtCore.QRect(10, 60, 194, 22)) self.dateTimeEdit.setObjectNa…
has comment: http://stackoverflow.com/comment/80607249
has title: PyQt5: Fill combo-boxes with items from a table-widget

http://stackoverflow.com/q/46841864
has answer: http://stackoverflow.com/a/46841934
has title: Python Print Order
has answer: http://stackoverflow.com/a/46841943
has comment: http://stackoverflow.com/comment/80631496
type: Question
has body: This is probably a dumb question, but I'm new to programming and I have a recursive function set up that I'm trying to figure out. For any print function in Python, is it necessarily true that lines are printed in the order that they are written in the script OR for larger outputs, is it possible that smaller length outputs can get printed first in the console even though the print statement is later in the code (maybe due to some memory lag)? Example: def test_print(): #don't run this, but was meant for scale. Is there any chance the 1 would print before the list of lists? print([[i for i in range(10000)] for j in range(10000)]) print(1)
has comment: http://stackoverflow.com/comment/80631530
favorite count: 0
has answer: http://stackoverflow.com/a/46841888
score: 0
answer count: 3
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/80694568
type: Comment
comment on: http://stackoverflow.com/q/46873354
has text: I would strongly invite you to read through [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples).
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80577633
comment on: http://stackoverflow.com/q/46812671
score: 0
has text: @hpaulj I have tried it but it unfortunately did not yield the correct output.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46849694
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46844771
type: Answer
has body: Good question. Try to use another selector, for example: css class or use xpath method contains(). Example: //div[contains(text(), "checkbox")] I can help you if you can provide source code of the page or needed element.
answers question: http://stackoverflow.com/q/46844771
has comment: http://stackoverflow.com/comment/80655782
score: 0

http://stackoverflow.com/q/46760037
favorite count: 0
tagged with: python
has title: How to calculate the mean index in array with NumPy
has comment: http://stackoverflow.com/comment/80465426
score: 2
upvote count: 2
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/53162738
has body: How can I calculate the mean index T for an array nums that minimize the value of abs(sum(nums[:T])-sum(nums[T:]))
has answer: http://stackoverflow.com/a/67584865
tagged with: average
tagged with: numpy
has comment: http://stackoverflow.com/comment/80465613
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80465739
has comment: http://stackoverflow.com/comment/80465512

http://stackoverflow.com/comment/80495624
type: QuestionComment
has text: You can't use `equals()` to test whether a `WebElement` is equal to a `String`. That's comparing apples with watermelons.
score: 1
comment on: http://stackoverflow.com/q/46774701
type: Comment

http://stackoverflow.com/q/46827718
score: 4
has comment: http://stackoverflow.com/comment/80602908
type: UnansweredQuestion
has title: How to upload file to a tftp server using python?
has comment: http://stackoverflow.com/comment/80603217
has answer: http://stackoverflow.com/a/46827834
type: Question
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80602716
has body: Please help me to upload a file to a TFTP server using python. I'm using tftpy module. In the document(http://tftpy.sourceforge.net/sphinx/index.html) it says class tftpy.TftpClient.TftpClient(host, port, options={}) upload(filename, input, packethook=None, timeout=5) what should be the filename- is it a path of the remote server where the file already existing or is it just new file name which server will create using the filename in the default directory or path for the new file (filename) to create ? Do I have to have to create a file of same name as input file in the server before upload? What is the default directory the server will upload files to? If so, what is the other way for the server to create a file using the name passed (filename)? What I'm sending is tftp_obj.upload('something.txt','/home/username/project/example.txt') I'm sending the new file name something.txt which doesn't exist in the server I'm getting the error message: raise TftpException, "Received ERR from server: " + str(pkt) tftpy.TftpShared.TftpException: Received ERR from server: ERR packet: errorcode = 1 msg = File not found I get the same error if I create the file (same as input file name) in the remote server under root (/example.txt) (assuming the default folder it uploads to is root) and give path for filename parameter tftp_obj.upload('/example.txt','/home/username/project/example.txt') Same error when I pass just the existing file name tftp_obj.upload('example.txt','/home/username/project/example.txt') Please help with examples.
tagged with: python
tagged with: tftp
has comment: http://stackoverflow.com/comment/80602808

http://stackoverflow.com/comment/80661833
comment on: http://stackoverflow.com/q/46836818
score: 0
has text: Thanks, is it better to use one over the other in certain situations?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46838019
score: 1
upvote count: 1
has body: The following will aggregate the data of type and sum that of value. You'll find the summation in sum_value from django.db.models import Count query = (Names.objects .values('type') .annotate(sum_value=Count('value'))
answers question: http://stackoverflow.com/q/46837716
downvote count: 0
type: Answer

http://stackoverflow.com/q/46830351
has answer: http://stackoverflow.com/a/46830580
has comment: http://stackoverflow.com/comment/80608138
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/80608054
has answer: http://stackoverflow.com/a/46830460
type: Question
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/46830444
has title: Generating multiple list from a list
has answer: http://stackoverflow.com/a/46830452
downvote count: 2
possible better answer: http://stackoverflow.com/a/46830458
has answer: http://stackoverflow.com/a/46830458
has body: What is the best way to append a list of A = [1,2,3,4,5] and obtain a list of this sort; B = [[1], [1, 2], [1,2,3], [1,2,3,4], [1,2,3,4,5]]
tagged with: list
upvote count: 5
accepted answer: http://stackoverflow.com/a/46830444
answer count: 5

http://stackoverflow.com/a/46752214
type: Answer
answers question: http://stackoverflow.com/q/46752146
downvote count: 0
has body: a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6] from itertools import groupby [list(g) for k, g in groupby(a, lambda x:x&lt;7) if k] Output: [[3, 2, 5], [4, 5, 6, 3], [4, 5], [5], [4], [6]]
accepted answer of: http://stackoverflow.com/q/46752146
score: 9
type: AcceptedAnswer
upvote count: 9

http://stackoverflow.com/q/46820182
has answer: http://stackoverflow.com/a/46820312
has answer: http://stackoverflow.com/a/46820633
has body: I wanted to generate 1 or -1 in Python as a step to randomizing between non-negative and non-positive numbers or to randomly changing sign of an already existing integer. What would be the best way to generate 1 or -1 in Python? Assuming even distribution I know I could use: import random #method1 my_number = random.choice((-1, 1)) #method2 my_number = (-1)**random.randrange(2) #method3 # if I understand correctly random.random() should never return exactly 1 # so I use "&lt;", not "&lt;=" if random.random() &lt; 0.5: my_number = 1 else: my_number = -1 #method4 my_number = random.randint(0,1)*2-1 Using timeit module I got the following results: #method1 s = "my_number = random.choice((-1, 1))" timeit.timeit(stmt = s, setup = "import random") &gt;2.814896769857569 #method2 s = "my_number = (-1)**random.randrange(2)" timeit.timeit(stmt = s, setup = "import random") &gt;3.521280517518562 #method3 s = """ if random.random() &lt; 0.5: my_number = 1 else: my_number = -1""" timeit.timeit(stmt = s, setup = "import random") &gt;0.25321546903273884 #method4 s = "random.randint(0,1)*2-1" timeit.timeit(stmt = s, setup = "import random") &gt;4.526625442240402 So unexpectedly method 3 is the fastest. My bet was on method 1 to be the fastest as it is also shortest. Also both method 1 (since Python 3.6 I think?) and 3 give the possibility to introduce uneven distributions. Although method 1 is shortest (main advantege) for now I would choose method 3: def positive_or_negative(): if random.random() &lt; 0.5: return 1 else: return -1 Testing: s = """ import random def positive_or_negative(): if random.random() &lt; 0.5: return 1 else: return -1 """ timeit.timeit(stmt = "my_number = positive_or_negative()", setup = s) &gt;0.3916183138621818 Any better (faster or shorter) method to randomly generate -1 or 1 in Python? Any reason why would you choose method 1 over method 3 or vice versa?
has answer: http://stackoverflow.com/a/46821099
tagged with: python
has answer: http://stackoverflow.com/a/46820635
type: AnsweredQuestion
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/69326040
has answer: http://stackoverflow.com/a/50026751
possible better answer: http://stackoverflow.com/a/46821099
has answer: http://stackoverflow.com/a/46829405
has title: Randomly generate 1 or -1 (positive or negative integer)
upvote count: 28
tagged with: random
has comment: http://stackoverflow.com/comment/80588076
downvote count: 0
has answer: http://stackoverflow.com/a/76220340
accepted answer: http://stackoverflow.com/a/46820635
favorite count: 0
score: 28

http://stackoverflow.com/q/46869520
has comment: http://stackoverflow.com/comment/80686358
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46869623
linked to: http://stackoverflow.com/q/972
accepted answer: http://stackoverflow.com/a/46869556
possible better answer: http://stackoverflow.com/a/57231862
tagged with: stdout
type: Question
has answer: http://stackoverflow.com/a/46869556
has comment: http://stackoverflow.com/comment/80686920
has comment: http://stackoverflow.com/comment/80686329
has body: The following lines change the stdout from sys.__stdout__ to a file. This works fine. import sys sys.stdout = open("stdout.txt", "a") print("test") However, I want the output to the file as well as to sys.__stdout__. What do I need to add so "test" will be written to both?
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/57231862
tagged with: python
has title: How to redirect stdout to both a file and `sys.__stdout__`?
tagged with: file

http://stackoverflow.com/comment/80743530
has text: Ok, so, take a look to this post hope will be helpful: https://stackoverflow.com/questions/31235059/how-to-downgrade-python-version-on-centos
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46897967
score: 0

http://stackoverflow.com/comment/80656336
comment on: http://stackoverflow.com/q/46854451
has text: You should run it where `requirements.txt` is
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46780049
has body: Ok stored in a list: sum_of_squares=[] def add_squares(start, end,sum_of_squares): for n in range(start, end): calc=(n**2) sum_of_squares.append(calc) answer=sum(sum_of_squares) print(answer) add_squares(1,21,sum_of_squares) Result 2870
type: Answer
has comment: http://stackoverflow.com/comment/80506143
answers question: http://stackoverflow.com/q/46780007
has comment: http://stackoverflow.com/comment/80506175
score: 0

http://stackoverflow.com/comment/80581974
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46811270
has text: @oj43085 forget line numbers and we are saying the same ; do you get the idea ?
type: AnswerComment

http://stackoverflow.com/a/46822823
has comment: http://stackoverflow.com/comment/80594426
type: Answer
answers question: http://stackoverflow.com/q/46816469
has body: This is because your feature category has dimension = 3 (3 values), but feature demon has dimension 9 (9 values) in your tfrecord. When using LinearClassifier, you need to ensure all features have the same dimensions.
has comment: http://stackoverflow.com/comment/80790764
score: 0

http://stackoverflow.com/comment/80766599
comment on: http://stackoverflow.com/a/46901799
type: AnswerComment
has text: ha ha, i said use it in ur code, it's the pseudo code. i am editing it.
score: 0
type: Comment

http-status-code-404
tags question: http://stackoverflow.com/q/46799609
type: Tag
tag name: http-status-code-404

http://stackoverflow.com/comment/80496865
score: 12
type: AnswerComment
type: Comment
has text: @BabkenVardanyan That command would install two packages named `splinter` and `django`. `splinter[django]`, on the other hand, installs a variant of the `splinter` package which contains support for `django`. Note that it has nothing to do with the `django` package itself, but is just a string defined by the `splinter` package for a particular feature set that gets enabled.
comment on: http://stackoverflow.com/a/46775606

http://stackoverflow.com/comment/80563681
type: Comment
type: QuestionComment
has text: check this https://stackoverflow.com/questions/43357732/how-to-calculate-the-cosine-similarity-between-two-tensors/43358711#43358711
score: 0
comment on: http://stackoverflow.com/q/46793190

http://stackoverflow.com/q/46835301
has answer: http://stackoverflow.com/a/46835411
downvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46835327
answer count: 3
has title: How to find the list with the the first value is the largest in python
has answer: http://stackoverflow.com/a/46835465
favorite count: 0
has body: Here i have a list of lists: m = [[[0.5898237279659958, 620, 200]],[[0.58557319664958118, 720, 200]],[[0.5959494936867108, 820, 200]], [[0.59444930616327041, 920, 200]]] I would like to find out the list which first value is the largest, for example, in m, i need to find out this [[0.5959494936867108, 820, 200]]
tagged with: python
has comment: http://stackoverflow.com/comment/80618149
score: 0
possible better answer: http://stackoverflow.com/a/46835411
upvote count: 1
has answer: http://stackoverflow.com/a/46835327

http://stackoverflow.com/q/46903529
type: Question
answer count: 2
has body: I'm attempting to make a dynamic GUI where clicking a button causes the creation of a new frame that is placed above the button with 3 entry widgets (user options) inside of it, and I need to be able to read the user input from the 3 entry widgets &amp; possibly alter them. Each time the button is pressed, three new callable entry widgets should appear. I know that this is wrong because it has been giving me errors, but could something similar to the lists be used to create the widgets dynamically? from Tkinter import * app = Tk() frameNames = [] widgetNames = [] def createwidgets(): global widgetNames global frameNames frameNames += (str("g"+str(len(frameNames)))) #why does the letter &amp; number get added as seperate elements? widgetNames += [(str("w"+str(len(widgetNames)-1))), (str("w"+str(len(widgetNames)))), (str("w"+str(len(widgetNames)+1)))] frameNames[len(frameNames) - 1] = Frame(app) frameNames[len(frameNames) - 1].pack() widgetNames[len(widgetNames) - 3] = Entry(frameNames[len(frameNames) - 1]) widgetNames[len(widgetNames) - 3].pack() widgetNames[len(widgetNames) - 2] = Entry(frameNames[len(frameNames - )- 1]) widgetNames[len(widgetNames) - 2].pack() widgetNames[len(widgetNames) - 1] = Entry(frameNames[len(frameNames) - 1]) widgetNames[len(widgetNames) - 1].pack() createWidgetButton = Button(app, text="createWidgets", command=createwidgets()) createWidgetButton.grid(sticky=S) app.mainloop()
favorite count: 0
has answer: http://stackoverflow.com/a/46907707
has comment: http://stackoverflow.com/comment/80756846
tagged with: python
tagged with: tkinter-entry
possible better answer: http://stackoverflow.com/a/46907707
has answer: http://stackoverflow.com/a/46911007
tagged with: tkinter
score: 0
upvote count: 1
downvote count: 1
has title: Tkinter dynamically create widgets from button
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80767579
accepted answer: http://stackoverflow.com/a/46911007

http://stackoverflow.com/comment/80597113
has text: Hi, It doesn't select items in the ROI with rectangles around them I am clearly missing code to select objects in the ROI with rectangles around them ...
score: 0
comment on: http://stackoverflow.com/q/46824478
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46836287
has comment: http://stackoverflow.com/comment/81144899
has comment: http://stackoverflow.com/comment/81098934
tagged with: python-module
tagged with: python
has comment: http://stackoverflow.com/comment/81114240
has comment: http://stackoverflow.com/comment/81149311
has title: How to get a list of modules imported by a python module
downvote count: 0
has answer: http://stackoverflow.com/a/47093697
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81152215
score: 6
linked to: http://stackoverflow.com/q/4858100
type: Question
linked to: http://stackoverflow.com/q/32236052
has comment: http://stackoverflow.com/comment/80621341
has comment: http://stackoverflow.com/comment/81152923
has comment: http://stackoverflow.com/comment/81134132
tagged with: python-2.7
tagged with: python-import
has comment: http://stackoverflow.com/comment/81147708
answer count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/81134778
has body: I want to access some kind of import dependency tracking in Python, if there is any. I decided to add to my module a __dependencies__ dict describing versions of all modules imported by the module. I want to have an automated way of obtaining a list of modules imported by my module. Preferably in the last line of the module. ModuleFinder (as suggested by How to list imports within a Python module? ) would not work since the inspection shall be performed for already loaded module. Another problem with ModuleFinder is that it inspects a Python script (with if __name__ == '__main__' branch), not a module. If we consider a toy script script.py: if __name__ == '__main__': import foo then the result is: &gt;&gt;&gt; mf = ModuleFinder &gt;&gt;&gt; mf.run_script('script.py') &gt;&gt;&gt; 'foo' in mf.modules True which should be False if script is imported as a module. I do not want to list all imported modules - only modules imported by my module - so sys.modules (suggested by What is the best way of listing all imported modules in python?) would return too much. I may compare snapshots of sys.modules from the beginning and the end of the module code. But that way I would miss all modules used by my module, but imported before by any other module. It is important to list also modules from which the module imports objects. If we consider a toy module example.py: from foo import bar import baz then the result should be like: &gt;&gt;&gt; import example &gt;&gt;&gt; moduleImports(example) {'foo': &lt;module 'foo' from ... &gt;, 'baz': &lt;module 'baz' from ...&gt;} (it may contain also modules imported recursively or foo.bar given bar is a module). Use of globls() (according to How to list imported modules?) requires me to deal with non-module imports manually, like: from foo import bar import bar How can I avoid that? There is another issue with my solution so far. PyCharm tends to clean up my manual imports on refactoring, which makes it hard to keep it working.
favorite count: 0
linked to: http://stackoverflow.com/q/31165584
tagged with: python-3.x

http://stackoverflow.com/a/46879436
has body: The main reason why this does not work is because: n = (input("Enter the number of darts you have. ")) will put a string into n, we can solve this with: n = int(input("Enter the number of darts you have. ")) and: print("Pi is " + 4*(1.*circleval/squareval)) expects a string, but you do not provide one, we can solve this with: print("Pi is " + str(4*(1.*circleval/squareval))) But that being said, the program is still incorrect: it gives 0.773 as output for Pi, which is clearly wrong. The main problem is your sampling: you want to generate numbers between -1 and 1, but you generate numbers between -1 and 3. In your distance computations, you then use x-1 and y-1 shifting it to the -2 to 2 domain, but that is still too large. Furthermore the code not very elegant. from random import random n = int(input("Enter the number of darts you have. ")) c = 0 for i in range(n): x = 2*random()-1 y = 2*random()-1 if x*x + y*y &lt;= 1: c += 1 print("Pi is %s" % (4.0*c/n)) for n=100000, this has given me 3.14368 (although it might vary of course between several simulations).
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46879374
answers question: http://stackoverflow.com/q/46879374
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/80706201
has comment: http://stackoverflow.com/comment/80706237

http://stackoverflow.com/comment/80694050
has text: It would be helpful if you could post the original Date/Price columns (or at least the first 10-20 rows), along with the code you tried to get it to this state. It would seem like you could use `df.lookup`, but I'll reserve any more comments until we can see your data.
comment on: http://stackoverflow.com/q/46873354
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/46877421
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46876631
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46876631
type: Answer
has body: From PythonSpot: from Tkinter import * master = Tk() def callback(): print "click!" b = Button(master, text="OK", command=callback) b.pack() mainloop()

http://stackoverflow.com/q/46888006
score: 0
linked to: http://stackoverflow.com/q/4007413
has answer: http://stackoverflow.com/a/46888091
answer count: 1
has comment: http://stackoverflow.com/comment/80734380
tagged with: python-3.x
tagged with: python
tagged with: css
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46888091
tagged with: selenium
has body: I am trying to get these 6 selectors. I am only able to get 8 it seems. Furthermore, it is dynamic so it keeps changing //div[@class='sm-CouponLink']//div[@class='sm-CouponLink_Label'] The page keeps changing to //div[@class='sm-Coupon']//div[@class='sm-CouponLink'] And other variations of that. Ideally something like //div[@class*='sm-Coup'] I’ve tried using a wildcard but I’m fairly certain using that xpath does not support this and I am not wanting to use CSS in this case as I am fairly reliant on it. I have also tried: //div[starts-with(@class, ''sm-Coupo')] I am on this page here: https://www.bet365.com.au/#/AS/B1/
type: Question
has title: Unable to get partial or wildcard equivalent xpath selector

http://stackoverflow.com/a/46761133
downvote count: 0
answers question: http://stackoverflow.com/q/46759906
score: 4
type: Answer
has body: The blockmodel function has been replaced in the latest version of networkx (you are looking at older documentation) with quotient_graph. Here is an example of generating a blockmodel &gt;&gt;&gt; G = nx.path_graph(6) &gt;&gt;&gt; partition = [{0, 1}, {2, 3}, {4, 5}] &gt;&gt;&gt; M = nx.quotient_graph(G, partition, relabel=True) &gt;&gt;&gt; list(M.edges()) [(0, 1), (1, 2)] See https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.minors.quotient_graph.html?highlight=blockmodel for the updated documentation.
upvote count: 4

http://stackoverflow.com/q/46763121
linked to: http://stackoverflow.com/q/11067962
has comment: http://stackoverflow.com/comment/80472001
type: Question
accepted answer: http://stackoverflow.com/a/46765307
has comment: http://stackoverflow.com/comment/80472454
has body: Quite simply, I'm learning how to edit photos with openCV/numpy. My question is why is the second function using the image created by the first? I run two functions - one to color columns in black and white, and a second that colors rows in black and white. First function runs fine, but the second one uses the image created in the first, so I get rows and columns in black and white. import cv2 import numpy as np from matplotlib import pyplot as plt img_source = "brad.jpg" def read_image(image_source): #global img, width, height img = cv2.imread(image_source, 1) height, width = img.shape[:2] print("Image size: x ", width, " y ", height) return img, width, height def black_and_white_cols(image_source): width_adjustment = 100 total_cols = round(width / width_adjustment,0) edited_image = image_source bw_image = cv2.imread(img_source, 0) # The next line is to convert to the right interface # https://stackoverflow.com/questions/11067962/is-it-possible-to-have-black-and-white-and-color-image-on-same-window-by-using-o bw_image_b = cv2.cvtColor(bw_image,cv2.COLOR_GRAY2BGR) for x in range(1, int(total_cols), 2): top_row = 0 bottom_row = height left_col = x*width_adjustment right_col = (x * width_adjustment) + width_adjustment bw_part = bw_image_b[top_row:bottom_row, left_col:right_col] edited_image[top_row:bottom_row, left_col:right_col] = bw_part show_image(edited_image) def black_and_white_cols(image_source): width_adjustment = 100 total_cols = round(width / width_adjustment,0) edited_image = image_source bw_image = cv2.imread(img_source, 0) # The next line is to convert to the right interface # https://stackoverflow.com/questions/11067962/is-it-possible-to-have-black-and-white-and-color-image-on-same-window-by-using-o bw_image_b = cv2.cvtColor(bw_image,cv2.COLOR_GRAY2BGR) for x in range(1, int(total_cols), 2): top_row = 0 bottom_row = height left_col = x*width_adjustment right_col = (x * width_adjustment) + width_adjustment bw_part = bw_image_b[top_row:bottom_row, left_col…
score: 0
has answer: http://stackoverflow.com/a/46765307
answer count: 1
has comment: http://stackoverflow.com/comment/80472546
has comment: http://stackoverflow.com/comment/80471945
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80472032
tagged with: python
has title: Why is the image being used an image from a previous process?
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80471546
has comment: http://stackoverflow.com/comment/80471554

http://stackoverflow.com/comment/80754244
score: 1
has text: The interpreter is the first thing I set for a new project, no matter what the default settings may be. Open your project, go to File, Settings, Project Interpreter and then choose the one yo like. `OK` will save that to your project and you are good to go.
comment on: http://stackoverflow.com/q/46903166
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46897878
accepted answer of: http://stackoverflow.com/q/46897691
has comment: http://stackoverflow.com/comment/80744596
has comment: http://stackoverflow.com/comment/80742993
answers question: http://stackoverflow.com/q/46897691
type: Answer
has body: It sounds like what you need is a dictionary which relates the name of a month and its numerical value. import datetime month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months = {name : (index + 1) for index, name in enumerate(month_names)} current_month = datetime.date.today().strftime('%B') month_joined = input("Please enter the month you joined: ") month_difference = abs(months[current_month] - months[month_joined]) print(month_difference) You can also accomplish the creation of the dictionary through use of the calendar module's month_name list attribute. import datetime, calendar months = {name : (index + 1) for index, name in enumerate(calendar.month_name[1:])} current_month = datetime.date.today().strftime('%B') month_joined = input("Please enter the month you joined: ") month_difference = abs(months[current_month] - months[month_joined]) print(month_difference)
has comment: http://stackoverflow.com/comment/80743796
has comment: http://stackoverflow.com/comment/80743889
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80744902
has comment: http://stackoverflow.com/comment/80743775
has comment: http://stackoverflow.com/comment/80743793
type: AcceptedAnswer
downvote count: 0

gnu-make
type: Tag
tags question: http://stackoverflow.com/q/46831085
tag name: gnu-make

http://stackoverflow.com/comment/80468505
has text: @Greenstick Maybe I'm misunderstanding your question, but I did it like that because herteladrian wants to pass the header as an arg to the printProgressBar function, and that header may change over subsequent calls to the same progress bar.
comment on: http://stackoverflow.com/a/46751803
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/46810099
tagged with: dictionary
has answer: http://stackoverflow.com/a/46815299
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I am trying to encrypt password from userinput through args and write it to an existing conf file without overwriting existing dict variables in conf file. I have tried following script, Please let me know how to achieve it or any suggestions are appreciated. inputJson.conf { "MetadataInputs": { "redHat": { "hostName": "10.110.20.30", "userName": "admin", "password": "admin123", "organisationName": "networks", "repository":"Red Hat" } } } WriteJson.py import json from Crypto.Cipher import AES import base64 import sys import io with open('conf.json') as inputParameters: readInputData = json.load(inputParameters) class Test(): def __init__(self,readInputData): self.__dict__=readInputData self.hostName = readInputData['MetadataInputs']['redHat']['hostName'] self.userName = readInputData['MetadataInputs']['redHat']['userName'] self.orgName = readInputData['MetadataInputs']['redHat']['organisationName'] self.repostiroyName = readInputData['MetadataInputs']['redHat']['repository'] def encryptPassword(self): try: args = sys.argv[1:] self.inputPassword = sys.argv[1] msg_text = self.inputPassword.rjust(32) secret_key = '1234567890123456' cipher = AES.new(secret_key, AES.MODE_ECB) encoded = base64.b64encode(cipher.encrypt(msg_text)) # self.password = { # "MetadataInputs": { # "redHat": { # "password": encoded # } # }} with io.open('conf.json', 'w', encoding='utf8') as outfile: self.password=outfile['MetadataInputs']['redHat']['password'] str_ = json.dump(self.password, outfile, indent=4, ensure_ascii=False) outfile.write((str_)) except Exception: print "Exception Occurred --- Please provide password " obj = Test(readInputData) obj.encryptPassword()
type: Question
tagged with: python-2.7
score: 0
answer count: 1
has title: How to write specific variable into conf/json file without overwriting existing dict variables using python
tagged with: python

http://stackoverflow.com/comment/80743962
has text: There is no module called 'monthdelta' for me
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46898192

http://stackoverflow.com/a/54929520
has body: I had an old setup without a cv2.__version__ variable (egg file was used to install opencv 2.4.2 for python 2.7.6 under windows 10; just returned AttributeError: 'module' object has no attribute '__version__') This worked for all setups: opencv_version = cv2.__version__ if hasattr(cv2, '__version__') else cv2.__file__.replace('\\','').replace('/','').split("cv2-")[-1].split("-")[0]
answers question: http://stackoverflow.com/q/46837658
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/46760564
answers question: http://stackoverflow.com/q/46760474
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80478028
accepted answer of: http://stackoverflow.com/q/46760474
type: Answer
has body: use count function like this: a = "hi, hello, good by, , ," print(a.count(",")) it will show you: 5 but for your original code: path = 'D:/Stiudies/Data/female/*.txt' inf = glob.glob(path) buffer_commas = 0 for name in inf: with open(name, 'r', encoding="utf8") as input_file: raw_data = input_file.read() buffer_commas = buffer_commas + raw.count(",") print(buffer_commas)
has comment: http://stackoverflow.com/comment/80480896

http://stackoverflow.com/q/46769913
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80485903
has body: Is there any extension of the Hough Transform (https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html) to 3D volumic images (stacks) ? I have (image below) a 3D skeleton on which I want to detect segments. The 3D skeleton was computed using the 'skeletonize_3d()' belonging to te 'skimage' package. enter image description here
has comment: http://stackoverflow.com/comment/80485770
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80485634
upvote count: 1
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/80485462
tagged with: stack
tagged with: image-processing
tagged with: medical
type: Question
has title: 3D Hough Transform for medical imaging
favorite count: 0

http://stackoverflow.com/a/46790962
has body: It seems you need double merge, parameter on should me omit if only same joined columns of dfs: df = df1.merge(df2).merge(df3)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80540723
answers question: http://stackoverflow.com/q/46790905

http://stackoverflow.com/comment/80493153
type: QuestionComment
comment on: http://stackoverflow.com/q/46773511
has text: @ipetr The `await` lines could probably be removed too by making a function. I've never used `await` before though; I didn't know python even had such a keyword.
score: 0
type: Comment

http://stackoverflow.com/a/46858019
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46857779
has body: I am not 100% sure what you are trying to do in your code. But from what I can tell this will do what you want it to do. Please comment if you were intending for it to do something else. I cleaned up a lot of the formating. And changed the last for loop to loop to all of the values in com_que_store to check_store. I am sure this is not the full intention of your code, but now it might be easier for you to addapt it to for your use. from random import randint, shuffle run = True num = 0 diff = int(input('Pick a number from 1-3: ')) if not diff &lt;= 3 and diff &gt;= 1: print('Make sure your number is from 1 to 3') raise TypeError que_1 = 'wright 1' que_2 = 'wrong 2' que_3 = 'wrong 3' que_4 = 'wrong 4' que_store = [que_2, que_3, que_4] com_que_store = [que_1] check_store = [] abcd = ['A', 'B', 'C', 'D'] for i in range(diff): r = randint(0, (2 - num)) print(que_store[r]) com_que_store.append(que_store[r]) que_store.pop(r) num = num + 1 print(com_que_store) shuffle(com_que_store) print('\n\n\n') print(com_que_store) for value in com_que_store: print value check_store.append(value) num = num + 1
type: Answer
answers question: http://stackoverflow.com/q/46857779
has comment: http://stackoverflow.com/comment/80663779
score: 0

http://stackoverflow.com/q/46896907
answer count: 1
tagged with: maya
tagged with: callback
has title: Open Maya callBacks in Python or C++ query all callbacks in Memory
tagged with: python
tagged with: c++
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47960295
type: Question
has comment: http://stackoverflow.com/comment/82924365
has body: Hello, I'm wondering if there is a way to query all **User Created callbacks in Maya?, And in the same way, if I can query what objects or nodes are connected to them. I want to manage better the cleanliness in the memory at every time and not let any callback lost in memory.** import maya.cmds as cmds import maya.OpenMaya as OpenMaya ########################################## class MayaSignals(object): def __init__(self): super(MayaSignals) self.callback_list = [] def setCallback(self, node): sel = OpenMaya.MSelectionList() sel.add(node) obj = OpenMaya.MObject() sel.getDependNode(0, obj) idx = OpenMaya.MNodeMessage.addAttributeChangedCallback(obj, self.reading_node) self.callback_list.append(idx) def removeAllCallback(self): for idx,itm in enumerate(self.callback_list): print(idx, 'removed') OpenMaya.MMessage.removeCallback(itm) def reading_node(self, msg, plug, otherplug, *clientData): if msg &amp; OpenMaya.MNodeMessage.kAttributeSet: print ('Attribute Changed On: %s' % plug.name()) if msg &amp; OpenMaya.MNodeMessage.kConnectionMade: print('Connection Created On: %s' % plug.name()) if msg &amp; maya.OpenMaya.MNodeMessage.kConnectionBroken: print ("Broken Connection On: %s" % plug.name()) ################################################################################################ node = cmds.ls(sl=True)[0] #&lt; ------ Node string type #signal = MayaSignals() # class to manage the callbacks #signal.setCallback(node) signal # # # # to keep the instance alive signal.removeAllCallback() # remove all into the array # ---------------------------------------------`-`---------------------------------------------- # Here, I created an example where I tag an object to a callback, and print something when some conditions happen, also. add to array every callback ID to delete it later. I just need a light, even if is in C++ I could check on the docs about the recommendations here.
score: 0
tagged with: maya-api
has answer: http://stackoverflow.com/a/47960295

http://stackoverflow.com/comment/80681909
type: QuestionComment
type: Comment
has text: So basically, you're computing k-means clusters but you've got too many clusters at the end. One janky solution would be to just take 1 "gold standard" sports document and then sort everything into 1 of 2 buckets based on distance from that one. Another option is to look into basic machine learning. This would be really easy to train since the only 2 outcomes are business or sports.
comment on: http://stackoverflow.com/q/46867085
score: 0

http://stackoverflow.com/comment/80744559
comment on: http://stackoverflow.com/q/46898512
has text: @chasmani Yes but some fields from the original JSON are optional. My code is working, but I don't think it's the better way to do it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46772652
answers question: http://stackoverflow.com/q/46772012
type: Answer
has body: edit botocore/credentials.py and change import httplib to import http.client as httplib
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/80680280
type: QuestionComment
type: Comment
has text: Oh wait, is header 2 within header1 ? Might be an idea to show how you'd expect the output `dict` to actually look
score: 0
comment on: http://stackoverflow.com/q/46866327

http://stackoverflow.com/a/46850965
downvote count: 0
has body: Taking source of table function, I come out with this from pattern.en import parse from pattern.text.tree import WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA, IOB, ROLE, MBSP, Text import pandas as pd def sentence2df(sentence, placeholder="-"): tags = [WORD, POS, IOB, CHUNK, ROLE, REL, PNP, ANCHOR, LEMMA] tags += [tag for tag in sentence.token if tag not in tags] def format(token, tag): # Returns the token tag as a string. if tag == WORD : s = token.string elif tag == POS : s = token.type elif tag == IOB : s = token.chunk and (token.index == token.chunk.start and "B" or "I") elif tag == CHUNK : s = token.chunk and token.chunk.type elif tag == ROLE : s = token.chunk and token.chunk.role elif tag == REL : s = token.chunk and token.chunk.relation and str(token.chunk.relation) elif tag == PNP : s = token.chunk and token.chunk.pnp and token.chunk.pnp.type elif tag == ANCHOR : s = token.chunk and token.chunk.anchor_id elif tag == LEMMA : s = token.lemma else : s = token.custom_tags.get(tag) return s or placeholder columns = [[format(token, tag) for token in sentence] for tag in tags] columns[3] = [columns[3][i]+(iob == "I" and " ^" or "") for i, iob in enumerate(columns[2])] del columns[2] header = ['word', 'tag', 'chunk', 'role', 'id', 'pnp', 'anchor', 'lemma']+tags[9:] if not MBSP: del columns[6] del header[6] return pd.DataFrame( [[x[i] for x in columns] for i in range(len(columns[0]))], columns=header, ) Usage &gt;&gt;&gt; string = parse('I want to go to the Restaurant as I am hungry very much') &gt;&gt;&gt; sentence = Text(string, token=[WORD, POS, CHUNK, PNP])[0] &gt;&gt;&gt; df = sentence2df(sentence) &gt;&gt;&gt; print(df) word tag chunk role id pnp lemma 0 I PRP NP - - - - 1 want VBP VP - - - - 2 to TO VP ^ - - - - 3 go VB VP ^ - - - - 4 to TO - - - - - 5 the DT NP - - - - 6 Restaurant NNP NP ^ - - - - 7 as IN PP - - PNP - 8 I PRP NP - - PNP - 9 am VBP VP - - - - 10 hungry JJ ADJP - - - - 11 very RB ADJP ^ - - - - 12 much JJ ADJP ^ - - - -
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46848343
has comment: http://stackoverflow.com/comment/80651690
answers question: http://stackoverflow.com/q/46848343
type: AcceptedAnswer

http://stackoverflow.com/a/46891184
accepted answer of: http://stackoverflow.com/q/46891001
answers question: http://stackoverflow.com/q/46891001
has comment: http://stackoverflow.com/comment/80729596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80729959
upvote count: 7
type: Answer
downvote count: 0
has body: When you pass a dictionary or callable to groupby it gets applied to an axis. I specified axis one which is columns. d = dict(A='AB', B='AB', C='CD', D='CD') df.groupby(d, axis=1).sum()
score: 7

http://stackoverflow.com/q/46856502
score: 0
has title: Python mock running in pytest crashing my instance
tagged with: mocking
has comment: http://stackoverflow.com/comment/80678699
tagged with: patch
has comment: http://stackoverflow.com/comment/80661190
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80663586
has body: I've got the following test module, running in Python 2.7 on FreeBSD: from mock import patch from t.conf import load_config @patch('t.conf._load_file') def test_open_file(mock_open): string_read = load_config('foo') print(repr(string_read)) It runs fine if I comment out the patch line. It crashes my machine after hanging for about 10 minutes if I leave it in. I'm using patch in other places without any issues. What's going on? _load_file looks like this: def _load_file(filename): with open(filename, 'rb') as f: return f.read() And load_config looks like this: def load_config(filename): text = _load_file(filename) data = yaml.safe_load(text) return data
tagged with: python
has comment: http://stackoverflow.com/comment/80733593
answer count: 0
tagged with: pytest
type: Question
has comment: http://stackoverflow.com/comment/80684766

http://stackoverflow.com/q/46870844
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46870867
has body: I have a dictionary that looks like this file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] } I want "Formation" and "Depth" to be the header, and want the file to be listed vertically in my output csv file. So, Formations Depth some1 1 some2 2 some3 3 something like this. How can this be done? Its ok that I convert depth list [1,2,3] into a string list, like ["1", "2", "3"], if thats necessary. To COLDSPEED, this is how it looks like in the output file. Formations Depth (blank) (blank) some1 1 (blank) (blank) some2 2 (blank) (blank) some3 3 (blank) here just denotes empty line with nothing. How can I fix this?
type: AnsweredQuestion
has title: export dictionary to csv file
type: Question
accepted answer: http://stackoverflow.com/a/46870867
tagged with: export
score: 0
answer count: 1

http://stackoverflow.com/q/46904162
score: 1
has comment: http://stackoverflow.com/comment/80755116
has comment: http://stackoverflow.com/comment/80757618
upvote count: 1
type: Question
has title: Can't set breakpoint within class initialization
has comment: http://stackoverflow.com/comment/80757071
tagged with: yaml
downvote count: 0
has body: I am using a custom YAML tag to define secrets in configuration. The path of the configuration key determines the path of the secret in the key store. import yaml import pdb yaml_str=""" databases: master: user: 'admin' pass: !KMS """ class KMSSecret(yaml.YAMLObject): def __repr__(self): pdb.set_trace() secret_path = '/' + '/'.join(self._find_key(config)) return secret_path def _find_key(self, data): pdb.set_trace() for key, value in data.items(): if isinstance(value, dict) or isinstance(value, list): path_item = self._find_key(value) if path_item: return [key] + path_item elif value is self: return [key] @classmethod def from_yaml(self, loader, node): return KMSSecret() yaml.add_constructor(u'!KMS', KMSSecret.from_yaml) config = yaml.load(yaml_str) Setting a breakpoint within the __repr__ or _find_key has no effect. The code must be executed at some point since inspecting the config variable after loading shows the expected representations. When adding print(config) to the end of the above snippet, the breakpoints work. I'd like to understand more about what is happening and what I should read up on.
favorite count: 0
has comment: http://stackoverflow.com/comment/80757425
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80816630
has comment: http://stackoverflow.com/comment/80757770
has comment: http://stackoverflow.com/comment/80762022
has comment: http://stackoverflow.com/comment/80777252
answer count: 0

http://stackoverflow.com/comment/80461267
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46757729
has text: im using read_pickle to read the file, the format is bz2. I was looking through the dataset but I did not see anything strange.

http://stackoverflow.com/q/46828549
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80605207
has comment: http://stackoverflow.com/comment/80605040
has comment: http://stackoverflow.com/comment/80604978
has comment: http://stackoverflow.com/comment/80605022
has comment: http://stackoverflow.com/comment/80605216
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80605804
has comment: http://stackoverflow.com/comment/80605903
has comment: http://stackoverflow.com/comment/80604880
has comment: http://stackoverflow.com/comment/80605090
has comment: http://stackoverflow.com/comment/80605031
has body: I have two Arrays. one is E which is an integer Array from 0-21. the second is E_Dist which Shows the number of elements for each index of E Array. the min and max values of E_Dist is 0-450000. I want to plot E_Dist vs E, i.e E in horizontal and E_Dist in vertical direction and fit a gaussian function to this plot. unfortunately How much I try I cannot fit a gaussian function to it. I have some Problems in fact: 1- how can I guess the Center of gaussian function correctly. I can use simply the mean value of E, which is 10, but in reality my gaussian plot Peaks about 5. I tried to use some formula like E_cen= sum(E*E_Dist)/sum(E) but now the result is much worse and is about 10e4. 2- I used two different gaussian function form one with Amplitude and another without it. I never could fit a gaussian function when I considered the Amplitude but without Amplitude I have a gaussian plot but never fit my data Points. I think one issue is that I couldn't calculate the Sigma or other gaussian Parameters correctly. another one can be the large difference of E_Dist values which covers 0 to 450000. I attached my plotanyone can help me how can I solve the Problem? Thanks in advance . ########### Gaussian fit E_cen= np.mean(E) print 'E_cen=',E_cen 10.54 mean_N = np.mean(E_Dist ) # mean number of particles print 'mean_N=',mean_N &gt;&gt;&gt;58937 sigma = np.sqrt( sum((E_Dist - mean_N)**2 )/len(E_Dist)-1 ) print 'sigma =',sigma #/1.e9,'*1.e9' &gt;&gt;&gt;119888.7 ########## # def gaus(x,a,x0,sigma): # return a*np.exp(-(x-x0)**2/(2*sigma**2)) # Gaussian function with amplitude #popt,pcov = curve_fit(gaus,E,E_Dist ,p0=[2,E_cen,sigma]) # def gaus(x,x0,sigma): return np.exp(-(x-x0)**2/(2*sigma**2)) popt,pcov = curve_fit(gaus,E,E_Dist ,p0=[E_cen,sigma]) # no amplitude ################# print 'min(popt)=',min(popt) &gt;&gt;&gt;10.54 print 'max(popt)=',max(popt) &gt;&gt;&gt;119800 print 'mean(popt)=',np.mean(popt) &gt;&gt;&gt;59940
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: fit gaussian function to a broad data

web
tags question: http://stackoverflow.com/q/46785536
tags question: http://stackoverflow.com/q/46897736
tags question: http://stackoverflow.com/q/46876826
tags question: http://stackoverflow.com/q/46868453
tags question: http://stackoverflow.com/q/46756381
tags question: http://stackoverflow.com/q/46889844
tags question: http://stackoverflow.com/q/46855255
type: Tag
tags question: http://stackoverflow.com/q/46860838
tags question: http://stackoverflow.com/q/46875205
tags question: http://stackoverflow.com/q/46755423
tags question: http://stackoverflow.com/q/46839880
tag name: web
tags question: http://stackoverflow.com/q/46750690
tags question: http://stackoverflow.com/q/46897272
tags question: http://stackoverflow.com/q/46870809
tags question: http://stackoverflow.com/q/46888128

http://stackoverflow.com/q/46888359
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/80725298
has comment: http://stackoverflow.com/comment/80741647
has comment: http://stackoverflow.com/comment/80724874
answer count: 0
type: Question
has body: this is 3rd hour of me knowing the existence of something which is called paramiko. my requirement: run a py script on windows that connects to remote linux server, executes a shell script there and take output of whatever shell script prints and return to python script and print it on python windows terminal. I am able to connect through ssh. Opening channel and session both working. Issue: SshObj.exec_command doesn't work for some commands or scripts. However, I tried with normal "ls" command. same SshObj.exec_command call is working fine. below is snippet: &gt;&gt;&gt; ssh = paramiko.SSHClient() &gt;&gt;&gt; ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) &gt;&gt;&gt; ssh.connect(IP,22,usname,pswd) &gt;&gt;&gt; stdin, stdout, stderr = ssh.exec_command('/home/scripts/a.sh') &gt;&gt;&gt; stdout.channel.recv_ready() False &gt;&gt;&gt; stdout.channel.recv_ready() False &gt;&gt;&gt; stdin, stdout, stderr = ssh.exec_command('/home/scripts/a.sh') &gt;&gt;&gt; stdin, stdout, stderr = ssh.exec_command('ls') &gt;&gt;&gt; stdout.channel.recv_ready() True
has title: paramiko object method exec_command doesn't execute shell script
tagged with: paramiko
score: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/80726014
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80740299

http://stackoverflow.com/q/46831437
has answer: http://stackoverflow.com/a/46831629
has answer: http://stackoverflow.com/a/67803446
has comment: http://stackoverflow.com/comment/80610370
type: AnsweredQuestion
score: -1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46831618
has comment: http://stackoverflow.com/comment/80610311
has answer: http://stackoverflow.com/a/46831591
possible better answer: http://stackoverflow.com/a/46831629
answer count: 6
has title: How to remove characters which are coming after point?
favorite count: 0
has answer: http://stackoverflow.com/a/46831722
downvote count: 3
has body: I am trying to remove characters which are coming after point. There are 6 characters after point. It is not changing. Input (String) : 52.01317215 1121.53601074 1049.63146973 1540.70495605 517.47277832 85.62935638 553.46118164 106.97449493 1.70361996 550.58435059 159.12145996 714.25854492 Output (String) (what i want): 52 1121 1049 1540 517 85 553 106 1 550 159 714 Any help would be appreciated...
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80610443
has comment: http://stackoverflow.com/comment/80610484
has answer: http://stackoverflow.com/a/46831602
accepted answer: http://stackoverflow.com/a/46831602

http://stackoverflow.com/comment/80702617
has text: yes scrapping all pages in same loop. and hence results prints just the last page scrapped.
comment on: http://stackoverflow.com/a/46877636
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80754151
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46903654
has text: Are you using python 2 or 3?

http://stackoverflow.com/q/46872930
has answer: http://stackoverflow.com/a/46872953
type: Question
has comment: http://stackoverflow.com/comment/80693074
score: -2
tagged with: class-attributes
tagged with: class
has comment: http://stackoverflow.com/comment/80692961
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/80693011
tagged with: attributes
favorite count: 0
has title: Update an attribute each time the class constructor is invoked
tagged with: python
accepted answer: http://stackoverflow.com/a/46872953
has comment: http://stackoverflow.com/comment/80693046
has comment: http://stackoverflow.com/comment/80693092
type: AnsweredQuestion
upvote count: 0
has body: I have this class in Python. (Removed the unecessary parts) class Spillebrett: def __init__(self, rader, kolonner): self._rader = rader self._kolonner = kolonner self._generasjonsnummer = 0 I need to add 1 to _generasjonsnummer everytime i run the class. If i try _generasjonsnummer += 1 i get an error. I tried to make a def addGenerasjonsnummer() and call it in the init like so: class Spillebrett: def __init__(self, rader, kolonner): self._rader = rader self._kolonner = kolonner self._generasjonsnummer = 0 addGenerasjonsnummer() def addGenerasjonsnummer(): self._generasjonsnummer += 1 But i cant call on functions in the init. What i need is for this number to update to +=1 each time i start the init, how do i do this?

http://stackoverflow.com/comment/83417372
type: QuestionComment
score: 2
has text: `data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'` does make a difference, `retrain.py` would interpret the filename of your model to `inception-2015-12-05.tgz`, so it would still use inception_v3 rather than inception_v4.
comment on: http://stackoverflow.com/q/46829684
type: Comment

http://stackoverflow.com/q/46826497
downvote count: 0
has answer: http://stackoverflow.com/a/46833531
favorite count: 0
has body: I have an installation of miniconda3 where I have created a virtual environment called py35. I have some libraries that I only want to use from within this environment. hence they are under /.../miniconda3/envs/py35/libs However they are not found from within the environment as LD_LIBRARY_PATH does not contain said folder. I now want to set LD_LIBRARY_PATH to include the /lib only when I am in the virtual environment. I was thinking of modifying the activate script miniconda uses to start the environment but am not quite sure if this is standard practice or if there is an easier way to achieve this.
has title: Conda set LD_LIBRARY_PATH for env only
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
has answer: http://stackoverflow.com/a/49238956
accepted answer: http://stackoverflow.com/a/46833531
type: Question
possible better answer: http://stackoverflow.com/a/49238956
duplicate of: http://stackoverflow.com/q/31598963
tagged with: virtualenv
score: 42
tagged with: conda
upvote count: 42
answer count: 2

http://stackoverflow.com/comment/80521046
comment on: http://stackoverflow.com/q/46787345
type: Comment
type: QuestionComment
score: 1
has text: If working with floats, it is not guaranteed that if `(str(a) == str(b))` (the rendered values look equal), then `(a - b) == 0`. Maybe you should try to set `tol_2` to something like 1e-6 and test if `abs(a1_SC - a2_SC) <= tol_2`

http://stackoverflow.com/a/46877206
answers question: http://stackoverflow.com/q/46876976
has comment: http://stackoverflow.com/comment/80701476
has body: Not elegant, but seems working: not var.__class__.__name__=='A'
score: 0
has comment: http://stackoverflow.com/comment/80701444
type: Answer
has comment: http://stackoverflow.com/comment/80701356
has comment: http://stackoverflow.com/comment/80701466
has comment: http://stackoverflow.com/comment/80701494

generator-expression
tags question: http://stackoverflow.com/q/46767818
type: Tag
tag name: generator-expression

http://stackoverflow.com/q/46770189
has answer: http://stackoverflow.com/a/59004889
type: Question
score: 5
upvote count: 5
has body: I was after some help configuring server side on_change events to trigger when a plot is zoomed. I have a large 2D array of data (5000, >1000000), which I wish to visualise as an image using bokeh. As such, I am resizing the data (skimage.transform.resize) to the bokeh plot width and height. I am trying to use an on_change function to call the resize when the plot is zoomed, panned or reset. I've attached a callback to the plot x_range and y_ranges to trigger on start and end changes. But this (understandably) causes the resize callback to be triggered 4 times on each zoom event. It is possible and desirable to be able to trigger a resize event on any subset of the range changes (a zoom may not change the y_range.end for instance), so I cannot simply wait for all on_change events to be calculated. Example code: import bokeh.plotting as bk from bokeh.application.handlers import FunctionHandler from bokeh.application import Application from bokeh.models import LinearColorMapper, ColumnDataSource from skimage.transform import resize import numpy as np import xarray as xa bk.output_notebook() # Create a simple array image - basically lifted from https://docs.bokeh.org/en/latest/docs/gallery/image.html N = 5000 x = np.linspace(0, 10*np.pi, N) y = np.linspace(0, 10*np.pi, N) xx, yy = np.meshgrid(x, y) d = np.sin(xx)*np.cos(yy) # Using xarray as this is the array handling object of choice in production code array = xa.DataArray(data = d, coords = (x, y), dims = ('x', 'y')) class Plot(): def __init__(self, array, width = 800, height = 800): # Probably unecessary, but done for syntactic familiarity self.tla = array.to_pandas() xrange = self.tla.index yrange = self.tla.columns # Configure plot object self.p = bk.figure(height = height, width = width, x_range = (xrange.min(), xrange.max()), y_range = (yrange.max(), yrange.min())) # Create ColoumnDataSource object with the resized input array, no arguments passed to # simplify its use during callback self.source = ColumnDataSou…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
has title: Bokeh - Triggering on_change callback from BoxZoomTool/ResetTool
type: UnansweredQuestion
tagged with: python
tagged with: bokeh

http://stackoverflow.com/comment/80659223
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46855838
has text: Much better, imo
score: 0

http://stackoverflow.com/comment/80667888
has text: OK, I have added the code that gets generated.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46859945

http://stackoverflow.com/a/46880615
has comment: http://stackoverflow.com/comment/80742871
score: 0
has comment: http://stackoverflow.com/comment/80711562
type: Answer
answers question: http://stackoverflow.com/q/46876336
has body: List Comprehensions are the pythonic way to loop through the items in a list and create a new list from operations on the input list's elements alast = [e[-1] for e in adjList] ['Yes' if (d[0] in alast) and set(d).issubset(adjList[alast.index(d[0])]) else 'No' for d in integer_data] ['Yes', 'No', 'No', 'No', 'No'] the 1st listcomp makes a list of the last number e[-1] in each sublist e of adjList the second block is actually a single list comprehension (with added line breaks) that takes the sublists d from integer_data in the last line: for d in integer_data the inline if-else of the 1st 3 lines gives 'Yes' or 'No' based on the logic split between the 1st and 2nd lines the 1st line of logic (d[0] in alast) is pretty obvious the 2nd line of the logical epression "and-ed" with the 1st checks if all of the numbers in d are in the matched index alast.index(d[0]) sublist of adjList using python's set built-in object's .issubset() method logic

http://stackoverflow.com/a/46781051
answers question: http://stackoverflow.com/q/46780987
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46780987
has comment: http://stackoverflow.com/comment/80508635
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80508729
downvote count: 0
has body: You could use df.index.intersection to find common indexes, and then use loc to access all relevant rows and add. idx = df1.index.intersection(df2.index) df2.loc[idx, 'Cash'] += df1.loc[idx, 'Cash'] print(df2) GOOG AAPL XOM IBM Cash 2011-01-10 0.0 0.0 0.0 0.0 -5134.75 2011-01-11 0.0 0.0 0.0 0.0 -5000.85

http://stackoverflow.com/comment/80580497
type: AnswerComment
has text: Well, I mean you'd still have to wrap it in `pd.Series`,but i mean instead of using `df.index` and `df.columns`, since I *think* the OP wants those to be arbitrary, i.e. `ind = [0, 1, 1]`
type: Comment
comment on: http://stackoverflow.com/a/46816505
score: 0

http://stackoverflow.com/comment/80457443
score: 0
comment on: http://stackoverflow.com/q/46756034
type: QuestionComment
type: Comment
has text: have you considered `from TestProg import Name, testfunc` ?

http://stackoverflow.com/a/46795852
has comment: http://stackoverflow.com/comment/80538336
accepted answer of: http://stackoverflow.com/q/46795816
has comment: http://stackoverflow.com/comment/80538631
has comment: http://stackoverflow.com/comment/80538313
downvote count: 0
answers question: http://stackoverflow.com/q/46795816
score: 6
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80538381
has body: Is there any reason I shouldn't use the syntax in Baz? Yes, there is a reason you shouldn't use that syntax. If you subclass from Baz, the super() call will resolve back to Baz.whee() and you'll get stuck in an infinite loop. This also applies to the syntax super(type(self), self).whee(). (Well, actually you will blow the recursion limit and error out. But either way it's a problem.)
type: Answer
upvote count: 6

http://stackoverflow.com/q/46759741
tagged with: spyder
tagged with: python
has body: When I run my python code from a console, everything works fine: I get one new tensorboard file (626 bytes) every time and I can look it up using the Tensorboard service. But, when I run this code from Spyder IDE, after every run there is a new file that contains data from all the runs made in Spyder since it's started. After 10 runs executed in Spyder, even when I shut down tensorboard server and delete dir with logs, after 11th run there will be a new file with approximately 6K size, containg all of the previous runs. import tensorflow as tf a = tf.constant(2,name ='a') b = tf.constant(3,name = 'b') x = tf.add(a, b) with tf.Session() as sess: # add this line to use TensorBoard. writer = tf.summary.FileWriter('./graphs', sess.graph) print (sess.run(x)) writer.close() # close the writer when you’re done using i After Spyder restart whole story starts again, first run produces correct result, while second already contains its predecessor data. Spyder IDE does some caching or what?
tagged with: machine-learning
has title: Spyder appends Tensorboard summary files
tagged with: tensorflow
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/46895760
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46895760
tagged with: tensorboard

http://stackoverflow.com/comment/80694479
has text: We had a [tag:best-practices] tag that we burninated. This question falls outside the scope of questions that are on topic as described in the help centre. As a user with nearly 1k rep, you should know that...
comment on: http://stackoverflow.com/q/46873692
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46751486
favorite count: 0
has answer: http://stackoverflow.com/a/46751541
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/46751500
has answer: http://stackoverflow.com/a/46751511
upvote count: 3
answer count: 3
accepted answer: http://stackoverflow.com/a/46751541
possible better answer: http://stackoverflow.com/a/46751511
has comment: http://stackoverflow.com/comment/80448902
has title: Python: Concatenate 3 lists into csv file?
type: AnsweredQuestion
score: 3
has body: I have three lists: name = ['rob', 'mike', 'bob'] age = ['19, '32', '88'] id = ['aaa', 'bbb', 'ccc'] Is there a way to concatenate these vertically and get a CSV as below? rob, 19, aaa mike, 32, bbb bob, 88, ccc
downvote count: 0

http://stackoverflow.com/comment/80464863
has text: This yields the combinations that have not yet been used. But how do I search through this new set (that does not contain the discounted groups) and create a set of [total students /2] (here 8) groups of students. This is what I am struggling with.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46759698
type: Comment

http://stackoverflow.com/a/46828253
downvote count: 0
answers question: http://stackoverflow.com/q/46827888
type: Answer
has body: It is possible that pip is installing the module in a foreign directory to the python version you run your script with. Try specifying the python version by appending the version number to the terminal command as such python3.6 -m pip install discord.py. If that doesn't work try using pip3 instead of pip. edit: Also do not try to install asyncio, it's part of the standard library.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46827888
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/46864799
has body: from tkinter import * import random tk = Tk() canvas = Canvas(tk, width=400, height=400) canvas.pack() for x in range(0, 40): x1 = random.randint(0,400) y1 = random.randint(0,400) x2 = random.randint(0,400) y2 = random.randint(0,400) x3 = random.randint(0,400) y3 = random.randint(0,400) my_triangle = canvas.create_polygon(x1, y1, x2, y2, x3, y3,\ fill =("blue"), outline="red") Hi! I am playing with tkinter and generating random triangles. The problem is: I want to use random on fill = " " to generate random colors random.randint(start, end) returns numbers, but fill accepts only strings like fill ="red" or hexadecimal = "#RGB" if I enter a numeric valuer like fill = (1,1,0) it doesn't work. How could I generate random string values in fill? Thank you
has title: Python Tkinter random generating the colors?
has comment: http://stackoverflow.com/comment/80677026
downvote count: 0
has answer: http://stackoverflow.com/a/46865398
favorite count: 0
tagged with: colors
tagged with: python
linked to: http://stackoverflow.com/q/4969543
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46865257
score: 1
tagged with: fill
answer count: 2

http://stackoverflow.com/comment/80467255
type: Comment
has text: Python has the in-built [`collections.Counter()`](https://docs.python.org/3/library/collections.html#collections.Counter) to achieve the same task
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46760775

http://stackoverflow.com/comment/80448477
has text: So I had read through that earlier and correct me if I'm wrong, but that code snippet only finds the longest common substring if it starts at the start of the word, in my case it may be anywhere in the word. I'm guessing I'm going to have to create another for loop in that to account for a sliding start point...
score: 1
comment on: http://stackoverflow.com/q/46751236
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46898217
tagged with: view
type: UnansweredQuestion
score: 1
has body: My question is based on this example given in the Django documentation. My models.py looks like this: class Wrestler(models.Model): name = CharField(max_length=255) class AlterEgo(models.Model): name = CharField(max_length=255) person = ForeignKey('someapp.Person', ) class Group(models.Model): name = CharField(max_length=255) members = models.ManyToManyField('someapp.Person', through='Membership') class Membership(models.Model): person= models.ForeignKey('someapp.Person',) alter_ego = models.ForeignKey('someapp.AlterEgo', blank=True, null=True) group = models.ForeignKey('someap.Group',) My group list template looks like this: {% for object in object_list %} {{ object.name }} {% endfor %} As you can see, my extra field is the "alter_ego" one. Every person can have an alter ego, e. g. Chris Jericho used to perform as Moongoose McQueen. With this template, members would be listed as "Chris Jericho & Richard Ward & ...". My problem is I don't want Jericho to be listed as Jericho but as McQueen if an alter ego is given. I guess there should me a custom function replacing my person FK if an alter ego is given but I'm still trying to wrap my head around it as I'm really a noob regarding all this. If someone could point me in the right direction I'd greatly appreciate it. Thanks in advance.
tagged with: django
has comment: http://stackoverflow.com/comment/80744343
has answer: http://stackoverflow.com/a/46898724
has comment: http://stackoverflow.com/comment/80743900
tagged with: django-managers
has title: Return extra fields of many-to-many relationship instead of another
type: Question
upvote count: 1
tagged with: function
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/80607292
comment on: http://stackoverflow.com/q/46829989
has text: `paramiko` is the way. What's wrong with it? From the python docs: "Paramiko is a native Python implementation of SSH. "
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46776610
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80500976
tagged with: python
has comment: http://stackoverflow.com/comment/80501441
has comment: http://stackoverflow.com/comment/80502309
tagged with: selenium-webdriver
answer count: 0
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/80499585
tagged with: web-scraping
upvote count: 1
type: Question
has title: DuckDuckGo giving error while running through selenium
has comment: http://stackoverflow.com/comment/80500570
score: 1
has body: I am providing search values to input into search box in DuckDuckGo from a csv file (with approx. 5000 rows) and using a loop trying to return the url of the first result from DuckDuckGo for all the rows using selenium. The program runs fine for about 400 rows or so but after a few hundred iterations of the program, I noticed DuckDuckGo gives the following error: “Oops, there was an error. Please try again. If it persists, please email error@duckduckgo.com" Screenshot of the error page I am wondering why it gives the error after a few hundred iterations. Any help/suggestion is appreciated.

http://stackoverflow.com/q/46767903
has answer: http://stackoverflow.com/a/46769104
has body: I try to validate document using Schematron. I use schema for ISOSTS standard. from lxml import etree from lxml.isoschematron import Schematron def validate(self, filename: str): file = open(filename) schema_filename = join('/path/to/ISOSTS_validation.sch') schema_file = open(schema_filename) # fixme it works. But fails with ISOSTS scheme # schema_file = StringIO('''\ # # # Sum equals 100%. # # Sum is not 100%. # # # # ''') sct_doc = etree.parse(schema_file) schematron = Schematron(sct_doc) ## <- FAIL !!! doc = etree.parse(file) result = schematron.validate(doc) file.close() schema_file.close() return result validate('/path/to/feature_doc.xml') Error message: File "/var/www/.../venv/lib/python3.5/site-packages/lxml/isoschematron/__init__.py", line 279, in __init__ schematron_schema_valid.error_log) lxml.etree.SchematronParseError: invalid schematron schema: <string>:553:0:ERROR:RELAXNGV:RELAXNG_ERR_EXTRACONTENT: Element function has extra content: param <string>:560:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMNAME: Expecting element schema, got variable <string>:0:0:ERROR:RELAXNGV:RELAXNG_ERR_INTEREXTRA: Extra element function in interleave <string>:42:0:ERROR:RELAXNGV:RELAXNG_ERR_CONTENTVALID: Element schema failed to validate content How to repair it?
tagged with: schematron
answer count: 2
upvote count: 1
type: UnansweredQuestion
has title: SchematronParseError: invalid schematron schema (for ISOSTS schema)
tagged with: lxml
has answer: http://stackoverflow.com/a/46768958
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/80611692
type: QuestionComment
score: 0
has text: I am no expert in `threading` nor `multiprocessing` too... Could you pls provide an example or solution using `multiprocessing` if possible? Appreciated!!
comment on: http://stackoverflow.com/q/46832024
type: Comment

http://stackoverflow.com/comment/80692624
type: AnswerComment
type: Comment
has text: I've resolve it, I need to add a commit and it should be `not path.endswith("\n")`
score: 1
comment on: http://stackoverflow.com/a/46872391

http://stackoverflow.com/q/46888842
tagged with: python
answer count: 0
downvote count: 0
score: 1
tagged with: machine-learning
has body: I am not able to pickle my model below. import numpy as np import matplotlib.pyplot as plt import pandas as pd import os script_dir = os.path.dirname(__file__) abs_file_path = os.path.join(script_dir, 'Churn_Modelling.csv') # Importing the dataset dataset = pd.read_csv(abs_file_path) X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features=[1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Part 2 - Now let's make the ANN! # Importing the Keras libraries and packages from tensorflow.contrib.keras.api.keras.models import Sequential from tensorflow.contrib.keras.api.keras.layers import Dense from tensorflow.contrib.keras import backend # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu', input_dim=11)) # Adding the second hidden layer classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu')) # Adding the output layer classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid')) # Compiling the ANN classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Fitting the ANN to the Training set classifier.fit(X_train, y_train, batch_size=10, epochs=100, validation_split=0.1) # Part 3 - Making predictions…
type: Question
has title: Error pickling scikit-learn model
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: pickle

http://stackoverflow.com/a/46868885
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46868526
upvote count: 6
answers question: http://stackoverflow.com/q/46868526
has comment: http://stackoverflow.com/comment/80693539
type: Answer
has comment: http://stackoverflow.com/comment/80685010
has body: Python's Standard Library is called the Standard Library because it is a standard of Python. In other words, if there is no Standard Library installed, the python environment is not python at all. The Standard Library is tested and released together with each Python release as part of this release (not as an addition or extension). So, YES, you can expect these libraries to exist if the user has Python installed. Just by definition. Regarding the upgrades of the built-in libraries: NO, you cannot do this. Because they are part of the python setup, not of the application environment. Python is very tightly bound to the specific code in those libraries. All python apps &amp; libs expect the same behavior of those libraries, even if they are buggy. In addition to that, you cannot install a module/package with the same name as one of the python's builtins, because it will create the ambiguity on import, and can confuse/break all other libraries which depend on it (or worse, the system applications if you install it into the system python). However, in some cases you can find the backports of some of the libraries. Usually, they are backported from py3 to py2. Of course, their name is changed. As an example, you can look into concurrent.features library, which is a handy builtin in py3.2+, but was absent in py2.7. UPD: Though, as @JulienPalard hints in the comments, some OS distributions can split this standard library to simplify the binary dependencies: e.g., on Debian, Tkinter will be installable separately as python3-tk. This makes sense, indeed, from the point of view of the binary OS packaging: it is not worth installing the UI parts of the python library if you have no UI at all and want to save the disk space. However, you are still unable to install it via pip. Because this package is not packaged and available separately on PyPI. This standard library separation is made by the selected OS distributions and is resolved with the means of that OS distribution only…
score: 6
has comment: http://stackoverflow.com/comment/80685090
downvote count: 0
has comment: http://stackoverflow.com/comment/80685930

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

http://stackoverflow.com/a/46832462
has comment: http://stackoverflow.com/comment/80614788
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I hope this will resolve the issue with open(filename, encoding="cp437") as file: But if your file's encoding type is not cp437 and something else apart from that and if your using notepad++ to view your file, you can check its encoding type by clicking on Encoding, which will show the type of encoding. If your using sublime text go to View -> Show Console Type into field at bottom view.encoding() and it will give you the encoding type.
has comment: http://stackoverflow.com/comment/80614881
answers question: http://stackoverflow.com/q/46832127
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46832127

http://stackoverflow.com/comment/80721212
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/46887030
has text: Note, this really isn't how you write Python code; it looks more like Java. In Python you would define a `__str__` method, and then call `str(pitbull)`.

http://stackoverflow.com/q/46751326
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has title: How to concatenate Pandas Dataframe columns dynamically?
score: 1
has answer: http://stackoverflow.com/a/46751947
has answer: http://stackoverflow.com/a/46751356
has body: I have a dataframe df (see program below) whose column names and number are not fixed. However, there is a list ls which will have the list of columns of df that needs to be appended together. I tried df['combined'] = df[ls].apply(lambda x: '{}{}{}'.format(x[0], x[1], x[2]), axis=1) but here I am assuming that the list ls has 3 elements which is hard coding and incorrect.What if the list has 10 elements.. I want to dynamically read the list and append the columns of the dataframe. import pandas as pd def main(): df = pd.DataFrame({ 'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7], 'col_3': [14, 15, 16, 19], 'col_4': [22, 23, 24, 25], 'col_5': [30, 31, 32, 33], }) ls = ['col_1','col_4', 'col_3'] df['combined'] = df[ls].apply(lambda x: '{}{}'.format(x[0], x[1]), axis=1) print(df) if __name__ == '__main__': main()
type: Question
answer count: 2
downvote count: 0
tagged with: python-2.7
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/46838747
linked to: http://stackoverflow.com/q/20136955
tagged with: django
tagged with: python
has title: NameError for defined class variable
score: 2
answer count: 0
duplicate of: http://stackoverflow.com/q/13905741
has comment: http://stackoverflow.com/comment/80625519
type: Question
duplicate of: http://stackoverflow.com/q/20136955
tagged with: class
tagged with: scope
has body: Below, the artifact_urls class variable is clearly defined, and there is no problem referencing it in a print statement or dict constant, but referencing it from within a list comprehension raises a NameError. Why?!?! Here's the code and output. from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) class Constants(BaseConstants): artifact_urls = ["Hello, world!"] print(artifact_urls) artifact_const = { "url": artifact_urls[0] } artifact_const = [{ "url": artifact_urls[i] } for i in range(1)] Output: ['Hello, world!'] Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x1085426a8&gt; Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen impo…
downvote count: 0
tagged with: otree
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/46868855
has answer: http://stackoverflow.com/a/46870227
has title: Numpy: Replacing values in a 2D array efficiently using a dictionary as a map
tagged with: arrays
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46868996
possible better answer: http://stackoverflow.com/a/46868897
answer count: 5
has comment: http://stackoverflow.com/comment/80705727
has answer: http://stackoverflow.com/a/46868897
has comment: http://stackoverflow.com/comment/80685401
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80685330
type: AnsweredQuestion
has body: I have a 2D Numpy array of integers like so: a = np.array([[ 3, 0, 2, -1], [ 1, 255, 1, 2], [ 0, 3, 2, 2]]) and I have a dictionary with integer keys and values that I would like to use to replace the values of a with new values. The dict might look like this: d = {0: 1, 1: 2, 2: 3, 3: 4, -1: 0, 255: 0} I want to replace the values of a that match a key in d with the corresponding value in d. In other words, d defines a map between old (current) and new (desired) values in a. The outcome for the toy example above would be this: a_new = np.array([[ 4, 1, 3, 0], [ 2, 0, 2, 3], [ 1, 4, 3, 3]]) What would be an efficient way to implement this? This is a toy example, but in practice the array will be large, its shape will be e.g. (1024, 2048), and the dictionary will have on the order of dozens of elements (34 in my case), and while the keys are integers, they are not necessarily all consecutive and they can be negative (like in the example above). I need to perform this replacement on hundreds of thousands of such arrays, so it needs to be fast. However, the dictionary is known in advance and remains constant, so asymptotically, any time used to modify the dictionary or transform it into a more appropriate data structure doesn't matter. I'm currently looping over the array entries in two nested for loops (over the rows and columns of a), but there has got to be a better way. If the map didn't contain negative values (e.g. -1 like in the example), I would just create a list or an array from the dictionary once where the keys are the array indices and then use that for an efficient Numpy fancy indexing routine. But since there are negative values, too, this won't work.
has comment: http://stackoverflow.com/comment/80698450
accepted answer: http://stackoverflow.com/a/46868996
has comment: http://stackoverflow.com/comment/80697583
type: Question
has comment: http://stackoverflow.com/comment/80700025
linked to: http://stackoverflow.com/q/3403973
has answer: http://stackoverflow.com/a/68451627
has comment: http://stackoverflow.com/comment/80717878
has comment: http://stackoverflow.com/comment/80698327
score: 15
has comment: http://stackoverflow.com/comment/80685240
has comment: http://stackoverflow.com/comment/80685541
tagged with: numpy
upvote count: 15
has answer: http://stackoverflow.com/a/46869289

http://stackoverflow.com/comment/80638633
score: 0
type: AnswerComment
has text: Any time, glad I could help :)
type: Comment
comment on: http://stackoverflow.com/a/46845080

http://stackoverflow.com/a/46756209
accepted answer of: http://stackoverflow.com/q/46756154
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46756154
type: AcceptedAnswer
downvote count: 0
has body: You were quite close with your regex. After the position found by the lookbehind, you just want to read up to the next &lt;: (?&lt;=&lt;/span&gt;)[^&lt;]+ Check it out on regex101 $ cat test.py import re s='&lt;/span&gt;A walk in the park&lt;span class="html-tag"' print re.findall(r'(?&lt;=&lt;/span&gt;)[^&lt;]+', s) $ python test.py ['A walk in the park']
type: Answer

http://stackoverflow.com/q/46788681
favorite count: 0
has body: I am trying to establish a long running Pull subscription to a Google Cloud PubSub topic. I am using a code very similar to the example given in the documentation here, i.e.: def receive_messages(project, subscription_name): """Receives messages from a pull subscription.""" subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path( project, subscription_name) def callback(message): print('Received message: {}'.format(message)) message.ack() subscriber.subscribe(subscription_path, callback=callback) # The subscriber is non-blocking, so we must keep the main thread from # exiting to allow it to process messages in the background. print('Listening for messages on {}'.format(subscription_path)) while True: time.sleep(60) The problem is that I'm receiving the following traceback sometimes: Exception in thread Consumer helper: consume bidirectional stream: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/path/to/google/cloud/pubsub_v1/subscriber/_consumer.py", line 248, in _blocking_consume self._policy.on_exception(exc) File "/path/to/google/cloud/pubsub_v1/subscriber/policy/thread.py", line 135, in on_exception raise exception File "/path/to/google/cloud/pubsub_v1/subscriber/_consumer.py", line 234, in _blocking_consume for response in response_generator: File "/path/to/grpc/_channel.py", line 348, in __next__ return self._next() File "/path/to/grpc/_channel.py", line 342, in _next raise self grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.UNAVAILABLE, The service was unable to fulfill your request. Please try again. [code=8a75])&gt; I saw that this was referenced in another question but here I am asking to how to handle it properly in Python. I have tried to wrap the request in an exception but it seems to run in the background and …
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46840983
type: Question
downvote count: 0
has title: Google PubSub python client returning StatusCode.UNAVAILABLE
linked to: http://stackoverflow.com/q/42638468
accepted answer: http://stackoverflow.com/a/46840983
tagged with: google-cloud-pubsub
answer count: 1

http://stackoverflow.com/a/46889742
answers question: http://stackoverflow.com/q/46884770
has comment: http://stackoverflow.com/comment/80790158
downvote count: 0
score: 1
has body: EDIT: This lines causes the error: labeledData += ld += operand doesn't work for zips. You can change zips to list. def getLabeledDataVector(dataset, clazz, label): ... return list(output) Also, unzipped list can be empty, you should fix this line too(Thanks to ShadowRanger for comment): labels, data = unzipped if unzipped else ([], []) This changes probably will affect your code's logic. You should fix them on your own. BEFORE EDIT: In getData(generateTuningData) function, ROOT_DIR + clazz expression causes the error, because ROOT_DIR is None. sys.path.append doesn't return anything(returns None). You need to change your code as: ... import os.path ... sys.path.append("../train/") ROOT_DIR = os.path.dirname(os.getcwd()) + "/train/" # parent directory and "/train/" ... I assumed ROOT_DIR is your current working directory's parent + "/train/". If it is not, you can fix it. Also, there may be other problems, but this solves unsupported operand type(s).
upvote count: 1
type: Answer

http://stackoverflow.com/comment/80637476
type: QuestionComment
comment on: http://stackoverflow.com/q/46844950
has text: Can you elaborate on what you've already tried?
score: 0
type: Comment

http://stackoverflow.com/comment/80484906
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46769776
type: Comment
has text: Is Python a requirement? You can do this with Excel itself. Write `=IF($A2 >= $B2;"OK";"Verify")` in `C2` and then extend it to the whole column. If you really need Python you should export the excel data as a csv from excel itself or use a tool that can read excel files.

smtplib
tags question: http://stackoverflow.com/q/46858273
type: Tag
tag name: smtplib
tags question: http://stackoverflow.com/q/46800562
tags question: http://stackoverflow.com/q/46827020

http://stackoverflow.com/comment/80656301
type: AnswerComment
score: 1
type: Comment
has text: Yikes, that sounds troublesome. I agree that top-level modules with overlapping names should be blocked. For submodules, I think it's okay, e.g. `import mypackage.os`.
comment on: http://stackoverflow.com/a/46853292

http://stackoverflow.com/q/46888809
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80724818
has comment: http://stackoverflow.com/comment/80789257
tagged with: scrapinghub
tagged with: scrapy
has answer: http://stackoverflow.com/a/46898596
type: Question
has comment: http://stackoverflow.com/comment/80735147
has comment: http://stackoverflow.com/comment/80725439
has comment: http://stackoverflow.com/comment/80739384
has title: text substitution {} does not work at scrapinghub
score: 0
has body: I create a url with {} format to change the url on the fly. It works totally fine on my PC. But once I upload and run it from scrapinghub one(state) of the many substitutions(others work fine) does not work, it returns %7B%7D&amp; in the url which is encoded curly braces. Why does this happen? What do I miss when referencing State variable? This is the url from my code: def __init__(self): self.state = 'AL' self.zip = '35204' self.tax_rate = 0 self.years = [2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017] def parse_m(self, response): r = json.loads(response.text) models = r['models'] year = response.meta['year'] make = response.meta['make'] for model in models: for milage in [40000,50000,60000,70000,80000,90000,100000]: url = '****/vehicles/?year={}&amp;make={}&amp;model={}&amp;state={}&amp;mileage={}&amp;zip={}'.format(year,make, model, self.state, milage, self.zip) and this is the url i see in the log of scrapinghub: ***/vehicles/?year=2010&amp;make=LOTUS&amp;model=EXIGE%20S&amp;state=%7B%7D&amp;mileage=100000&amp;zip=35204

http://stackoverflow.com/comment/80734174
score: 0
has text: You could try acquiring some data using the `raspivid` command-line and seeing if you can play that back on another system, to see if the data really are corrupt.
comment on: http://stackoverflow.com/q/46891359
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80693162
has text: does your actual csv look like that? or commas as a separator? or you use a spreadsheet to input the value? because csv shouldn't look like that, it should look like `frame.number,frame.len,frame.cap_len,frame.Type` and is separated by commas.
score: 1
comment on: http://stackoverflow.com/q/46872971
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80599424
has text: Maybe this stackoverflow link [Imshow: extent and aspect](https://stackoverflow.com/questions/13384653/imshow-extent-and-aspect) answers your question
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46825924
score: 1

http://stackoverflow.com/comment/80545142
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46799018
has text: @CoryKramer [this](https://stackoverflow.com/a/46350322/4799172) was the answer I intended to link to, but there has to be a better target for this kind of question (`self` being included in the argument count).

http://stackoverflow.com/comment/80576329
type: QuestionComment
has text: All the entries in the Title column are unique. Regarding the Content column, I want the Title entry to match the first found match in the Content entry.
comment on: http://stackoverflow.com/q/46814225
score: 0
type: Comment

http://stackoverflow.com/comment/80520966
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46787231
type: Comment
has text: Thanks for the comment, please see ammended - sorry I forgot the brackets encapsulating it! Yes, at the moment there is always a comma

http://stackoverflow.com/q/46766166
type: Question
score: -1
has answer: http://stackoverflow.com/a/46766377
has answer: http://stackoverflow.com/a/46766438
has answer: http://stackoverflow.com/a/46766564
tagged with: string
favorite count: 0
answer count: 5
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/11520492
has body: I want to make a function called remove_short_synonyms() which is passed a dict as a parameter. The keys of the parameter dict are words and the corresponding values are lists of synonyms. The function removes all the synonyms which have less than 7 characters from each corresponding list of synonyms. If this is the dict: synonyms_dict = {'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']} How can I get this as the output? {'beautiful': ['dazzling', 'handsome', 'magnificent', 'splendid']}
tagged with: list
has title: How to remove short strings from a list which is a value of a dict
has answer: http://stackoverflow.com/a/46766522
has answer: http://stackoverflow.com/a/46766427
upvote count: 1

integer-division
tags question: http://stackoverflow.com/q/46749191
type: Tag
tag name: integer-division

http://stackoverflow.com/a/46865921
upvote count: 1
answers question: http://stackoverflow.com/q/46865587
has body: If you just want a grid of fixed strings you don't need any loops, you can just use string and list multiplication, and the string .join method to join the rows of the grid together for printing. size = 5 row = " O " * size grid = [row] * size print('\n'.join(grid)) output O O O O O O O O O O O O O O O O O O O O O O O O O
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/46877471
score: 2
has body: Yes, Python supports multiple return values for functions by separating the return values with commas. e.g., def foo(): return 1, 2, 3 a, b, c = foo() Where printing a, b, and c respectively gives the following: &gt;&gt;&gt; print(a) 1 &gt;&gt;&gt; print(b) 2 &gt;&gt;&gt; print(c) 3
answers question: http://stackoverflow.com/q/46877409
downvote count: 2
type: Answer
upvote count: 4

http://stackoverflow.com/q/46803155
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46803222
has title: How to replace values in pandas data frame according to a function
linked to: http://stackoverflow.com/q/46841519
favorite count: 0
linked to: http://stackoverflow.com/q/21316968
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46822149
possible better answer: http://stackoverflow.com/a/46856076
has answer: http://stackoverflow.com/a/46856076
tagged with: dataframe
has answer: http://stackoverflow.com/a/46803222
has body: I have a pandas data frame it looks like this 0 1 2 3 4 5 6 7 8 9 ... 253 254 255 256 257 258 259 260 261 262 0 30 84 126 135 137 179 242 342 426 ... 0 0 0 0 0 0 0 0 0 0 1 24 53 75 134 158 192 194 211 213 ... 0 0 0 0 0 0 0 0 0 0 2 51 143 173 257 446 491 504 510 559 ... 0 0 0 0 0 0 0 0 0 0 3 1 20 22 92 124 149 211 335 387 ... 0 0 0 0 0 0 0 0 0 0 4 34 51 56 106 110 121 163 233 266 ... 0 0 0 0 0 0 0 0 0 0 I want to divide each number in the data frame by 7 and put the result in the data frame instead of the number, I was testing with a for loop, but it doesn't work for me for i in x: y = i % 7 if y == 0: x.replace(i, 7) It should work but when I print the data frame I can't see the change, I even tried to replace a specific value, but also no change. How should I do it and I was wondering what is the best solution memory wise since I'm trying to scale this to a bigger data frame lets say we have a line like this 0 8 30 28 36 40 45 0 56 the output I want should be, 0 1 2 7 1 5 3 0 7 Thanks in advance
downvote count: 1
type: Question
tagged with: numpy
upvote count: 0
score: -1
answer count: 2

http://stackoverflow.com/comment/80604453
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46827395
has text: I can't use the id attribute because there are multiple tables with the same id. I was able to select that specific tablet only with find_all. Comunque sei italiano per caso?

http://stackoverflow.com/q/46786868
has body: How do I iterate over a numpy array of n dimensions and create a new array of similar shape. e.g. for the inputs: import numpy as np arr = np.array([[1,2,3], [4,5,6], [7,8,9], [0,0,0]]) alpha = 3. median = np.median(arr) I would like to build a new array of same (4,3) with flags set to 1 for a random condition. e.g. flag = (arr[i,j] &gt; median - alpha) or (arr[i,j] &lt; median + alpha) I would solve this with 2 for statements flags = arr * 0 for i in range(arr.shape[0]): for j in range(arr.shape[1]): flags[i,j] = (arr[i,j] &gt; median - alpha) or (arr[i,j] &lt; median + alpha) Is there a way to solve this in a simpler and more efficient pythonic way ? The solution should ideally also work for n dimensional arrays (1,2, ... n dimensions)
has comment: http://stackoverflow.com/comment/80520195
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/80520105
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46787146
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46790811
upvote count: 2
has title: Create new array while Iterating over a n dimensional numpy array
has answer: http://stackoverflow.com/a/46790811
type: Question
tagged with: numpy
tagged with: arrays
accepted answer: http://stackoverflow.com/a/46787146

http://stackoverflow.com/q/46759587
has answer: http://stackoverflow.com/a/46759634
score: 0
tagged with: random
has comment: http://stackoverflow.com/comment/80464635
answer count: 1
favorite count: 0
has title: unsupported operand type(s) for /: 'list' and 'list' Python
accepted answer: http://stackoverflow.com/a/46759634
tagged with: python
has body: I need to generate 10 random numbers in 2 variables and calculated the ratio between them. My code is below. What am I doing wrong? from random import randint N=10 a = [random.randint(0, 10) for _ in range(N)] b = [random.randint(0, 10) for _ in range(N)] print (a,b) ratio = a/b TypeError: unsupported operand type(s) for /: 'list' and 'list'
type: AnsweredQuestion
upvote count: 2
downvote count: 2
type: Question

http://stackoverflow.com/comment/80562064
has text: Yes I thought about it, what I did was not correct as it will confuse people, I will now recreate another question on the other issue instead thanks for your advise
comment on: http://stackoverflow.com/a/46807250
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80572355
comment on: http://stackoverflow.com/q/46812096
type: Comment
type: QuestionComment
has text: @ctwheels thanks for the suggestion. already this has been helpful because I think the error is down to malformed regex. I will give the unicode a go.
score: 0

http://stackoverflow.com/a/46888145
has comment: http://stackoverflow.com/comment/80724396
has comment: http://stackoverflow.com/comment/80723358
has comment: http://stackoverflow.com/comment/80724325
has comment: http://stackoverflow.com/comment/80723199
has body: Your recursion logic doesn't seem correct to me. You don't need to use for loop in a recursive function. You handle a part of job, reduce the problem and call the same function again to rest of the problem. At the end, use the returned value from the function. Also, you need to put a condition to stop. Something like this could work for your problem: def find_tuple(l, score = 0): if len(l)&lt;=1: return score if l[0] == 0 and l[1] == 0: score += 1 return find_tuple(l[2:], score) print(find_tuple([0,0])) print(find_tuple([0,0,0])) print(find_tuple([0,0,0,0])) print(find_tuple([0,0,0,0,0,0])) Output: 1 1 2 3
score: 0
has comment: http://stackoverflow.com/comment/80723284
has comment: http://stackoverflow.com/comment/80723755
has comment: http://stackoverflow.com/comment/80723266
type: Answer
has comment: http://stackoverflow.com/comment/80723977
answers question: http://stackoverflow.com/q/46887816

http://stackoverflow.com/comment/80483255
score: 0
comment on: http://stackoverflow.com/q/46768778
has text: There's some relevant info [here](https://stackoverflow.com/a/39506697/4014959); also see the other answers (and their comments) on that page.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46774069
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46774118
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/46774305
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46774305
score: 12
has body: I'm reading several spreadsheets into a data frame and there is an ID field that is a string in some spreadsheets and a number in others. I've converted it into a string, which is the data type I need, but I'm ending up with some IDs that have a ".0" at the end. How do I remove the decimal and zero? Example: ID number 805096730.0 should be 805096730
type: Question
has answer: http://stackoverflow.com/a/46774118
has title: Python - Remove decimal and zero from string
answer count: 2
upvote count: 12

http://stackoverflow.com/comment/80788567
comment on: http://stackoverflow.com/q/46900804
has text: thanks so much for the response! importing it differently did not do anything different, i checked the server logs and it says this : ImportError: No module named 'bs4'
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46902425
downvote count: 0
upvote count: 13
answers question: http://stackoverflow.com/q/46902367
has comment: http://stackoverflow.com/comment/84106647
type: Answer
score: 13
has body: try the following to change your array to 1D a.reshape((1, -1))

http://stackoverflow.com/q/46868453
has comment: http://stackoverflow.com/comment/80995684
has comment: http://stackoverflow.com/comment/80995575
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47024533
has answer: http://stackoverflow.com/a/46868715
type: Question
has comment: http://stackoverflow.com/comment/80684706
possible better answer: http://stackoverflow.com/a/46868715
tagged with: web
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/80995717
tagged with: python
has answer: http://stackoverflow.com/a/47024533
has answer: http://stackoverflow.com/a/47024943
has title: Django - template build-in filter tags {% url %}
has body: I am a new coder with Django. So, first apologize for it if this question is too easy. class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea) def save_comments_into_database(topic, user_id, content): data = Comment(topic=topic, commenter_id=user_id, content=content) data.save() this is the code for form {% csrf_token %} {{ form.as_p }} submit I am trying to use url tag to call a function is views.py. topic is a variable I passed in when this page is created. this is my code in urls.py url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"), then this is how I do in views.py def comment(request, the_topic, user_id): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': the_topic} # save the data in database save_comments_into_database(the_topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': the_topic}) I get the NoReserveMatchException: I really don't get where it goes wrong.
has comment: http://stackoverflow.com/comment/80684146
tagged with: django
tagged with: backend

http://stackoverflow.com/comment/80677160
comment on: http://stackoverflow.com/q/46864449
score: 0
type: Comment
type: QuestionComment
has text: My first guess is that you are getting characters for which `ch.isupper()` is false because they are not even alphabetic. The generator which ignores certain special characters could be made more robust by **keeping** alphabetic characters rather than **ignoring** some nonalphabetic characters.

http://stackoverflow.com/comment/80685844
comment on: http://stackoverflow.com/q/46869272
score: 0
type: Comment
type: QuestionComment
has text: I'm also currently back to just the blue screen

http://stackoverflow.com/a/46774920
type: Answer
has body: Try this one: string = "abc" letters = {"a" : "Ayeee", "b" : "Beeee", "c" : "Seee"} stringList = list(string) def print_banner(string, orientation): #" " for horizontal #"\n" for vertical result = list(map(lambda elem: letters.get(elem), stringList)) print(orientation.join(result)) print() print_banner(string, " ") print_banner(string, "\n") The output is: Ayeee Beeee Seee Ayeee Beeee Seee
answers question: http://stackoverflow.com/q/46774696
score: 0

http://stackoverflow.com/comment/80750979
type: QuestionComment
has text: Are you asking how to convert your list of unicode objects into a list of integers?
score: 2
type: Comment
comment on: http://stackoverflow.com/q/46902141

http://stackoverflow.com/comment/80681404
type: Comment
score: 0
has text: @martijn I know, that's why I said "a similar error" :^) None of the Arabic legacy encodings I tried gave the exact error.
type: AnswerComment
comment on: http://stackoverflow.com/a/46866274

http://stackoverflow.com/a/46772329
type: AcceptedAnswer
downvote count: 1
has body: If I search for Load More in the source code of the result I can't find it. Did you try using the non-javascript version? You can use it by simply add htmlto the url: https://duckduckgo.com/html?q=paralegal&amp;t=h_&amp;ia=web There you can find the next button at the end. This one works for me (Chrome version): results_url = "https://duckduckgo.com/html?q=paralegal&amp;t=h_&amp;ia=web" browser.get(results_url) results = browser.find_elements_by_id('links') num_page_items = len(results) for i in range(num_page_items): print(results[i].text) print(len(results)) nxt_page = browser.find_element_by_xpath('//input[@value="Next"]') if nxt_page: browser.execute_script('arguments[0].scrollIntoView();', nxt_page) nxt_page.click() Btw.: Duckduckgo also provides a nice api, which is probably much easier to use ;) edit: fix selector for next page link which selected the prev button on the second result page (thanks to @kingbode)
type: Answer
answers question: http://stackoverflow.com/q/46771995
accepted answer of: http://stackoverflow.com/q/46771995
has comment: http://stackoverflow.com/comment/80495111
score: 0
upvote count: 1

http://stackoverflow.com/q/46862719
type: AnsweredQuestion
tagged with: user-agent
has answer: http://stackoverflow.com/a/46862792
downvote count: 0
favorite count: 0
has body: I am trying to create a web scraper for NBA data. When I am running the below code: import requests response = requests.get('https://stats.nba.com/stats/leaguedashplayerstats?College=&Conference=&Country=&DateFrom=10%2F20%2F2017&DateTo=10%2F20%2F2017&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2017-18&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=') requests are timing out with the error: File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 70, in get return request('get', url, params=params, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 488, in request resp = self.send(prep, **send_kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 609, in send r = adapter.send(request, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 473, in send raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')",)) However, when I hit the same URL in the browser, I am getting a response.
score: 9
type: Question
tagged with: python
has title: Python's requests library timing out but getting the response from the browser
accepted answer: http://stackoverflow.com/a/46862792
answer count: 3
tagged with: web-scraping
tagged with: python-requests
upvote count: 9
possible better answer: http://stackoverflow.com/a/61967987
has answer: http://stackoverflow.com/a/61967987
has answer: http://stackoverflow.com/a/62914918

http://stackoverflow.com/a/46820757
accepted answer of: http://stackoverflow.com/q/46819088
upvote count: 2
type: Answer
has body: This is not how TF should be used. You should create graph once. You should create session once. Your current code does both things in a loop, thus causing slowness and memory issues. The problem lies in the fact that TF is not imperative language, so new_img =tf.image.adjust_brightness(image, .4) #image transformation is not application of a function on the image.This creates an operation in a graph, and stores reference to this operation in new_img. So each time you call this function, your graph grows. So in pseudo code it should be: create placeholder for image name create transformed image op - new_img create session for each image call in a session new_img op, providing path to the placehodler using feed_dict
score: 2
answers question: http://stackoverflow.com/q/46819088
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46769839
answers question: http://stackoverflow.com/q/46768751
type: Answer
has body: If you want to call a Windows command, you need to give the full path to the command. You can try: import subprocess import os.path # C:\ToolsSuite&gt;sdi --ip 172.23.240.41 --fwdl "c:\BUILDS\firmware_image.zip" cmd = os.path.join("C:\\ToolsSuite", "sdi") args = [cmd, '--ip', '172.23.240.41', '--fwdl', 'c:\\BUILDS\\firmware_image.zip'] subprocess.check_call(args) Here, check_call is useful to replace non-zero exit code by an exception. Of course, you can also choose another function of the same family.
score: 0

http://stackoverflow.com/comment/80710297
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46881531
has text: Change `{}` to `[]`. `{}` is for set and `[]` is for list. Set will only have unique elements so the output is correct
score: 0

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/46885308

http://stackoverflow.com/a/46782629
answers question: http://stackoverflow.com/q/46782289
has comment: http://stackoverflow.com/comment/87213469
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46782289
type: Answer
has comment: http://stackoverflow.com/comment/87213091
has body: Couple of ways: In [3166]: df.apply(lambda x: x.fillna(df.close.shift())).ffill() Out[3166]: open high low close Timestamp 2014-01-07 13:18:00 874.67040 892.06753 874.67040 892.06753 2014-01-07 13:19:00 892.06753 892.06753 892.06753 892.06753 2014-01-07 13:20:00 892.06753 892.06753 892.06753 892.06753 2014-01-07 13:21:00 883.23085 883.23085 874.48165 874.48165 2014-01-07 13:22:00 874.48165 874.48165 874.48165 874.48165 In [3167]: df.fillna({c: df.close.shift() for c in df}).ffill() Out[3167]: open high low close Timestamp 2014-01-07 13:18:00 874.67040 892.06753 874.67040 892.06753 2014-01-07 13:19:00 892.06753 892.06753 892.06753 892.06753 2014-01-07 13:20:00 892.06753 892.06753 892.06753 892.06753 2014-01-07 13:21:00 883.23085 883.23085 874.48165 874.48165 2014-01-07 13:22:00 874.48165 874.48165 874.48165 874.48165

http://stackoverflow.com/a/46830655
answers question: http://stackoverflow.com/q/46830131
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46830131
type: AcceptedAnswer
downvote count: 0
has body: Expanding Roman Kutlak's answer, here is how I would rewrite your app fixture: @pytest.fixture(scope='session') def app(): _app = create_app() _app.debug = False _app.engine = create_engine(_app.config['SQLALCHEMY_DATABASE_URI'], connect_args={"options": "-c timezone=utc"}) # session should probably not be global?.. DbSession = scoped_session( sessionmaker(), scopefunc=_app_ctx_stack.__ident_func__ ) DbSession.configure(bind=_app.engine, query_cls=BaseQuery) # Establish an application context before running the tests. ctx = _app.app_context() ctx.push() # this function is specifically for app's teardown, don't call it again for fixture teardown @_app.teardown_appcontext def teardown(exception=None): if DbSession: DbSession.remove() # here is where tests will be executed yield _app # now tear-down our fixture (as apposed to flask app's teardown) ctx.pop() It is not needed to use global keyword unless you want to assign a value to global variable from within inner scope.
type: Answer

http://stackoverflow.com/q/46808219
score: 1
has answer: http://stackoverflow.com/a/46809121
type: Question
has comment: http://stackoverflow.com/comment/80563784
tagged with: python-2.7
upvote count: 1
downvote count: 0
answer count: 1
has title: Regex to remove underscore followed by number in string in python?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80565529
has body: I have set of strings like this: CLM_ADJUSTMT.CLAIM_DATA.TUDCAP_L_2.CRT_TS_0, marks.science_0.physics_0, marks.geo_1 I want to remove only if underscore is followed by number(CRT_TS_0=CRT_TS) can someone help me to get the right regex I tried using re.sub('_[0-9]+$', '',newstr) but it removes all underscore and numbers output: CLM_ADJUSTMT.CLAIM_DATA.TUDCAP_L.CRT_TS, marks.science.physics, marks.geo
has comment: http://stackoverflow.com/comment/80563398

http://stackoverflow.com/q/46877213
has title: Django create CustomUser model
has comment: http://stackoverflow.com/comment/80701605
answer count: 1
has answer: http://stackoverflow.com/a/46878731
downvote count: 0
accepted answer: http://stackoverflow.com/a/46878731
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
has body: Folks, I'm trying to create my own User model by extending the AbstractBaseUser model provided by Django. However, I keep on getting the following error when migrating: ValueError: The field admin.LogEntry.user was declared with a lazy reference to '&lt;app_name&gt;.user', but app '&lt;app_name&gt;' doesn't provide model 'user'. What I have done so far is the following: In app/models.py added CustomUser class together with CustomUserManager with relevant fields and all. In app/admin.py I've added this: from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from &lt;app_name&gt;.models import CustomUser class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email',) class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email',) def clean_username(self): username = self.cleaned_data["username"] try: get_user_model().objects.get(username=username) except get_user_model().DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm fieldsets = ( (None, {'fields': [('username', 'password'),]}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) admin.site.register(CustomUser, CustomUserAdmin) Apart from that there is this added to seetings.py AUTH_USER_MODEL = '&lt;app_name&gt;.CustomUser' Everything that I found so far suggests that the above given code should make this work, but it doesn't. I spent like 4-5 hours already and I still can't get my head around it. Someone please help
upvote count: 1
type: Question

http://stackoverflow.com/comment/80550248
comment on: http://stackoverflow.com/q/46801747
type: Comment
type: QuestionComment
has text: Your issue is that `s` is pointer to `stack` so it is a shallow copy not a deep copy which is what you want
score: 1

http://stackoverflow.com/comment/80731904
has text: Hi, thank you for your answer. When I try this I receive selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "//a[@class='cls_arw arw_blue'][@id,'ctl00_cphMain_gdvSchdRel_ctl02_lnkSchTyp']" is invalid: SyntaxError: The expression is not a legal expression. I edited the source code to show the full div of the table.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46883599

http://stackoverflow.com/q/46869272
has comment: http://stackoverflow.com/comment/82995786
downvote count: 0
tagged with: tornado
tagged with: dokku
has comment: http://stackoverflow.com/comment/80685796
favorite count: 0
has comment: http://stackoverflow.com/comment/80685687
has comment: http://stackoverflow.com/comment/80685803
type: UnansweredQuestion
has body: I'm sorry if this issue has already been dealt with in the past, but I have scoured the net and have failed to turn up any fixes. My issue is as follows: I deployed a Tornado Python app with Dokku yesterday and all was gravy. I am working on this as a group project, however, so I had to wait for my changes to be merged with the master branch in our repository before I could push the most up-to-date app.py file to the server. Everything was fine, and then I pushed the updates and the app broke! I have searched the net and thoroughly read the Dokku docs, but the problem persists. I have run dokku apps:destroy, removed the remote and started from scratch a dozen times and each time I deploy, as seen below: successful deployment screenshot At first I was greeted with a blue screen, but now on my most recent deployment I am getting sent to another one of my sites: https://hobby.logancodes.com/ --edit-- the correct address should be http:mind-cloud.logancodes.com I'm not sure if the issue is my DNS setting, or something else but it's got me stumped. Any help would be greatly appreciated!
tagged with: python
has title: Deployment issue with Dokku
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80685844

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/46775664
tags question: http://stackoverflow.com/q/46854971
tags question: http://stackoverflow.com/q/46819433
tags question: http://stackoverflow.com/q/46757106
tags question: http://stackoverflow.com/q/46867510
tags question: http://stackoverflow.com/q/46790599
tags question: http://stackoverflow.com/q/46875933
tags question: http://stackoverflow.com/q/46797693
tags question: http://stackoverflow.com/q/46897446
tags question: http://stackoverflow.com/q/46842966
tags question: http://stackoverflow.com/q/46887402
tags question: http://stackoverflow.com/q/46806768
tags question: http://stackoverflow.com/q/46877209
tags question: http://stackoverflow.com/q/46774876
tags question: http://stackoverflow.com/q/46818891
tags question: http://stackoverflow.com/q/46839706
type: Tag
tags question: http://stackoverflow.com/q/46837552
tags question: http://stackoverflow.com/q/46872614
tags question: http://stackoverflow.com/q/46850404
tags question: http://stackoverflow.com/q/46787713
tags question: http://stackoverflow.com/q/46825189
tags question: http://stackoverflow.com/q/46882954
tags question: http://stackoverflow.com/q/46829997
tags question: http://stackoverflow.com/q/46859242
tags question: http://stackoverflow.com/q/46882521
tags question: http://stackoverflow.com/q/46878575
tags question: http://stackoverflow.com/q/46897818
tags question: http://stackoverflow.com/q/46785507
tags question: http://stackoverflow.com/q/46898644
tags question: http://stackoverflow.com/q/46792631
tags question: http://stackoverflow.com/q/46772871
tags question: http://stackoverflow.com/q/46798038
tags question: http://stackoverflow.com/q/46766828
tags question: http://stackoverflow.com/q/46772369
tags question: http://stackoverflow.com/q/46902141
tags question: http://stackoverflow.com/q/46750690
tags question: http://stackoverflow.com/q/46846620
tags question: http://stackoverflow.com/q/46841618
tags question: http://stackoverflow.com/q/46901064
tags question: http://stackoverflow.com/q/46848877
tags question: http://stackoverflow.com/q/46752760
tags question: http://stackoverflow.com/q/46843619
tags question: http://stackoverflow.com/q/46810334
tags question: http://stackoverflow.com/q/46850954
tags question: http://stackoverflow.com/q/46839347
tag name: html
tags question: http://stackoverflow.com/q/46757494
tags question: http://stackoverflow.com/q/46806711
tags question: http://stackoverflow.com/q/46834373
tags question: http://stackoverflow.com/q/46771636
tags question: http://stackoverflow.com/q/46765683
tags question: http://stackoverflow.com/q/46834418
tags question: http://stackoverflow.com/q/46889098
tags question: http://stackoverflow.com/q/46831044
tags question: http://stackoverflow.com/q/46772932
tags question: http://stackoverflow.com/q/46759563
tags question: http://stackoverflow.com/q/46874472
tags question: http://stackoverflow.com/q/46754742
tags question: http://stackoverflow.com/q/46860816
tags question: http://stackoverflow.com/q/46890431
tags question: http://stackoverflow.com/q/46805811
tags question: http://stackoverflow.com/q/46848562

http://stackoverflow.com/q/46756034
has comment: http://stackoverflow.com/comment/80459183
has comment: http://stackoverflow.com/comment/80457936
has comment: http://stackoverflow.com/comment/80457516
score: 0
has comment: http://stackoverflow.com/comment/80457896
has comment: http://stackoverflow.com/comment/80458147
tagged with: python
has comment: http://stackoverflow.com/comment/80457808
has comment: http://stackoverflow.com/comment/80458089
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80457781
type: Question
has body: I have a program I'm writing. It's becoming too large to manage well: it has a lot of code related to GUI functionality (PyQt5), and it's nearly 2000 lines. I understand that in Python, it is acceptable to have large scripts that are coded completely in one file, but writing this program has become unmanageable. I can't easily organize the code in one file. I previously tried to split it into multiple files (using methods I'd found here on StackOverflow), but to no avail. I finally just realized what I might have to do for my situation. (I know that realistically, you'd never split the following into two files, but I'm using it as an example.) Here is a very simple example of a script split in two (file 1): # TestProg.py class Name: def __init__(self, name): self.name = name def testfunc(): nm.name += nm.name[int(len(nm.name)/2):] # Add to name, second half of name return nm.name if __name__ == '__main__': import TestModule print(TestModule.returnName(TestModule.nm)) input() File 2: # TestModule.py import TestProg Name = TestProg.Name testfunc = TestProg.testfunc nm = Name('Henry') def returnName(name): return name.name[::-1] + testfunc() If you try running this, it won't work. I finally figured out it's because of the fact that testfunc is defined in TestProg and uses a global variable (which isn't defined in TestProg). To solve this problem, you must modify the globals dict of testfunc, with testfunc.__globals__['nm'] = nm, and place that in TestModule right after you define nm. I understand this is not a pretty thing to do, but it seems to be the best way I can think of to do it. Now, I know, "Just use a local variable/parameter for testfunc, instead of global." The thing is, it is a global variable (which needs to be defined in a file separate from the function in the split). I don't want to have to pass the variable to the function every time, that's very tedious, repetitive, and a waste of time. My question is: is there a better way to do it? I would assume no…
has title: Is this the best method to split Python code into dependent modules?
has comment: http://stackoverflow.com/comment/80457443

http://stackoverflow.com/q/46881901
answer count: 2
has answer: http://stackoverflow.com/a/47398902
has title: How to write a long type into bytesarray
score: 0
has comment: http://stackoverflow.com/comment/80711244
has answer: http://stackoverflow.com/a/47399380
tagged with: netty
tagged with: python
type: UnansweredQuestion
type: Question
has body: i have a socket server that written by java(using netty),i use LengthFieldBasedFrameDecoder to decode message ; the encoder ,if use java should be: Message.Type msgType = in.type(); // All messages have the frame length, message type, and message itself. int headerLength = 8 + msgType.encodedLength() + in.encodedLength(); // long frameLength = headerLength + bodyLength; ByteBuf header = ctx.alloc().heapBuffer(headerLength); //header.writeLong(frameLength); header.writeLong(headerLength); msgType.encode(header); in.encode(header); but now i need a socket client written by python ,so how do i write the message length(8 bytes,long type) into buffer
tagged with: java

http://stackoverflow.com/comment/80599709
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46825666
type: Comment
has text: This is what I was looking for. Thank you :)

http://stackoverflow.com/q/46807209
upvote count: 1
tagged with: python
has title: Error when deploying Google DataFlow job on App Engine CRON
accepted answer: http://stackoverflow.com/a/46905664
has comment: http://stackoverflow.com/comment/80568629
has comment: http://stackoverflow.com/comment/80567194
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80562916
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/80571638
has body: (Continued from a previous question) I am trying to deploy a google dataflow job to run it as a cron job on the google app engine, following the method described here. I have an DataFlow script (written in python) in a pipelines/script.py folder. Running this script locally (using the Apache Beam DirectRunner) or on google cloud (using the DataFlowRunner) works properly. But when deploying the job to run it periodically on the app engine, the job raises the following error when executed: (4cb822d7f796239a): Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 582, in do_work work_executor.execute() File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 166, in execute op.start() File "apache_beam/runners/worker/operations.py", line 294, in apache_beam.runners.worker.operations.DoOperation.start (apache_beam/runners/worker/operations.c:10607) def start(self): File "apache_beam/runners/worker/operations.py", line 295, in apache_beam.runners.worker.operations.DoOperation.start (apache_beam/runners/worker/operations.c:10501) with self.scoped_start_state: File "apache_beam/runners/worker/operations.py", line 300, in apache_beam.runners.worker.operations.DoOperation.start (apache_beam/runners/worker/operations.c:9702) 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 858, in load dispatch[key](self) File "/usr/lib/python2.7/pickle.py", line 1090, 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/li…
type: Question
has comment: http://stackoverflow.com/comment/80569711
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46905664
has comment: http://stackoverflow.com/comment/80571544
answer count: 1
has comment: http://stackoverflow.com/comment/80568040
linked to: http://stackoverflow.com/q/46564730
tagged with: google-app-engine
tagged with: apache-beam

http://stackoverflow.com/a/46757128
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46757088
downvote count: 0
has comment: http://stackoverflow.com/comment/80459531
type: Answer
has body: There could be better answer [i for i,j in enumerate(list) if j==min(list)] [0, 4]

http://stackoverflow.com/q/46812643
type: Question
tagged with: python-3.6
upvote count: 1
answer count: 1
has body: I have a basic shopping cart that works. I am trying to learn string formatting -- Custom Object: https://pyformat.info/#custom_1 What I want to do is this: print("Your cart contains: {0:short}".format(cart)) Should return: Your cart contains: cucumbers, tissues, tomatoes, toothpaste My format method is wrong. I keep getting: Traceback (most recent call last): File "C:/Users/Mark/PycharmProjects/main/main.py", line 54, in &lt;module&gt; print("Your cart contains: {0:short}".format(cart)) TypeError: __format__ must return a str, not NoneType My code: class Item(object): def __init__(self, unq_id, name, price, qty, measure): self.unq_id = unq_id self.product_name = name self.price = price self.qty = qty self.measure = measure class Cart(object): def __init__(self): self.content = dict() def __format__(self, format_type): if format == 'short': return ', '.join(item.name for item in self.content) def add(self, item): if item.unq_id not in self.content: self.content.update({item.unq_id: item}) return for k, v in self.content.get(item.unq_id).items(): if k == 'unq_id': continue elif k == 'qty': total_qty = v.qty + item.qty if total_qty: v.qty = total_qty continue self.remove_item(k) else: v[k] = item[k] def get_total(self): return sum([v.price * v.qty for _, v in self.content.items()]) def get_num_items(self): return sum([v.qty for _, v in self.content.items()]) def remove_item(self, key): self.content.pop(key) if __name__ == '__main__': cart = Cart() cart.add(Item(1, "Cucumbers", 1., 1, 'kg')) cart.add(Item(2, "Tissues", 1., 2, 'dozen')) cart.add(Item(3, "Tomatoes", 1., 5, 'box')) cart.add(Item(4, "Toothpaste", 1., 5, 'box')) # print("You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total())) print("Your cart contains: {0:short}".format(cart)) # cart.remove_item(1) # print("You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total()))
favorite count: 0
accepted answer: http://stackoverflow.com/a/46813027
tagged with: string-formatting
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46813027
score: 1
has title: String formatting Custom Objects

http://stackoverflow.com/comment/80599462
comment on: http://stackoverflow.com/a/46825947
score: 0
type: AnswerComment
has text: to_datetime will handle the `nan` types, return type is `pandas._libs.tslib.NaTType`
type: Comment

http://stackoverflow.com/q/46900044
favorite count: 0
has body: I am trying to unpickle an object sent via a socket My server has this class ActivePeerList = [] class PeerInfo(): def __init__(self): self.hostname = "" self.cookie = None self.active = False self.TTL = 7200 self.port = "" self.no_of_times = 0 self.LastActiveDate = None I append instances of this class into the list and send it via a socket to a client. client[0].send(pickle.dumps(ActivePeerList)) I get this error when I try to unpickle i.e. pickle.loads(client.recv(1024)) AttributeError: Can't get attribute 'PeerInfo' on &lt;module '__main__' (&lt;_frozen_importlib.SourceFileLoader object at 0x0000000002A73828&gt;)&gt; Is transferring unkown classes(i.e.unknown to the client) forbidden?? Even if it is, I am engulfing it in a List object. So it should work. RIght?? Any help would be appreciated
tagged with: python-3.x
tagged with: sockets
tagged with: pickle
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: Unable to Unpickle
has comment: http://stackoverflow.com/comment/80747276
has answer: http://stackoverflow.com/a/46900097
accepted answer: http://stackoverflow.com/a/46900097
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/115744634
comment on: http://stackoverflow.com/q/46801008
type: QuestionComment
type: Comment
has text: If I remember correctly, those packages expect their namespaces to be used, so remapping URLs would still have the same problem. Having said that, I believe I ended up using Patrick Altman's suggestion. It's been 3 years though, so I don't remember for sure.
score: 0

http://stackoverflow.com/q/46784550
has body: I want to make a stickymenu like this yeah looks like iosApp menubar. I already know i should use screenmanager but i understood it can use only Class of Screen. If i hope use in Boxlayout class.But i dont know it. If somebody tell me how make like this menu. I forgot to write important things. The menu that I want to make is in a state where it is fixed without making a transition for each menu when making a page transition.
score: -1
downvote count: 1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has title: I want to make a sticky menu using kivy's screenmanager
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/46788072

http://stackoverflow.com/a/46816505
downvote count: 0
score: 8
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/80580343
has comment: http://stackoverflow.com/comment/80580541
has comment: http://stackoverflow.com/comment/80580497
has comment: http://stackoverflow.com/comment/80580379
accepted answer of: http://stackoverflow.com/q/46816226
has comment: http://stackoverflow.com/comment/80580456
answers question: http://stackoverflow.com/q/46816226
has body: you can use DataFrame.lookup(): In [6]: pd.Series(df.lookup(df.index, df.columns), index=df.columns) Out[6]: A 0 B 4 C 8 dtype: int32 or: In [14]: pd.Series(df.lookup(ind, cols), index=df.columns) Out[14]: A 0 B 4 C 8 dtype: int32 Explanation: In [12]: df.lookup(df.index, df.columns) Out[12]: array([0, 4, 8])
type: AcceptedAnswer

http://stackoverflow.com/q/46770171
has answer: http://stackoverflow.com/a/46770312
has answer: http://stackoverflow.com/a/46770254
accepted answer: http://stackoverflow.com/a/46770254
has comment: http://stackoverflow.com/comment/80485788
favorite count: 0
has body: I have the below dictionary format, I want to sum the dictionary values based on date. dict1 = [ {'date':"10-05-2017", 'cost':20}, {'date':"10-05-2017", 'cost':10}, {'date':"11-05-2017", 'cost':15}, {'date':"11-05-2017", 'cost':10}, {'date':"12-05-2017", 'cost':5} ] Result: [ {'date':"10-05-2017", 'cost':30}, {'date':"11-05-2017", 'cost':25}, {'date':"12-05-2017", 'cost':5} ]
possible better answer: http://stackoverflow.com/a/46770281
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/80485699
has comment: http://stackoverflow.com/comment/80485603
has title: How to sum date based dictionary values in python?
has answer: http://stackoverflow.com/a/46770491
has comment: http://stackoverflow.com/comment/80485689
upvote count: 1
downvote count: 6
type: AnsweredQuestion
score: -5
has answer: http://stackoverflow.com/a/46770281
has answer: http://stackoverflow.com/a/46770662
type: Question

http://stackoverflow.com/comment/80731066
has text: 1) I'll see to use queue and process. I already test with these, but I didn't understand very well 2) It depends, it can be less of 1000 points, or more than 16 millions. It can be again more, because I can to have need to use 3 point clouds in same time
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46878414

http://stackoverflow.com/q/46854905
has comment: http://stackoverflow.com/comment/80929070
tagged with: pyspark
possible better answer: http://stackoverflow.com/a/46931018
accepted answer: http://stackoverflow.com/a/47004597
has comment: http://stackoverflow.com/comment/80953764
has answer: http://stackoverflow.com/a/46931018
has body: I'm trying to parallelize a machine learning prediction task via Spark. I've used Spark successfully a number of times before on other tasks and have faced no issues with parallelization before. In this particular task, my cluster has 4 workers. I'm calling mapPartitions on an RDD with 4 partitions. The map function loads a model from disk (a bootstrap script distributes all that is needed to do this; I've verified it exists on each slave machine) and performs prediction on data points in the RDD partition. The code runs, but only utilizes one executor. The logs for the other executors say "Shutdown hook called". On different runs of the code, it uses different machines, but only one at a time. How can I get Spark to use multiple machines at once? I'm using PySpark on Amazon EMR via Zeppelin notebook. Code snippets are below. %spark.pyspark sc.addPyFile("/home/hadoop/MyClassifier.py") sc.addPyFile("/home/hadoop/ModelLoader.py") from ModelLoader import ModelLoader from MyClassifier import MyClassifier def load_models(): models_path = '/home/hadoop/models' model_loader = ModelLoader(models_path) models = model_loader.load_models() return models def process_file(file_contents, models): filename = file_contents[0] filetext = file_contents[1] pred = MyClassifier.predict(filetext, models) return (filename, pred) def process_partition(file_list): models = load_models() for file_contents in file_list: pred = process_file(file_contents, models) yield pred all_contents = sc.wholeTextFiles("s3://some-path", 4) processed_pages = all_contents.mapPartitions(process_partition) processedDF = processed_pages.toDF(["filename", "pred"]) processedDF.write.json("s3://some-other-path", mode='overwrite') There are four tasks as expected, but they all run on the same executor! I have the cluster running and can provide logs as available in Resource Manager. I just don't know yet where to look.
has comment: http://stackoverflow.com/comment/80757795
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/80857330
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80705075
favorite count: 0
score: 16
has comment: http://stackoverflow.com/comment/80928992
type: Question
has comment: http://stackoverflow.com/comment/80954618
has comment: http://stackoverflow.com/comment/80954778
has comment: http://stackoverflow.com/comment/80704475
tagged with: python
has comment: http://stackoverflow.com/comment/80955542
has title: Spark is only using one worker machine when more are available
answer count: 2
upvote count: 16
has comment: http://stackoverflow.com/comment/80952341
has answer: http://stackoverflow.com/a/47004597

http://stackoverflow.com/a/67138596
has body: I was having this same problem. In my case, the version of pexpect and traitlets installed on my system were older than what jupyter needed. After running this... sudo -H python3.9 -m pip install --upgrade --ignore-installed pexpect traitlets Jupyter started correctly and I no longer saw the error.
answers question: http://stackoverflow.com/q/46880699
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/46805662
accepted answer: http://stackoverflow.com/a/55173445
has comment: http://stackoverflow.com/comment/80559037
tagged with: python
has comment: http://stackoverflow.com/comment/80559546
answer count: 4
has body: I have a model and I want to write an update() method for it in order to update. The below snippet is my model: class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) university = models.CharField(max_length=50,blank=True, null=True) teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE) and the below snippet is corresponding Serializer: class KlassSerializer(ModelSerializer): teacher = ProfileSerializer() url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk') klass_settings = KlassSettingsSerializer() class Meta: model = Klass fields = ('url', 'id', 'title', 'description', 'university','teacher') def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.university = validated_data.get('university', instance.university) instance.save() return instance And for update, I use below snippet: class KlassAPIView(APIView): def put(self, request, pk=None): if pk == None: return Response({'message': 'You must specify class ID'}, status=HTTP_400_BAD_REQUEST) klass = Klass.objects.get(pk=pk) if request.user.profile.type != 't': raise PermissionDenied(detail={'message': 'You aren't teacher of this class, so you can't edit information.'}) serializer = KlassSerializer(data=request.data, context={'request': request}) serializer.initial_data['teacher'] = request.user.profile.__dict__ if serializer.is_valid(): serializer.update(instance=klass, validated_data=serializer.data) # Retrieve teacher and store return Response({'data': serializer.data}, status=HTTP_200_OK) else: return Response({'data': serializer.errors}, status=HTTP_400_BAD_REQUEST) but when I send data with PUT method, it returns below error: AttributeError at /api/class/49/ 'collections.OrderedDict' object has no attribute 'pk' and the error occurs in serializer.update(inst…
has comment: http://stackoverflow.com/comment/80559106
tagged with: django
has comment: http://stackoverflow.com/comment/80558801
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48194725
tagged with: django-rest-viewsets
has answer: http://stackoverflow.com/a/55173445
tagged with: django-models
has comment: http://stackoverflow.com/comment/80558933
score: 4
possible better answer: http://stackoverflow.com/a/48194725
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80558832
has answer: http://stackoverflow.com/a/61571580
downvote count: 0
tagged with: django-rest-framework
has title: 'collections.OrderedDict' object has no attribute 'pk' - django rest framework
has answer: http://stackoverflow.com/a/67363910
favorite count: 0
has comment: http://stackoverflow.com/comment/80563537

http://stackoverflow.com/comment/80505413
has text: Welcome to SO. You should consider adding your code to the question instead of having it as a screenshot. You wont get much help if the people trying to help you cant reproduce (c+p) your code to debug the problem
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46779708

http://stackoverflow.com/a/46830548
has comment: http://stackoverflow.com/comment/80609496
upvote count: 1
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/46830231
has body: Suppose we use a Series with the data specified in the question, named user_id, with a single line you do what you need: user_id.where(user_id == 0).fillna('is not empty') I don't like loc very much since I think it complicates the reading. It might be better than replace because it allows the opposite case: user_id.where(user_id != 0).fillna('is empty')

http://stackoverflow.com/comment/80493851
type: Comment
comment on: http://stackoverflow.com/q/46773854
type: QuestionComment
score: 0
has text: These 2 solutions are not nearly equivalent; in the top one you use a `while True`, which is slower than a `for` loop. Also the bottom one you explore a much more limited range of numbers, so it's hardly surprising that this is faster

http://stackoverflow.com/q/46801825
has comment: http://stackoverflow.com/comment/80551035
score: 1
has answer: http://stackoverflow.com/a/46802248
type: Question
tagged with: decimal
answer count: 2
possible better answer: http://stackoverflow.com/a/46802226
has comment: http://stackoverflow.com/comment/80551135
downvote count: 0
has answer: http://stackoverflow.com/a/46802226
has title: Problems with decimal separator
has comment: http://stackoverflow.com/comment/80551100
has body: I've latitude/longitude numbers, like: -4726786457893145 but i need a decimal separator, like: -47.26786457893145 I've tried 'format' or 'for' structures but without success. I've even converted to list, then inserted a dot and then convert to float again, but not work for all numbers and i do not know why. I'd appreciate your help. Thanks. Here's my partial code: latitude = [] longitude = [] for i in range(len(data['Latitude'])): a = list(str(data['Latitude'][i].replace(',',''))) a.insert(3,'.') str1 = ''.join(a) latitude.append(float(str1)) a = list(str(data['Longitude'][i].replace(',',''))) a.insert(3,'.') str1 = ''.join(a) longitude.append(float(str1))
accepted answer: http://stackoverflow.com/a/46802248
has comment: http://stackoverflow.com/comment/80585073
favorite count: 0
tagged with: separator
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/46809103
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/46809328
tagged with: ipython
has body: I have two sets of 8 images each given as numpy arrays. Because I want to use a for loop at some point in my program, I want to display each set as matplotlib subplots in the same cell, unfortunately it does not work (I tried to use the display function from IPython.display, with no success at all). Here is the code I used : import matplotlib.pyplot as plt import numpy as np %matplotlib inline for i, img in enumerate(set1): plt.subplot(2, 4, i+1) plt.axis('off') plt.imshow(img) for i, img in enumerate(set2): plt.subplot(2, 4, i+1) plt.axis('off') plt.imshow(img) It only displays the second set.
has title: plot several subplots in IPython notebook
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/46809328

http://stackoverflow.com/comment/80684209
type: AnswerComment
score: 0
type: Comment
has text: @ClaytonWahlstrom Nice. Good idea.
comment on: http://stackoverflow.com/a/46868155

http://stackoverflow.com/a/46860157
has comment: http://stackoverflow.com/comment/80673228
has comment: http://stackoverflow.com/comment/80673217
type: AcceptedAnswer
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/46860145
has comment: http://stackoverflow.com/comment/80677050
accepted answer of: http://stackoverflow.com/q/46860145
type: Answer
has body: It appears you've adapted python2.x code to use in python3.x. Note that map does not return a list in python3.x, it returns a generator map object (not a list, basically) that you've to convert to a list appropriately. Furthermore, I'd recommend using list.extend instead of adding the two together. Why? The former creates a new list object every time you perform addition, and is wasteful in terms of time and space. numbers = [] for line in f: numbers.extend(list(map(float, line.rstrip().split(',')))) print(numbers) An alternative way of doing this would be: for line in f: numbers.extend([float(x) for x in line.rstrip().split(',')]) Which happens to be slightly more readable. You could also choose to get rid of the outer for loop using a nested list comprehension. numbers = [float(x) for line in f for x in line.rstrip().split(',')] Also, forgot to mention this (thanks to chris in the comments), but you really should be using a context manager to handle file I/O. with open('scores.txt', 'r') as f: ... It's cleaner, because it closes your files automatically when you're done with them. After seeing your ValueError message, it's clear there's issues with your data (invalid characters, etc). Let's try something a little more aggressive. numbers = [] with open('scores.txt', 'r') as f: for line in f: for x in line.strip().split(','): try: numbers.append(float(x.strip())) except ValueError: pass If even that doesn't work, perhaps, something even more aggressive with regex might do it: import re numbers = [] with open('scores.txt', 'r') as f: for line in f: line = re.sub('[^\d\s,.+-]', '', line) ... # the rest remains the same
upvote count: 7
has comment: http://stackoverflow.com/comment/80673355
has comment: http://stackoverflow.com/comment/80673402
has comment: http://stackoverflow.com/comment/80677093

http://stackoverflow.com/comment/80704335
comment on: http://stackoverflow.com/a/46878206
has text: I called it after your solution. It better fits the logic of my function. Thanks.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46801675
has title: python argument of type 'int' is not iterable when using for in
answer count: 2
has comment: http://stackoverflow.com/comment/80592257
has answer: http://stackoverflow.com/a/46801819
score: 0
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has body: I am trying to write code that will accept a filename from the command line and print out the following properties: number of lines number of characters number of words number of “the” number of “a/an" I keep getting the error message "argument of type 'int' is not iterable" for the line if 'the' in words:. How do I fix this? import sys import string file_name=sys.argv[0] char= words = lines = theCount = aCount= 0 with open(file_name,'r') as in_file: for line in in_file: lines +=1 words +=len(line.split()) char +=len(line) if 'the' in words: theCount +=1 if 'a' in words: a +=1 if 'an' in words: a +=1 print("Filename:", file_name) print("Number of lines:", lines) print("Number of characters:", char) print("Number of 'the'", theCount) print("Number of a/an:", aCount)
type: Question
has answer: http://stackoverflow.com/a/46801843

http://stackoverflow.com/comment/80500199
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46774732
has text: The thing everyone talks about is the name value which is a variable.the idea behind it to rename it automatically . Whatever the original name is or the given name is.

http://stackoverflow.com/a/46829870
has comment: http://stackoverflow.com/comment/80608677
has comment: http://stackoverflow.com/comment/80608554
type: Answer
has comment: http://stackoverflow.com/comment/80608466
answers question: http://stackoverflow.com/q/46829769
upvote count: 1
has comment: http://stackoverflow.com/comment/80607859
has comment: http://stackoverflow.com/comment/80638196
has comment: http://stackoverflow.com/comment/80607706
score: 1
has comment: http://stackoverflow.com/comment/80607432
has comment: http://stackoverflow.com/comment/80608503
has body: Use stack: print (df.columns) MultiIndex(levels=[['Cat1'], ['Type1', 'Type2'], ['2018'], ['1Q', '2Q', '3Q', '4Q']], labels=[[0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 1, 2, 3, 0]]) df = df.stack([0,1,2,3]).reset_index() df.columns = ['Name','Cat','Type','Year','Quarter','Value'] print (df) Name Cat Type Year Quarter Value 0 Name1 Cat1 Type1 2018 1Q 1.0 1 Name1 Cat1 Type1 2018 2Q 5.0 2 Name1 Cat1 Type1 2018 3Q 3.0 3 Name1 Cat1 Type1 2018 4Q 5.0 4 Name1 Cat1 Type2 2018 1Q 4.0 5 Name2 Cat1 Type1 2018 1Q 3.0 6 Name2 Cat1 Type1 2018 2Q 23.0 7 Name2 Cat1 Type1 2018 3Q 4.0 8 Name2 Cat1 Type1 2018 4Q 2.0 9 Name2 Cat1 Type2 2018 1Q 4.0 10 Name3 Cat1 Type1 2018 1Q 4.0 11 Name3 Cat1 Type1 2018 2Q 3.0 12 Name3 Cat1 Type1 2018 3Q 5.0 13 Name3 Cat1 Type1 2018 4Q 3.0 14 Name3 Cat1 Type2 2018 1Q 44.0 15 Name4 Cat1 Type1 2018 1Q 3.0 16 Name4 Cat1 Type1 2018 2Q 6.0 17 Name4 Cat1 Type1 2018 3Q 5.0 18 Name4 Cat1 Type1 2018 4Q 4.0 19 Name4 Cat1 Type2 2018 1Q 2.0
has comment: http://stackoverflow.com/comment/80607601
downvote count: 0
has comment: http://stackoverflow.com/comment/80608442
has comment: http://stackoverflow.com/comment/80638164
has comment: http://stackoverflow.com/comment/80607779
has comment: http://stackoverflow.com/comment/80608376

http://stackoverflow.com/a/46855475
has body: You are using json.loads when you should be using json.dumps.
score: 1
answers question: http://stackoverflow.com/q/46855313
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/46813770
downvote count: 0
has body: How about this: import itertools names = ['John', 'Mike'] years = ['1980', '1975'] print [ zip(names, year_product) for year_product in itertools.product( years, repeat=len(names)) ]
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46813603
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/46813603

http://stackoverflow.com/a/46900669
answers question: http://stackoverflow.com/q/46900610
has comment: http://stackoverflow.com/comment/80752183
has body: import sys stuff = ("{}{}{}{}".format(totalAllScraped, str(" profiles scraped "), (len(sortedurls)), str(" filtered profiles saved."))) sys.stdout.write("\r" + stuff) sys.stdout.flush() this did the trick thanks anyway
downvote count: 0
has comment: http://stackoverflow.com/comment/80749417
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/80597450
type: Comment
type: QuestionComment
has text: @KenWei [link] (https://www.google.ru/search?q=mnist+%D0%BA%D0%B0%D1%80%D1%82%D0%B8%D0%BD%D0%BA%D0%B8&newwindow=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi5iqK-mPzWAhUDJ5oKHT38AeQQ_AUICigB&biw=1350&bih=675#imgdii=sj08Q9EcrWfzBM:&imgrc=rU4Z5sMB-yONiM:)
score: 0
comment on: http://stackoverflow.com/q/46822207

http://stackoverflow.com/comment/80632254
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46807792
type: Comment
has text: i have checked the below code now it works perfectly string = input("Enter a string: ") length = len(string) while (not( (string[0] == "b" or string[0] == "B") and (string[length-1] == "z" or string[length-1] == "Z") and (length == 6))): print("Error!") string = input("Enter a string: ") print("Nice! ")

http://stackoverflow.com/a/59308800
score: 12
upvote count: 12
downvote count: 0
has body: You can use the built-in ipaddress library: import ipaddress network = ipaddress.IPv4Network('10.0.0.20/255.255.255.0', strict=False) print(network.network_address) Result: 10.0.0.0
type: Answer
answers question: http://stackoverflow.com/q/46881328

http://stackoverflow.com/comment/80701730
type: Comment
comment on: http://stackoverflow.com/q/46877099
has text: Did the original function work?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80588538
type: AnswerComment
has text: My test shows this slower than all the OP's options.
type: Comment
comment on: http://stackoverflow.com/a/46820312
score: 0

http://stackoverflow.com/q/46897950
tagged with: global
has title: Python change variable in another module and save it
has comment: http://stackoverflow.com/comment/80743543
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: package
has answer: http://stackoverflow.com/a/46898248
has comment: http://stackoverflow.com/comment/80743323
tagged with: python
score: 2
has body: I have a simple python package named my_package with three files: init.py from .a import func from .settings import var settings.py var = 1 a.py import .settings def func(): settings.var = 2 When I add this package to PATH and import it I run below script, couldn't get expected result: import my_package my_package.func() print(my_package.var) I am expecting to get '2' but it returns '1'. What am I doing wrong here?
linked to: http://stackoverflow.com/q/1977362
tagged with: global-variables
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/q/46881107
accepted answer: http://stackoverflow.com/a/46881259
has title: Python - calculating a gradient
score: 0
has comment: http://stackoverflow.com/comment/80709533
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80709526
type: Question
tagged with: numpy
tagged with: math
answer count: 2
has answer: http://stackoverflow.com/a/46881259
favorite count: 0
possible better answer: http://stackoverflow.com/a/76927242
has answer: http://stackoverflow.com/a/76927242
linked to: http://stackoverflow.com/q/67468493
tagged with: python
has body: If I have some function as array and I want to calculate its gradient then I am going to use the gradient function: from numpy import gradient g = gradient(f) Then I get that gradient, but If I want to let the gradient to be equal to zero, how can I find the extreme points? Normally I am not a programmer and I am using Python. I don't understand how to write a function like that yet. It's for my physics project. I understand that if I just write that the gradient equals zero that I will just save the value zero. But when I tried to write that function (million times) I have always failed, mostly syntax problem. Am I right it's going to be 'if' function please? Does anyone has some example? Thanks.
type: AnsweredQuestion

http://stackoverflow.com/q/46792418
has answer: http://stackoverflow.com/a/53032468
has answer: http://stackoverflow.com/a/46815935
downvote count: 1
tagged with: unit-testing
type: Question
has body: I'm using Py.Test to test functions in a Python Flask app. I have the tests passing fine when I use one "app_test.py" file that contains all the fixtures and tests. Now that I've split the fixtures into their own module, and separated the tests into different modules which each import the fixtures module I'm running into issues. If I run tests on each module individually, everything passes fine: pytest tests/test_1.py, pytest tests/test_2.py, pytest tests/test_3.py, etc. However trouble starts if I want to run all the tests in sequence with one command, e.g. pytest tests. I get the first module of tests passing and all future ones report an error: AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late. E To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests. All the tests and fixtures in one file looks something like this: # app_test.py from flask_app import create_app @pytest.fixtures(scope="session") def app(request): app = create_app() with app.app_context(): yield app @pytest.fixture(scope="session"): def client(request, app): client = app.test_client() return client def test1(client): # test body def test2(client): # test body ... I run $ pytest app_test.py and everything runs perfectly. Now let's say we split those into three different modules: fixures.py, test_1.py and test_2.py. The code now looks like this. # tests/fixtures.py from flask_app import create_app @pytest.fixtures(scope="session") def app(request): app = create_app() with app.app_context(): yield app @pytest.fixture(scope="session"): def client(request, app): client = app.test_client() return client # tests/test_1.py from tests.fixtures import app, client def test_1(client): # test body # tests/test_2.py from tests.fixtures import…
tagged with: flask
answer count: 2
accepted answer: http://stackoverflow.com/a/46815935
favorite count: 0
tagged with: python-3.x
upvote count: 8
has title: PyTest fails on a directory with multiple test files when modularizing fixtures
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53032468
tagged with: pytest
score: 7

http://stackoverflow.com/a/46763239
type: Answer
has comment: http://stackoverflow.com/comment/80471707
has comment: http://stackoverflow.com/comment/80472131
has comment: http://stackoverflow.com/comment/80471901
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46763025
answers question: http://stackoverflow.com/q/46763025
has comment: http://stackoverflow.com/comment/80472094
score: 1
has comment: http://stackoverflow.com/comment/80471731
has body: Like I mentioned, you'll need to import your data first, then filter it, and then join your filtered columns. df = pd.read_excel("my_excel.xlsx", skiprows=[0]) m = df.isin(['CUP']).any(axis=0) mystring = ' '.join(df.loc[:, m].values.ravel('F'))
upvote count: 1
has comment: http://stackoverflow.com/comment/80472446
has comment: http://stackoverflow.com/comment/80471850
type: AcceptedAnswer

http://stackoverflow.com/q/46821732
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
has title: Why can't an `async def` coroutine function contain any `yield`?
upvote count: 1
type: Question
has body: From Python in a Nutshell, why is it that An async def coroutine function cannot contain any yield. Thanks.
has answer: http://stackoverflow.com/a/46821779

http://stackoverflow.com/q/46876847
type: Question
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/80701853
tagged with: pandas
has body: I have a code which web scraps and returns the data to excel. However, there are more than 1 webpages. The code works but overwrites the data from the previous webpage scrapped. Any help? for i in range(1,4): url="https:..." response=request.get(url) soup=BeautifulSoup(response.text) data=soup.find_all("td",{"class"}) results=[] for item in data: results.append(item.text) writer=pd.ExcelWriter("test.xlsx",engine='xlsxwriter')df=pd.DataFrame(np.array(results).reshape(20,7),colums=list(abcdefg")) df.to_excel(writer, sheet_name-'Sheet1') writer.save thank you in advance :)
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80701017
has comment: http://stackoverflow.com/comment/80736652
tagged with: python
has comment: http://stackoverflow.com/comment/80700970
has answer: http://stackoverflow.com/a/46877636
tagged with: xlsxwriter
has title: Pandas xlsxwriter : find first empty row

http://stackoverflow.com/q/46838799
score: 0
tagged with: scikit-learn
tagged with: tf-idf
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80625387
has body: I have data class 'scipy.sparse.csr.csr_matrix' looks like (0, 55) 1 (0, 54) 1 (1, 55) 1 (1, 54) 1 (1, 55) 1 (1, 54) 1 (2, 945) 1 (2, 945) 1 (2, 950) 1 ... I need to transform it. First I try to use sklearn.feature_extraction.text.TfidfTransformer but it doesn't improve value of roc_auc And next I try to use from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer(max_features=13, max_df=0.5, min_df=0.1, ngram_range=(1, 2)) data_tfidf = tfidf.fit_transform(data) But it returns an error AttributeError: lower not found How can I fix that?
answer count: 0
has comment: http://stackoverflow.com/comment/80631833
type: Question
has comment: http://stackoverflow.com/comment/80625389
has title: Sklearn: using TfidfVectorizer

http://stackoverflow.com/comment/80761445
comment on: http://stackoverflow.com/q/46902090
score: 0
type: Comment
type: QuestionComment
has text: the whole point of ajax is to avoid page refreshes, navigation, postbacks etc. Ajax clients don't automatically follow redirect headers returned by the server (like a browser would in a traditional postback) for precisely this reason. If you need to redirect after the POST, then a traditional postback is more suitable, no need for ajax.

http://stackoverflow.com/q/46751879
has title: Switch anaconda python version which runs in IDE
tagged with: anaconda
has body: I am new to coding. I installed anaconda2 and installed python36 as a environment in anaconda2. And I activate python36 in the anaconda prompt. Then, I run the following codes on pycharm to test whether my version is switched to python36. print('3 / 2 =', 3 / 2) It returns 3 / 2 = 1 The result supposed to be 1.5. Seems it doesn't work. Is there any thing wrong with my steps? Can I switch version which runs in IDE by activate py36 in prompt? Another question is what is the difference between anaconda3 and anaconda2 which activated python3.x? Do I need download anaconda3 and switch interpreter in my IDE sitting?
type: Question
linked to: http://stackoverflow.com/q/37442494
answer count: 1
has comment: http://stackoverflow.com/comment/80449591
has answer: http://stackoverflow.com/a/46783570
accepted answer: http://stackoverflow.com/a/46783570
has comment: http://stackoverflow.com/comment/80449743
score: 0
has comment: http://stackoverflow.com/comment/80449757
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/46753088
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Here is an example: string = """Data 2017-10-12 Nr lekcji 6 Nauczyciel Name Nothing Rodzaj sprawdzian Przedmiot Math Opis This is just a test. Data dodania 2017-10-01 18:12:31 """ # Clean the input data by splitting by row and removing blanks clean = [i.strip() for i in string.split("\n") if i] # Assume the data is in pairs and group them in key,pair by using index # and index+1 in [0,2,4,6...] d = {clean[ind]:clean[ind+1] for ind in range(0,len(clean),2)} print(d) Returns: {'Data': '2017-10-12', 'Data dodania': '2017-10-01 18:12:31', 'Nauczyciel': 'Name Nothing', 'Nr lekcji': '6', 'Opis': 'This is just a test.', 'Przedmiot': 'Math', 'Rodzaj': 'sprawdzian'}
type: Answer
accepted answer of: http://stackoverflow.com/q/46752942
score: 2
answers question: http://stackoverflow.com/q/46752942

http://stackoverflow.com/comment/80568689
has text: can not send keys to 'availability', 'epic exposures' and 'submit' now.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46792565

http://stackoverflow.com/comment/102276081
comment on: http://stackoverflow.com/a/49893339
score: 0
type: AnswerComment
type: Comment
has text: mysqlclient also worked for me. And there is no need to put any code in __init__.py, you just need to install the package and change the database connection properties in the settings.py file

http://stackoverflow.com/a/46870257
upvote count: 2
has body: def sum(l1, l2, result = None, id = 0): if result is None: result = [] if id &lt; min(len(l1), len(l2)): result.append(l1[id] + l2[id]) return sum(l1, l2, result, id + 1) else: if len(l1)&gt;len(l2): biggest=l1 else: biggest=l2 return result+biggest[id:] Input r=sum([1,5,3,2],[4,5,9,8,15]) Output [5, 10, 12, 10, 15]
answers question: http://stackoverflow.com/q/46870115
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/46870095
tagged with: python
has title: Pandas Plotting Date Frequency
duplicate of: http://stackoverflow.com/q/32572419
score: 0
has comment: http://stackoverflow.com/comment/80687698
tagged with: plot
has comment: http://stackoverflow.com/comment/80687519
tagged with: matplotlib
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80687621
answer count: 0
has body: I am new to Pandas and trying to plot some data from a DataFrame but would like all DateTime values visible on the x-axis. However, when I plot the data I am only seeing 5 out of the 25 DateTimes plotted. How can I specify to display all datetimes on the x-axis? Below is my code as well as the chart generated that shows only 5 of the 25 datetimes plotted. My DataFrame 0 Degrees 10/21 14:55 93.1 10/21 15:10 92.3 10/21 15:25 93.5 10/21 15:40 95.2 10/21 15:55 93.1 10/21 16:10 93.8 10/21 16:25 95.1 10/21 16:40 90.8 10/21 16:55 91.1 10/21 17:10 92.4 10/21 17:25 94.3 10/21 17:40 94.6 10/21 17:55 94.6 10/21 18:10 95.5 10/21 18:25 98.6 10/21 18:40 95.7 10/21 18:55 97.0 10/21 19:10 95.8 10/21 19:25 96.6 10/21 19:40 95.7 10/21 19:55 91.3 10/21 20:10 95.6 10/21 20:25 97.6 10/21 20:40 95.3 10/21 20:55 95.3 Code: import pandas as pd desired_width = 400 pd.set_option('display.width', desired_width) import matplotlib.pyplot as plt from pylab import rcParams import re rcParams['figure.figsize'] = 12, 6 fig = plt.figure() ax = fig.add_subplot(111) df.Degrees.plot(kind='line', color='maroon', linestyle='--', alpha=0.5, marker='o', label="Test Report") ax.legend(loc='lower right') ax.legend(loc="lower left", fontsize=9, bbox_to_anchor=(0.0, 0.060)) ax.tick_params(axis='both', which='both', labelsize=7.5) plt.tight_layout() fig.autofmt_xdate() plt.show() plt.close() Chart Output:
has comment: http://stackoverflow.com/comment/80687628
has comment: http://stackoverflow.com/comment/80687655
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/80687648
linked to: http://stackoverflow.com/q/32572419

http://stackoverflow.com/q/46858715
tagged with: arrays
accepted answer: http://stackoverflow.com/a/46858820
score: 0
answer count: 1
has body: I have these two arrays slist = np.arange(1,1723,50) #List of start index elist = np.arange(50,1800,50) #End index This 'G'+'{:0&gt;5}'.format(slist[0])+"-"+'{:0&gt;5}'.format(elist[0]) gives me: 'G00001-00050' I want to do this over all the elements of slist and elist. How can I do this? The idea is to construct a array list which I'll use to import files which have them as strings in file names
tagged with: python
has title: How can I create an array by concatenating from 2 arrays?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46858820
type: Question
tagged with: numpy

http://stackoverflow.com/comment/80677514
type: QuestionComment
has text: @Code-Apprentice: Thanks for the input. I just find it hard to believe there is not a way to do it within the datetime module.
type: Comment
comment on: http://stackoverflow.com/q/46864957
score: 0

python-requests
tags question: http://stackoverflow.com/q/46876652
tags question: http://stackoverflow.com/q/46871253
tags question: http://stackoverflow.com/q/46776298
tags question: http://stackoverflow.com/q/46870368
tags question: http://stackoverflow.com/q/46887162
tags question: http://stackoverflow.com/q/46795467
tags question: http://stackoverflow.com/q/46751127
tags question: http://stackoverflow.com/q/46857087
type: Tag
tags question: http://stackoverflow.com/q/46889283
tags question: http://stackoverflow.com/q/46777164
tags question: http://stackoverflow.com/q/46881720
tags question: http://stackoverflow.com/q/46878216
tags question: http://stackoverflow.com/q/46897955
tags question: http://stackoverflow.com/q/46768322
tags question: http://stackoverflow.com/q/46867028
tags question: http://stackoverflow.com/q/46754742
tags question: http://stackoverflow.com/q/46862719
tags question: http://stackoverflow.com/q/46800101
tags question: http://stackoverflow.com/q/46882276
tags question: http://stackoverflow.com/q/46855146
tags question: http://stackoverflow.com/q/46875777
tags question: http://stackoverflow.com/q/46833888
tags question: http://stackoverflow.com/q/46799234
tags question: http://stackoverflow.com/q/46781563
tags question: http://stackoverflow.com/q/46790021
tags question: http://stackoverflow.com/q/46789770
tags question: http://stackoverflow.com/q/46800437
tags question: http://stackoverflow.com/q/46868702
tags question: http://stackoverflow.com/q/46860838
tags question: http://stackoverflow.com/q/46774009
tags question: http://stackoverflow.com/q/46866677
tag name: python-requests
tags question: http://stackoverflow.com/q/46862996
tags question: http://stackoverflow.com/q/46792756
tags question: http://stackoverflow.com/q/46836616
tags question: http://stackoverflow.com/q/46858686
tags question: http://stackoverflow.com/q/46885331
tags question: http://stackoverflow.com/q/46859990
tags question: http://stackoverflow.com/q/46836499
tags question: http://stackoverflow.com/q/46783078
tags question: http://stackoverflow.com/q/46897501
tags question: http://stackoverflow.com/q/46759689

http://stackoverflow.com/a/46798601
answers question: http://stackoverflow.com/q/46798445
type: Answer
upvote count: 1
has body: You can try this: import re data = open('filename.txt').read() the_key = re.findall("^\n*[\.\d]+", data) values = [re.split("\s+\=\s+", i) for i in re.findall("[a-zA-Z0-9]+\s*\=\s*[a-zA-Z0-9]+", data)] final_data = {the_key[0]:dict(values)} Output: {'\n.1.3.6.1.4.1.14823.1.1.27': {'VENDOR': 'Aruba', 'CERTIFICATION': 'CERTIFIED', 'Fault': 'MIB2', 'VLAN': 'Dot1q', 'Environment': 'ArubaSysExt', 'HEALTH': 'ARUBA', 'Memory': 'ArubaController', 'Performance': 'MIB2', 'CONT': 'Aruba', 'MODEL': 'ArubaS3500', 'TYPE': 'Switch'}}
score: 1
downvote count: 0

http://stackoverflow.com/comment/80737748
type: Comment
comment on: http://stackoverflow.com/q/46895204
score: 1
has text: Json format doesn't mean you magically get a dictionary. You have a list apparently.
type: QuestionComment

http://stackoverflow.com/q/46901021
has title: Error when running python code in R
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80749548
has comment: http://stackoverflow.com/comment/80749454
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/46901305
has body: I am trying to run the following python code csv2po.py through R: # -*- coding: utf-8 -*- # # Copyright 2003-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # translate is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see &lt;http://www.gnu.org/licenses/&gt;. """Convert Comma-Separated Value (.csv) files to Gettext PO localization files. See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/csv2po.html for examples and usage instructions. """ import logging from translate.storage import csvl10n, po logger = logging.getLogger(__name__) def replacestrings(source, *pairs): """Use ``pairs`` of ``(original, replacement)`` to replace text found in ``source``. :param source: String to on which ``pairs`` of strings are to be replaced :type source: String :param \*pairs: Strings to be matched and replaced :type \*pairs: One or more tuples of (original, replacement) :return: String with ``*pairs`` of strings replaced """ for orig, new in pairs: source = source.replace(orig, new) return source def quotecsvstr(source): return '"' + \ replacestrings(source, ('\\"', '"'), ('"', '\\"'), ("\\\\'", "\\'"), ('\\\\n', '\\n')) + \ '"' def simplify(string): return ''.join(filter(type(string).isalnum, string)) class csv2po(object): """a class that takes translations from a .csv file and puts them in a .po file """ def __init__(self, templatepo=None, charset=None, duplicatestyle="keep"): """construct the converter...""" se…
has comment: http://stackoverflow.com/comment/80749494
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/46901305
has comment: http://stackoverflow.com/comment/80749450
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/80749413
has comment: http://stackoverflow.com/comment/80749110

http://stackoverflow.com/q/46872671
type: Question
accepted answer: http://stackoverflow.com/a/46872724
tagged with: python-2.7
answer count: 3
has body: I was working on a practice problem in a website and got stuck at a point. The question is: Position Digits Sum The program must accept two positive integers as the input and then print the sum of their unit digits, tenth digits and so on. Input Format: The first line will contain A and B separated by a space. Output Format: The first line will contain the sum of unit digits, tenth digits and so on with the values separated by a space. Boundary Conditions: 1 &lt;= A,B &lt;= 9999999 Example Input/Output 1: Input: 23 49 Output: 12 6 Example Input/Output 2: Input: 12456 687 Output: 13 13 10 2 1 Well I solved the problem but out of 6 test cases (which are hidden) 5 cases passed and 1 didn't. This is my code: a,b = input().split() assert 1&lt;=len(a)&lt;=7 and 1&lt;=len(b)&lt;=7 assert a.isdigit() == True and b.isdigit() == True if len(a)&gt;1 and len(b)&gt;1: assert a[0] != '0' and b[0] != '0' h = [] m = [] def pp(a,b): c = [] for i in range(1,len(a)+1): x = int(a[-i])+int(b[-i]) c.append(x) return c if len(a)==len(b): g = pp(a,b) y = [str(i) for i in g] for i in range(0,len(y)-1): y[0] = y[0]+' '+y[1] y.remove(y[1]) print(y[0]) if len(a)&gt;len(b): d = abs(len(a)-len(b)) for i in range(0,d): h.append(a[i]) r = a.replace(a[0:d],'') p = pp(r,b) p = p+h[::-1] t = [str(i) for i in p] for i in range(0,len(t)-1): t[0] = t[0]+' '+t[1] t.remove(t[1]) print(t[0]) if len(a)&lt;len(b): d = abs(len(a)-len(b)) for i in range(0,d): m.append(b[i]) u = b.replace(b[0:d],'') q = pp(a,u) q = q + m[::-1] e = [str(i) for i in q] for i in range(0,len(e)-1): e[0] = e[0]+' '+e[1] e.remove(e[1]) print(e[0]) I am a beginner, so I only used simple python code which made it to too long. I checked but didn't get what is wrong in it. Any help?
downvote count: 0
has answer: http://stackoverflow.com/a/46872788
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46872788
tagged with: python
has title: Position Digits Sum (Sum of digits in two numbers based on their position)
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/46872724
has answer: http://stackoverflow.com/a/46882998

http://stackoverflow.com/comment/80537733
score: 0
has text: @DanielF I apologise if the `entire code` seems not to be minimal. Why would you say it is not a MWE? If you copy and paste that `entire code`, you will get exactly all the errors I mention in the post. If this post seems long is because I wanted to explain in detail the problem
comment on: http://stackoverflow.com/q/46787345
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80641755
type: AnswerComment
has text: Does tkinters `entry.get()` return int if its get is only int? or does it always, no matter the input, grab the input as a str?
type: Comment
comment on: http://stackoverflow.com/a/46847039
score: 0

http://stackoverflow.com/comment/80668205
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46860218
type: Comment
has text: Append is an O(1) operation. I was just imaging replacing `x[i: i + 1]` with `[x[i]]`. However, the finally concatenation bounds the runtime at O(n) anyway, which is the worst case of slice lookup, so it really doesn't matter.

http://stackoverflow.com/comment/80471093
type: QuestionComment
comment on: http://stackoverflow.com/q/46762884
type: Comment
has text: Thanks @downshift , I did see that thread before posting my question but unafortunately I'm not able to use any of those solutions. As you can see, the first codeblock I put on my question comes from one of the bottom answers of that thread, but it doesn't works :/
score: 0

http://stackoverflow.com/a/46890600
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46890548
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46890548
has body: Keeping the order you used: if x is None and y is None: # code here for x = None = y elif x is not None and y is not None: # code here for x != None != y elif x is None: # code here for x = None != y else: # code here for x != None = y Modifying the order to reduce boolean evaluations: if x is None and y is None: # code here for x = None = y elif x is None: # code here for x = None != y elif y is None: # code here for x != None = y else: # code here for x != None != y In a 4 case scenario, you should consider which of the options has a higher probability and which has the second higher and keep them the first two options, as this will reduce the amount of conditions checked during execution. The last two options will both execute the 3 conditions so the order of these two doesn't matter. For example the first code above considers that prob(x=None &amp; y=None) &gt; prob(x!=None &amp; y!=None) &gt; prob(x=None &amp; y!=None) ~ prob(x!=None &amp; y=None) while the second one considers that prob(x=None &amp; y=None) &gt; prob(x=None &amp; y!=None) &gt; prob(x!=None &amp; y=None) ~ prob(x!=None &amp; y!=None)

http://stackoverflow.com/comment/80677926
has text: Oops I meant to write pip install gluon, which I've done. Also this will be using python2.7. I've used: sudo apt-get install python2.7-gluon but it says that it coudlnt find a matching distribution
comment on: http://stackoverflow.com/a/46865195
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/46890707
has body: you can start by using the elif statement, it will be a little bit shorter just like this: if x is None and y is None: # code here elif x is not None and y is not None: # code here elif x is None: # code here if y is None: # code here`
answers question: http://stackoverflow.com/q/46890548
type: Answer
score: 0

http://stackoverflow.com/comment/80589669
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46820975
has text: I might need to change the nevironement of my anaconda to python27 for this
score: 0

http://stackoverflow.com/a/46778702
has body: IIUC you don't need to loop, you can simply use boolean indexing: new_df = df.loc[df['track'].isin(other_tracks)]
answers question: http://stackoverflow.com/q/46778674
has comment: http://stackoverflow.com/comment/80503457
accepted answer of: http://stackoverflow.com/q/46778674
type: Answer
has comment: http://stackoverflow.com/comment/80503223
downvote count: 0
has comment: http://stackoverflow.com/comment/80503379
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/80661931
comment on: http://stackoverflow.com/a/46857112
score: 0
type: Comment
has text: It's a strange question but definitely an interesting one?
type: AnswerComment

http://stackoverflow.com/a/46775484
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/93345725
type: Answer
accepted answer of: http://stackoverflow.com/q/46764574
score: 1
answers question: http://stackoverflow.com/q/46764574
upvote count: 1
has body: There are a few things here. To start, I don't think you're going to see much gain with running different types of requests in different processes. Your disconnect handlers are probably going to be very light - not doing much besides cleanup. Connect might not do much either and receive will get most of the load. You're betting off using the --threads parameter and starting multiple threads. Your current setup would only run one thread for each type of handler. The way runworker works is that it communicates with Daphne over your channel layer (ex Redis). All of the workers are listening to a queue. When a request comes in one worker will process it. While that worker is processing the request the other workers will wait for subsequent requests and process them. Once they send their response they go back to listening to the queue. If there are no --only-channels specified, each process will be pulling off requests and working on them as fast as it can and none of them will be waiting around. Its up to you to find the best balance of threads/workers by running multiple processes and the --threads parameter. You can also have workers reserved for heavy channels so they don't bring down your site. Having multiple Daphne instances will help. But since all they do is send messages between your server and the workers you might not see the benefit of running 4 of them. Everything stated here is not appliacable to Channels 2. This is for the old version of Django Channels.
has comment: http://stackoverflow.com/comment/93403367
has comment: http://stackoverflow.com/comment/80513047
has comment: http://stackoverflow.com/comment/93346072

http://stackoverflow.com/comment/80628969
has text: All I've got is a vague hand-wavy "inheritance". :) But exactly why, not sure.
comment on: http://stackoverflow.com/q/46840319
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80540163
type: QuestionComment
has text: Well, start [here](https://docs.python.org/3/library/zipfile.html).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46796395

http://stackoverflow.com/q/46752209
linked to: http://stackoverflow.com/q/13832911
tagged with: ajax
has comment: http://stackoverflow.com/comment/80450457
favorite count: 0
has answer: http://stackoverflow.com/a/46752440
has comment: http://stackoverflow.com/comment/80450627
type: UnansweredQuestion
has body: I have a problem, i cant open render_template after post data with ajax. this is my ajax code. if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'negasi') $.ajax({ data: { metodeSkoring: skoring }, type: 'POST', url: '/evaluasiModel' }) } and this is my server code. @app.route('/evaluasiModel', methods=['POST',"GET"]) def evaluasiModel(): metodeSkoring = request.form['metodeSkoring'] metodeSkoring = int(metodeSkoring) return render_template("evaluasiModelKlasifikasi.html", hasilSkoring = metodeSkoring) i hope after post data ajax to "def evaluasiModel()", I can open render_template "evaluasiModelKlasifikasi.html" and get data metodeSkoring to show in this template.
tagged with: python
has answer: http://stackoverflow.com/a/46752537
has comment: http://stackoverflow.com/comment/80450545
duplicate of: http://stackoverflow.com/q/13832911
upvote count: 5
has title: How render template after post data with ajax in FLASK?
downvote count: 1
type: Question
answer count: 2
tagged with: javascript
tagged with: jquery
score: 4
tagged with: flask

http://stackoverflow.com/a/47523651
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82089631
has comment: http://stackoverflow.com/comment/82081588
score: 6
has comment: http://stackoverflow.com/comment/102619889
has comment: http://stackoverflow.com/comment/82164367
has body: This works for me (mostly): keyboard.send_keys("&lt;ctrl&gt;+&lt;shift&gt;+u+" + "012b") keyboard.send_keys("&lt;ctrl&gt;") It seems to depend on the app you are writing to, the desktop environment, the distro and the version thereof... For example, it is working now in this window - but it's not working inside LibreOffice Writer on KDE/Manjaro (although it was working there a few months ago).
has comment: http://stackoverflow.com/comment/82159494
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/126865243
accepted answer of: http://stackoverflow.com/q/46878824
has comment: http://stackoverflow.com/comment/133012563
answers question: http://stackoverflow.com/q/46878824

http://stackoverflow.com/comment/131915501
comment on: http://stackoverflow.com/a/74650195
score: 1
has text: Very cool, marked as correct answer!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80560669
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46806715
has text: I want each value in the CSV to be a tuple.

http://stackoverflow.com/q/46820353
has title: Click "show more" button until all data in table is shown and fetch all data from table
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46822948
score: 1
tagged with: selenium
upvote count: 1
type: Question
has body: I need to fetch all data from the table on this page https://www.nets.eu/dk-da/l%C3%B8sninger/Registreringsnumre But I need to click the "show more" button until all data is shown.. But no matter how many time I click the "show more" button the table keeps having 30 rows..!? import sys import time from pyvirtualdisplay import Display from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import json class Scrape: display = None driver = None def __init__(self): # Start display self.display = Display(visible=0, size=(800, 600)) self.display.start() # Init driver self.driver = webdriver.Firefox() self.driver.wait = WebDriverWait(self.driver, 5) self.load_page() time.sleep(5) self.close() def load_page(self): data = [] url = 'https://www.nets.eu/dk-da/l%C3%B8sninger/Registreringsnumre' xpath = '//table[@class="itera-DataTable"]/tbody/tr' self.driver.get(url) try: table = self.driver.wait.until(EC.presence_of_element_located( (By.CLASS_NAME, 'itera-DataTable'))) print 'Table found!' i = 1 while True: button = self.driver.wait.until(EC.presence_of_element_located( (By.CLASS_NAME, 'itera-nextbatchbox'))) print 'Button %d found!' % (i) row_count = len(self.driver.find_elements_by_xpath(xpath)) print row_count button.click() i += 1 if i &gt; 5: break i = 1 for tr in self.driver.find_elements_by_xpath(xpath): print 'TR %d' % (i) tr_data = [] tds = tr.find_elements_by_tag_name('td') if tds: tr_data.append([td.text for td in tds]) data.append(tr_data) i += 1 #print json.dumps(data) except TimeoutException: self.error('Table not found') def error(self, str): self.close() print&gt;&gt;sys.stderr, str sys.exit(1) def close(self): if self.driver is not None: self.driver.quit() self.display.stop() if __name__ == '__main__': Scrape()
accepted answer: http://stackoverflow.com/a/46822948
has comment: http://stackoverflow.com/comment/80588229
has comment: http://stackoverflow.com/comment/80590785
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/80686254
type: QuestionComment
comment on: http://stackoverflow.com/q/46869500
has text: @chepner ... I need `list0`, `list1`, and `pairs` in other functions that I haven't put here. I will try your advice though as to `__add__`. Thanks
score: 0
type: Comment

performance
tags question: http://stackoverflow.com/q/46810714
tags question: http://stackoverflow.com/q/46842951
tags question: http://stackoverflow.com/q/46896785
tags question: http://stackoverflow.com/q/46788035
tags question: http://stackoverflow.com/q/46808236
tags question: http://stackoverflow.com/q/46810801
tags question: http://stackoverflow.com/q/46757534
tag name: performance
tags question: http://stackoverflow.com/q/46819188
tags question: http://stackoverflow.com/q/46774681
tags question: http://stackoverflow.com/q/46859304
tags question: http://stackoverflow.com/q/46896347
tags question: http://stackoverflow.com/q/46757639
type: Tag
tags question: http://stackoverflow.com/q/46901188
tags question: http://stackoverflow.com/q/46774685

http://stackoverflow.com/comment/80501240
score: 0
has text: `with` is a keyword to handle context management, what exactly do you expect that to do in this scenario?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46777749

inventory
tags question: http://stackoverflow.com/q/46830958
type: Tag
tag name: inventory

http://stackoverflow.com/q/46827915
has answer: http://stackoverflow.com/a/46829709
accepted answer: http://stackoverflow.com/a/46829709
type: Question
tagged with: time-series
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/80606335
answer count: 1
has body: I've got a frame df where columns are ['date', 'float', 'int'] to simplify. The dates and floats are not unique so I group them: dd = df.groupby(['date', 'float']).sum() Thing is, I need to resample the date index, which I have to do via dd = dd.unstack().resample('B').last() otherwise without unstacking it will drop a level. Now what I'd like to do is plot a scatter of the frame with 'date' as x axis, 'float' as y axis, and 'int' as the size of the dots. I'm struggling to achieve this with the frame I now have. Maybe the pre-processing I do is the wrong kind and there's a cleaner way to achieve this. Regards,
tagged with: python
tagged with: plot
type: AnsweredQuestion
has title: scatter plot of grouped time series frame
tagged with: matplotlib

http://stackoverflow.com/q/46819565
accepted answer: http://stackoverflow.com/a/46819667
has comment: http://stackoverflow.com/comment/80586759
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80586769
has body: I am very new to python, and want to make a program that swaps the lower and upper case. That is no problem, but I am having trouble with shuffling the words. This is my code: def swap_lower_upper(zin): print(zin.swapcase()) def shuffle(zin): import random lijst = list(zin) random.shuffle(lijst) print (lijst) swap_lower_upper('Dit IS een test') shuffle('Dit IS een test') I've tried many things but I can't seem to let the shuffle work. I would greatly appreciate your help! Thanks in advance.
has answer: http://stackoverflow.com/a/46819667
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: shuffle
has title: I need to perform a shuffle but I can't seem to let it work
type: Question

http://stackoverflow.com/comment/80689054
type: QuestionComment
score: 2
has text: SimpleHTTPServer and CGIHTTPServer are ok for testing and for private work, but they don't provide much in the way of security, so if you intend to expose your server to the real Internet then you should use a proper server like Apache. It's pretty easy to configure Apache to accept .py files as CGI scripts.
comment on: http://stackoverflow.com/q/46855638
type: Comment

http://stackoverflow.com/comment/80619278
comment on: http://stackoverflow.com/a/46835762
type: Comment
has text: Could you elaborate on what all this is doing? Would something like `all(pswrd[i] != pswrd[i+1] for i in xrange(len(pswrd)-1))` not be simpler?
score: 0
type: AnswerComment

http://stackoverflow.com/q/46860197
type: AnsweredQuestion
downvote count: 0
has body: My current doc2vec code is as follows. # Train doc2vec model model = doc2vec.Doc2Vec(docs, size = 100, window = 300, min_count = 1, workers = 4, iter = 20) I also have a word2vec code as below. # Train word2vec model model = word2vec.Word2Vec(sentences, size=300, sample = 1e-3, sg=1, iter = 20) I am interested in using both DM and DBOW in doc2vec AND both Skip-gram and CBOW in word2vec. In Gensim I found the below mentioned sentence: "Produce word vectors with deep learning via word2vec’s “skip-gram and CBOW models”, using either hierarchical softmax or negative sampling" Thus, I am confused either to use hierarchical softmax or negative sampling. Please let me know what are the differences in these two methods. Also, I am interested in knowing what are the parameters that need to be changed to use hierarchical softmax AND/OR negative sampling with respect to dm, DBOW, Skip-gram and CBOW? P.s. my application is a recommendation system :)
upvote count: 8
type: Question
accepted answer: http://stackoverflow.com/a/46867142
tagged with: doc2vec
linked to: http://stackoverflow.com/q/46970376
has answer: http://stackoverflow.com/a/46867142
answer count: 1
score: 8
favorite count: 0
tagged with: word2vec
tagged with: python
tagged with: gensim
tagged with: nlp
has title: Doc2vec and word2vec with negative sampling

http://stackoverflow.com/a/46856589
type: Answer
answers question: http://stackoverflow.com/q/46854798
accepted answer of: http://stackoverflow.com/q/46854798
has body: You need to tell pymongo where is the database you want it to connect to. Like many other ORMs/database-connectors pymongo uses a connection string. In Mongo's case it starts with mongodb:// (denoting the schema/protocol, just like http:// or ftp://). Then comes the host (either a hostname or an IP), which denotes the machine/server on which the database resides, and lastly the port the server listens on. If the database is on the same machine as the code, you should use 127.0.0.1 or localhost as the host.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/46785924
has comment: http://stackoverflow.com/comment/80518317
tagged with: bash
has comment: http://stackoverflow.com/comment/80518452
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80518465
favorite count: 0
has comment: http://stackoverflow.com/comment/80518243
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46785996
tagged with: python
linked to: http://stackoverflow.com/q/3172470
upvote count: 3
has comment: http://stackoverflow.com/comment/80518203
has body: I would like to check the result of a Bash command in a Python script. I'm using subprocess.check_output(). Before that, I checked manually the result of two commands in a shell: user@something:~$ hostname &gt; something user@something:~$ command -v apt &gt; /usr/bin/apt It works as expected. Now I'm trying to run the subprocess.check_output() function in the Python interpreter: &gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.check_output(['hostname'], shell=True, stderr=subprocess.STDOUT) b'something\n' &gt;&gt;&gt; subprocess.check_output(['command', '-v', 'apt'], shell=True, stderr=subprocess.STDOUT) b'' As you can see, the first command is working as expected, but not the second (as it returns an empty string). Why is that? EDIT I already tried removing shell=True, it returns an error: &gt;&gt;&gt; subprocess.check_output(['command', '-v', 'apt'], stderr=subprocess.STDOUT) Traceback (most recent call last): [...] FileNotFoundError: [Errno 2] No such file or directory: 'command'
has title: Subprocess returns an empty string
type: Question
score: 3

http://stackoverflow.com/q/46801187
type: Question
tagged with: matplotlib
has body: I've found a few solutions close to this but i can't get my axes to label correctly still. I'm missing something small. I have a radioactive decay curve to be plotted as a straight line. I have 2 lists of data, and i plot using scatter(hours,np.log(activity),color='red') the y axis comes out as np.log(activity) as expected but i wish to make it just activity while maintaining the linear plot. using a.yaxis.set_major_formatter(ticker.FormatStrFormatter("%d")) i can change the tick labels to whatever i want but i cant assign a list to the tick labels. if i replace %d with activity[0] for instance then all ticks take that value. I hope it's clear here what im trying to do. see plot here All i want to do is multiply the y-axis ticks by np.exp(y-ticks) cheers
tagged with: axis
answer count: 1
has title: Preserve linear y-axis scaling when plotting log data in matplotlib
has answer: http://stackoverflow.com/a/46802184
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: plot

http://stackoverflow.com/a/46879847
answers question: http://stackoverflow.com/q/46879820
has comment: http://stackoverflow.com/comment/80726799
score: 4
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80707306
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46879820
type: Answer
has body: You're producing endless output and tail -n 1 is waiting for the last line of input from stdin, which never arrives.

http://stackoverflow.com/a/46864423
answers question: http://stackoverflow.com/q/46863602
upvote count: 4
has comment: http://stackoverflow.com/comment/80676751
downvote count: 0
score: 4
has body: I do not know why I addict to using apply in this strange way ... df.apply(lambda x : x.groupby(x).count()).fillna(0) Out[31]: 2017-08-09 2017-08-10 active_1 2 3.0 active_1-3 1 0.0 active_3-7 1 1.0 pre 1 1.0 Or import collections df.apply(lambda x : pd.Series(collections.Counter(x))).fillna(0) As what I expected simple for loop is faster than apply pd.concat([pd.Series(collections.Counter(df[x])) for x in df.columns],axis=1)
type: Answer

http://stackoverflow.com/comment/125153151
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46863890
has text: @Lawrence D'Oliveiro It might come from punch cards. Also, the original IBM PC(and by extension any PC in text mode) has a display of 80x25(command line linux uses graphics mode to get higher character density).
score: 0

http://stackoverflow.com/q/46874249
has title: What is pattern python
tagged with: python
has comment: http://stackoverflow.com/comment/80695511
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80695512
downvote count: 1
accepted answer: http://stackoverflow.com/a/46874322
type: Question
score: -1
has body: I've been programming in Java for the past year and this weekend I decided to throw myself in the deep-end and build a text-classifier in Python3. While naturally there's syntax distinction, there's a lot of conceptual similarities that I'm familiar with. However, I've come across pattern, something I've yet to encounter in Java. I've done some research and understand it relates to design-patterns, the 23 GoF, patterns allow for reusability of code and improves interactions with objects etc. But I don't understand how patternis used in this following block of code. For context, the text-classifier is looping through each sentence in the training data, manipulating the pre-instantiated lists, words, classes and documents. Here's the link to what I'm following - https://machinelearnings.co/text-classification-using-neural-networks-f5cd7b8765c6 for pattern in training_data(pattern['sentence']) words.extend(w) documents.append((w, pattern['class'])) if pattern['class'] not in classes: classes.append(pattern['classes']) Cheers for your help!
has comment: http://stackoverflow.com/comment/80695627
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46874322

http://stackoverflow.com/comment/80676261
comment on: http://stackoverflow.com/a/46864391
has text: @JonClements my understand of the problem is that the OP wants to delete the first `n` characters, not lines. With `re.findall` the OP can get an entire listing of all the characters in the file, and then use the list slicing technique to remove the first `n`, or build on the slicing.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46818223
tagged with: stack
possible better answer: http://stackoverflow.com/a/46819769
linked to: http://stackoverflow.com/q/46234549
linked to: http://stackoverflow.com/q/14916358
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/46818727
upvote count: 5
answer count: 3
tagged with: pandas
downvote count: 0
tagged with: melt
favorite count: 0
has answer: http://stackoverflow.com/a/73029575
has title: Pandas - melt, stack, reshape or MultiIndex dataframe columns based on multiple attributes from the column name
has answer: http://stackoverflow.com/a/46819769
tagged with: python
has answer: http://stackoverflow.com/a/46818727
type: AnsweredQuestion
has body: I have a Pandas dataframe with data in a very wide form... for example: ID Equipment Function Task exprt_cond1_time exprt_cond2_time exprt_cond1_freq exprt_cond2_freq novce_cond1_time novce_cond2_time novce_cond1_freq novce_cond2_freq 0 eq_type_1 Fxn_a task_1 12 24 0.031 0.055 15 31 0.042 0.059 1 eq_type_1 Fxn_a task_2 10 22 0.028 0.052 12 29 0.039 0.055 2 eq_type_1 Fxn_b task_3 13 25 0.033 0.057 18 34 0.047 0.062 3 eq_type_1 Fxn_b task_4 9 19 0.027 0.051 10 28 0.038 0.054 4 eq_type_2 Fxn_a task_1 14 27 0.036 0.056 16 32 0.043 0.061 5 eq_type_2 Fxn_a task_2 11 26 0.030 0.054 14 30 0.041 0.058 but I am wanting to convert it to a more tidy long format using the text in the column label to make new columns...e.g., data from the first and last rows from the above might look something more like this: ID Equipment Function Task Experience Condition Time Freq 0 eq_type_1 Fxn_a task_1 expert cond1 12 0.031 1 eq_type_1 Fxn_a task_1 expert cond2 24 0.055 2 eq_type_1 Fxn_a task_1 novice cond1 15 0.042 3 eq_type_1 Fxn_a task_1 novice cond2 31 0.059 ... 16 eq_type_2 Fxn_a task_2 expert cond1 11 0.030 17 eq_type_2 Fxn_a task_2 expert cond2 26 0.054 18 eq_type_2 Fxn_a task_2 novice cond1 14 0.041 19 eq_type_2 Fxn_a task_2 novice cond2 30 0.058 I can't figure out the right combination of melt / stack / reshape / MultiIndex or other translation functions to make this happen efficiently, or without my code becoming ugly, unwieldy, &amp; nearly unreadable. This question and this question are close and help me some, but they only seem to convert based on a single attribute in the label. Would love any help or tips from the SO community!

http://stackoverflow.com/comment/80690603
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46868751
has text: @Shiru The code has a flaw in general. You assign the username to `y` only if one exists. If you had the line `",password"` in your login details, that would result in a `NameError` when you try to use `y`. Or if this is not the first line, it will use the username from a previous line. Just remove all that `z` nonsense and after `line = line.replace('\n, '').split(',')` simply do `if line[0] == username and line[1] == password:`.

http://stackoverflow.com/comment/80460828
comment on: http://stackoverflow.com/q/46756982
type: Comment
score: 0
has text: Thnx bro can you tell me how i can find the index of the value
type: QuestionComment

http://stackoverflow.com/comment/80466644
comment on: http://stackoverflow.com/q/46760626
has text: Is numpy built in ? To python
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46806690
type: Question
has answer: http://stackoverflow.com/a/46808623
has title: Replacing values in scipy sparse csr matrix
tagged with: sparse-matrix
has body: I want to replace -1 values by zeros in a scipy.sparse.csr_matrix like this: a = [ -1 0 -1 0 -1 1 1 -1 0 -1 0 0 ] Desired output: b = [ 0 0 0 0 0 1 1 0 0 0 0 0 ]
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46808623
tagged with: python
type: AnsweredQuestion
tagged with: scipy

http://stackoverflow.com/comment/80470224
comment on: http://stackoverflow.com/q/46758107
type: Comment
score: 0
has text: This answer seems relevant: https://stackoverflow.com/questions/23661583/reading-back-tuples-from-a-csv-file-with-pandas as does this: https://stackoverflow.com/questions/29550414/how-to-split-column-of-tuples-in-pandas-dataframe
type: QuestionComment

http://stackoverflow.com/a/46863206
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If you want to fill the random 1 and random2 with maximum repititon value then you can use agg with your own function i.e eg df = pd.DataFrame({ 'id': [1,1,1,1,2,2,2], 'r1': ['x','y','y','y','x','x','x'], 'r2': ['t','I','t','t','c','c','c'] }) def max_rep(x): return x.value_counts().idxmax() ndf = df.groupby('id',as_index=False).agg({'r1': max_rep,'r2':max_rep}) or using lambda if you want that in one line ndf = df.groupby('id',as_index=False).agg({'r1': lambda x: x.value_counts().idxmax(),'r2': lambda x: x.value_counts().idxmax()}) Output : id r1 r2 0 1 y t 1 2 x c As Jon commented you can do all your steps in one line using agg i.e df.groupby('ID',as_index=False).agg('Start Date': 'min', 'End Date': 'max', 'Value': 'sum', \ 'Random 1':max_rep,'Random 2':max_rep}) In case you are looking to group along with random1 and random2 then you can use df.groupby(['ID','Random 1','Random 2'],as_index=False).agg('Start Date': 'min', 'End Date': 'max', 'Value': 'sum')
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46863079
answers question: http://stackoverflow.com/q/46863079

http://stackoverflow.com/comment/80753260
has text: this code snippet is not working . It is not resizing the images that have exif data.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46884563
type: AnswerComment

http://stackoverflow.com/comment/80632944
comment on: http://stackoverflow.com/q/46842463
score: 0
type: Comment
type: QuestionComment
has text: @VijayabhaskarJ I have updated the question with `get_costed_productions` function

http://stackoverflow.com/comment/80577242
type: Comment
has text: That should work, I always forget about the good 'ole scatter plot.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46803626

http://stackoverflow.com/q/46852222
type: AnsweredQuestion
score: 1
type: Question
has title: How can I import all of sklearns regressors
tagged with: python-import
answer count: 2
linked to: http://stackoverflow.com/q/42160313
has body: I'm doing some predictive modeling and would like to benchmark different kinds of regressors in scikit-learn, just to see what's out there and how they perform on a given prediction task. I got inspired to do this by this kaggle kernel in which the author essentially manually imports a bunch of classifiers (about 10) and benchmarks them. I'm having trouble finding a comprehensive list of imports for the regressors in sklearn so I'm trying to automatize the import statements to automatically return me a list of classes that I can use. I tried to dynamically import the classes: from importlib import import_module import sklearn def all_regressors(): regressors=[] for module in sklearn.__all__: try: regressors.extend([cls for cls in import_module(f'sklearn.{module}').__all__ if 'Regress' in cls ]) except: pass regressors.append(sklearn.svm.SVR) return regressors print(all_regressors()) But i only get back the names as strings, rather than the classes: ['RandomForestRegressor', 'ExtraTreesRegressor', 'BaggingRegressor', 'GradientBoostingRegressor', 'AdaBoostRegressor', 'GaussianProcessRegressor', 'IsotonicRegression', 'ARDRegression', 'HuberRegressor', 'LinearRegression', 'LogisticRegression', 'LogisticRegressionCV', 'PassiveAggressiveRegressor', 'RandomizedLogisticRegression', 'SGDRegressor', 'TheilSenRegressor', 'RANSACRegressor', 'MultiOutputRegressor', 'KNeighborsRegressor', 'RadiusNeighborsRegressor', 'MLPRegressor', 'DecisionTreeRegressor', 'ExtraTreeRegressor', &lt;class 'sklearn.svm.classes.SVR'&gt;] How can I get the actual classes?
accepted answer: http://stackoverflow.com/a/74650195
tagged with: scikit-learn
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46852251
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/74650195
possible better answer: http://stackoverflow.com/a/46852251

http://stackoverflow.com/comment/80491255
type: QuestionComment
score: 0
has text: Can you `print(font_dirs)` and post the output?
comment on: http://stackoverflow.com/q/46772500
type: Comment

http://stackoverflow.com/q/46771550
has comment: http://stackoverflow.com/comment/80488930
type: Question
linked to: http://stackoverflow.com/q/6663272
has comment: http://stackoverflow.com/comment/80488500
upvote count: 5
linked to: http://stackoverflow.com/q/588004
linked to: http://stackoverflow.com/q/3846631
answer count: 3
has answer: http://stackoverflow.com/a/46772066
has comment: http://stackoverflow.com/comment/80488631
has comment: http://stackoverflow.com/comment/80489088
favorite count: 0
has comment: http://stackoverflow.com/comment/80488898
has answer: http://stackoverflow.com/a/46771805
has comment: http://stackoverflow.com/comment/80488897
tagged with: python
has answer: http://stackoverflow.com/a/46771769
tagged with: c++
accepted answer: http://stackoverflow.com/a/46771805
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80488826
has body: I had to find the result of a function f(x) = x / (1-x)^2 , where 0 &lt; x &lt; 1. The value had to be formatted up to 6 decimal places only. Here is my C++ code: float x; scanf("%f",&amp;x); printf("%.6f",x/((1-x)*(1-x))); And I did for the same in Python: x = float(input()) print ("%.6f" % (x/((1-x)**2))) For some values of x, both the programs give different answers. For example, for x = 0.84567, C++ gives 35.505867 and Python gives 35.505874 Why does this happen? According to solution, the Python answers are right, while C++ answers are wrong.
linked to: http://stackoverflow.com/q/34518653
possible better answer: http://stackoverflow.com/a/46771769
has title: The same arithmetic operations give different results in C++ and Python
tagged with: floating-point
downvote count: 1

http://stackoverflow.com/q/46902357
possible better answer: http://stackoverflow.com/a/51600428
has answer: http://stackoverflow.com/a/58356973
has answer: http://stackoverflow.com/a/78509911
favorite count: 0
has answer: http://stackoverflow.com/a/65950137
score: 120
linked to: http://stackoverflow.com/q/21440230
has answer: http://stackoverflow.com/a/69130250
has answer: http://stackoverflow.com/a/67197027
linked to: http://stackoverflow.com/q/40587558
tagged with: phpmyadmin
has answer: http://stackoverflow.com/a/48236411
accepted answer: http://stackoverflow.com/a/49893339
has answer: http://stackoverflow.com/a/51600428
has answer: http://stackoverflow.com/a/71033252
tagged with: python
type: AnsweredQuestion
answer count: 20
has answer: http://stackoverflow.com/a/56558266
has body: I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL. I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with... File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module> 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts.
has answer: http://stackoverflow.com/a/49893339
tagged with: mysql
tagged with: django
has answer: http://stackoverflow.com/a/63667393
linked to: http://stackoverflow.com/q/59006602
has answer: http://stackoverflow.com/a/62125864
has answer: http://stackoverflow.com/a/61878084
type: Question
has answer: http://stackoverflow.com/a/78393763
has answer: http://stackoverflow.com/a/75711615
has title: Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
has answer: http://stackoverflow.com/a/72011620
has comment: http://stackoverflow.com/comment/80751722
linked to: http://stackoverflow.com/q/15312732
has answer: http://stackoverflow.com/a/59575613
has answer: http://stackoverflow.com/a/70461252
has answer: http://stackoverflow.com/a/53589824
upvote count: 120
has answer: http://stackoverflow.com/a/56312295
downvote count: 0

cython
tags question: http://stackoverflow.com/q/46824143
tags question: http://stackoverflow.com/q/46819188
tags question: http://stackoverflow.com/q/46855221
tags question: http://stackoverflow.com/q/46854786
tags question: http://stackoverflow.com/q/46881413
tags question: http://stackoverflow.com/q/46824239
tags question: http://stackoverflow.com/q/46796227
tags question: http://stackoverflow.com/q/46850610
tags question: http://stackoverflow.com/q/46888891
tags question: http://stackoverflow.com/q/46815533
type: Tag
tags question: http://stackoverflow.com/q/46751063
tag name: cython
tags question: http://stackoverflow.com/q/46784964
tags question: http://stackoverflow.com/q/46887896
tags question: http://stackoverflow.com/q/46896925
tags question: http://stackoverflow.com/q/46838415
tags question: http://stackoverflow.com/q/46860193
tags question: http://stackoverflow.com/q/46848095

http://stackoverflow.com/a/46781734
has body: And... a pool of answers is never complete unless there is also a regex solution: def is_unique(string): import re patt = re.compile(r"^.*?(.).*?(\1).*$") return not re.search(patt, string) (I'll leave the whitespace handling as an exercise to the OP)
type: Answer
answers question: http://stackoverflow.com/q/46760847
score: 0

function-parameter
type: Tag
tag name: function-parameter
tags question: http://stackoverflow.com/q/46808362

http://stackoverflow.com/q/46803626
has comment: http://stackoverflow.com/comment/80560180
has body: I have been trying to stipple contour plots to show locations where values are statistically significant. However, when I do this in subplots where the significance is the same, the stippling looks different based on the random location of the filled stipples. I have reproduced the problem below. Is there a way to fix the location of the stipples so that they look the same when plotted? Or is there a better way to stipple plots? These 2 subplots are plotting the exact same data, but the stipples look different. import numpy as np from matplotlib import pyplot as plt #Create some random data x = np.arange(0,100,1) x,y = np.meshgrid(x,x) stipp = 10*np.random.rand(len(x),len(x)) fig =plt.figure(figsize=(12,8)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) #Plot stippling ax1.contourf(x,y,stipp,[0,4],colors='none',hatches='.') ax2.contourf(x,y,stipp,[0,4],colors='none',hatches='.') plt.show()
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80577007
favorite count: 0
has title: Fix location of stippling for subplots
tagged with: python
has answer: http://stackoverflow.com/a/49766072
accepted answer: http://stackoverflow.com/a/49766072
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/80577242
type: Question
tagged with: contourf
has comment: http://stackoverflow.com/comment/80576245

http://stackoverflow.com/q/46832025
downvote count: 0
has answer: http://stackoverflow.com/a/59442257
answer count: 3
tagged with: query-string
favorite count: 0
type: UnansweredQuestion
has title: How to use query string in Falcon python
tagged with: python
has answer: http://stackoverflow.com/a/46950485
has answer: http://stackoverflow.com/a/46839846
linked to: http://stackoverflow.com/q/8130692
has body: Ho do you configure the app to have following features: Have an api-endpoint defined as app.add_route('/v1/tablets', TabletsCollection()) And still be able to use QueryParams like this https://example.com/api/v1/tablets?limit=12&amp;offset=50&amp;q=tablet name the Collection has two methods on_get for retrieving the whole list and using the filter and on_post for the creation of a single record. I've been searching the net for some time, how do you get query_string and properly parsed params?
type: Question
score: 9
upvote count: 9
tagged with: falconframework

http://stackoverflow.com/q/46792118
has title: Display an unknown number of fields in Django template with field content of another record as the label
tagged with: django-templates
downvote count: 0
has body: I have a Django app which I want to be able to use in multiple instances. One model (Listing) can have a variable number of fields (for the different instances) but will then always have exactly those extra fields for the instance. I want these extra fields added through admin so I've created models like this: class BespokeField (models.Model): name = models.CharField( max_length = 20, verbose_name = "Field Title" ) def __unicode__(self): return self.name class Listing (models.Model): name = models.CharField ( verbose_name = 'Listing', max_length = 30 ) slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True, blank=True, null=True ) class ListingBespokeField (models.Model): bespoke_field = models.ForeignKey(BespokeField) listing = models.ForeignKey(Listing) value = models.CharField ( max_length = 60 ) def __unicode__(self): return u'%s | %s' % (self.listing.name, self.bespoke_field.name) The theory is admin specifies the bespoke fields and these are then displayed to the user in forms. Within admin this is relatively simple as I can assume a modicum on intelligence from the users so my admin.py looks like: class ListingBespokeFieldInline(admin.TabularInline): model = ListingBespokeField extra = len(BespokeField.objects.all()) max_num = len(BespokeField.objects.all()) class ListingAdmin(admin.ModelAdmin): inlines = [ListingBespokeFieldInline] It does mean the admin user has to select one of each BespokeField from the dropdown but I'm not uncomfortable with that because by using unique_together ensure there is only one of each. What I cannot work out how to do is present this to the non-admin user in a friendly way. What I want is the BespokeField.name to display on the form as a label for ListingBespokeField.value. This is what I have in forms.py (for ListingBespokeField). class ListingBespokeFieldInline(forms.ModelForm): class Meta: model = ListingBespokeField exclude =['id'] widgets = { 'bespoke_field' : forms.HiddenInput(), 'value' : for…
has answer: http://stackoverflow.com/a/46884120
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 7
tagged with: django-forms
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/80677083
has comment: http://stackoverflow.com/comment/80639923
has comment: http://stackoverflow.com/comment/80624504
accepted answer: http://stackoverflow.com/a/46884120
upvote count: 7
favorite count: 0

http://stackoverflow.com/q/46760166
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80481345
has comment: http://stackoverflow.com/comment/80473983
tagged with: amazon-web-services
has body: I'm trying to test my aws lambda function but when i run it the function fails with the error Unable to import module 'property_endpoint': cannot import name 'MProperty' My folder structure is Property/ custom_exceptions/ __init__.py custom_exceptions.py property_package/ __init__.py mproperty.py property_manager.py pymysql/ PyMySQL-0.7.11.dist-info/ property_endpoint.py and when i create my deployment package i just zip the contents of Property/ The lambda handler is in property_endpoint.py. At the top of property_endpoint.py I try to import my packages like this import logging from typing import Optional from custom_exceptions.custom_exceptions import * from property_package.mproperty import MProperty from property_package.property_manager import PropertyManager The file the error is about (MProperty) looks like this import json from property_package.property_manager import PropertyManager class MProperty: .... It doesn't complain about the 3 above it which i seem to be importing in the same way I'm new to python so not sure if I'm going about this in completely the wrong way. I've found similar posts here but nothing has seemed to solve my problem. Thanks
has comment: http://stackoverflow.com/comment/80586195
downvote count: 0
tagged with: aws-lambda
has title: importing python packages for aws lambda
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/q/46773416
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46774201
score: 0
has title: Rendering different templates to the same URL pattern in Django
tagged with: django
possible better answer: http://stackoverflow.com/a/46774201
type: Question
accepted answer: http://stackoverflow.com/a/46788515
has comment: http://stackoverflow.com/comment/80492599
has body: My question is similar to Same URL in multiple views in Django, but I am not rendering templates on the basis of user_authentication, but rather on the basis of JavaScript enabled or disabled in the browser. What I am trying to do? I am trying to render the index.html page if JavaScript is enabled in the browser, otherwise I want to render jsDisabled.html page if it's disabled and both of the pages should be rendered on the same URL pattern, for example: localhost:8000 should either render index.html if JavaScript is enabled in the browser or it should render jsDisabled.html page if JavaScript is disabled. Note: I am checking if JavaScript is disabled in the browser by using the tag which will run when JavaScript is disabled. Here is my code so far: base.html: {% load staticfiles %} ... abc ... /* This should render jsDisabled.html page on the same URL which is 'localhost:8000' */ urls.py: from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ ... url(r'^(?P<flag>[0-1])$', views.index, name='index'), ] views.py: from django.shortcuts import render def index(request, flag): if (flag): return render(request, 'jsDisabled.html') else: return render(request, 'index.html')
answer count: 2
linked to: http://stackoverflow.com/q/24289095
has answer: http://stackoverflow.com/a/46788515
has comment: http://stackoverflow.com/comment/80492670

http://stackoverflow.com/q/46758649
score: -1
has comment: http://stackoverflow.com/comment/80462688
has comment: http://stackoverflow.com/comment/80463303
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/46761527
favorite count: 0
has comment: http://stackoverflow.com/comment/80465305
tagged with: python
has comment: http://stackoverflow.com/comment/80463397
has answer: http://stackoverflow.com/a/46760547
tagged with: selenium
has title: cannot target dynamic id with selenium python
downvote count: 1
has body: I am working on a script that logins a website and does some button clicks. Although its not that hard, I have done this for other websites but this website seem to have dynamic id's which is making it hard for me to locate the fields. When ever I refresh the page, the id changes but it does have some text that does not change. I searched stackoverflow and found some code that I tried but didnt work. The code does nothing and the browser just closes. I have tried chrome and firefox both do the same thing. I am really new to python selenium plz help. this is the page https://www.quora.com/ driver.find_element_by_name("email") driver.find_elements_by_xpath('//*[contains(@id, "email")]').send_keys('ssss') &lt;input class="text header_login_text_box ignore_interaction" name="email" tabindex="1" data-group="js-editable" placeholder="Email" w2cid="IDHg1fF" id="__w2_IDHg1fF_email" type="text"&gt; &lt;input class="text header_login_text_box ignore_interaction" name="password" tabindex="2" data-group="js-editable" placeholder="Password" w2cid="IDHg1fF" id="__w2_IDHg1fF_password" type="password"&gt; how can i target these two fields ? as they do have a text that is at the end of the id. but the number keeps changing.
type: Question
has answer: http://stackoverflow.com/a/46761527
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46760547
has comment: http://stackoverflow.com/comment/80462908

http://stackoverflow.com/comment/80587695
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46819746
score: 0
has text: I see that now, but I am not using wsgi.STATUS_CODE_TEXT anywhere in my code(on purpose)... where can I look for references to it?

http://stackoverflow.com/comment/112668116
comment on: http://stackoverflow.com/a/46880090
has text: @rinkert Thank you for replying. Although I'm not sure whether this can be achieved soon, I would like to propose to add the detail document about how to use `fields` for Google APIs.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/46881360
has comment: http://stackoverflow.com/comment/80710464
type: Question
has title: How to handle mixed type data in pandas data frame?
tagged with: numpy
has comment: http://stackoverflow.com/comment/80710268
has comment: http://stackoverflow.com/comment/80710368
has body: I have a data frame that looks like this 1 0 0 0 0 2 0 0 0 0 0 ... 0 0 1 2 0 0 0 0 0 0 2 0 0 0 3 0 0 0 4 0 0 ... 0 5 0 0 3 0 0 [1, 3] 0 0 3 0 0 0 0 0 0 0 2 0 0 ... 6 6 0 [2, 4] 0 2 0 0 0 0 4 1 0 6 1 0 0 0 0 0 0 ... 0 0 0 0 4 0 0 5 0 0 5 0 0 0 0 6 0 0 [2, 7] 0 0 ... 0 0 0 0 0 0 0 0 0 0 There are multi dimensional point like this [1, 3] when I try to do any process on the data Like PCA I get the following error ValueError: could not convert string to float: '[1, 3]' I tried using Labelencoder but I get this error also ValueError: bad input shape (5, 143) How do I handle this? given that I want my model to be able to read the data in the list
tagged with: pandas
has comment: http://stackoverflow.com/comment/80713891
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/80711685
has comment: http://stackoverflow.com/comment/80738638
has comment: http://stackoverflow.com/comment/80710331
tagged with: python
has comment: http://stackoverflow.com/comment/80710499
has comment: http://stackoverflow.com/comment/80711767
answer count: 0
has comment: http://stackoverflow.com/comment/80712561
type: UnansweredQuestion
score: 0
tagged with: scipy

http://stackoverflow.com/comment/80614201
type: Comment
has text: A1[i][0] wont work as your 2D array looks like A1["wap"][i] according to the code you submitted . so the **row index** is a string here 'wap' . post your array A as well , then I would be able to help you more .
comment on: http://stackoverflow.com/a/46832297
score: 0
type: AnswerComment

http://stackoverflow.com/a/46892783
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80733310
upvote count: 1
answers question: http://stackoverflow.com/q/46892015
type: Answer
has body: Problem: When you declared your tfkids variable you specify it's shape to [POP_SIZE, DNA_SIZE] which is (10, 1). But when you feeding real data into the placeholder during training you are passing a (10,) shaped data. Solution: So you have to reshape your training data to (10, 1) in order to feed it to the variable. There are a couple of ways you can reshape your data. You can use reshape function of numpy library. Do the following before feeding you training data. kids = np.reshape(kids, [-1, 1]) Hope this helps!

http://stackoverflow.com/comment/80693700
comment on: http://stackoverflow.com/q/46873195
type: QuestionComment
has text: thanks for your reply yes i have removed the value for both DateTimeField and added default values but stiill its asking me for slug and author as well please can you figure it out what exactly the default values should be
score: 0
type: Comment

http://stackoverflow.com/comment/80458010
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46756302
score: 0
has text: writer = pd.ExcelWriter('C:/Users/{}/Desktop/RF Data.xlsx'.format(staName2))

http://stackoverflow.com/q/46753447
answer count: 1
has title: NaN values when resampling pandas dataframe
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80452729
has comment: http://stackoverflow.com/comment/80452796
tagged with: resampling
tagged with: python
accepted answer: http://stackoverflow.com/a/46753543
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46753543
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80452804
has comment: http://stackoverflow.com/comment/80452563
has comment: http://stackoverflow.com/comment/80452658
has comment: http://stackoverflow.com/comment/80452558
has body: I have a pandas dataframe with two different columns: a date time index column; a column containing a dict If I run a custom resampler that returns a new dict as result, I get a NaN value in the resampled data frame. Is it not possibile to run a resample that not returns a number? Thanks, FB EDIT1: This is a data sample: 2017-10-15 06:55:14.237039000,"{'SMA120C': {'status': 9, 'program': 5, 'velocity': 2188, 'totalProduction': 1488, 'dailyProduction': 4051, 'onlineHours': 4672, 'workingHours': 2399, 'errorInfo': 'Error No :687.808'}, 'SMA115_L': {'status': 9, 'program': 5, 'velocity': 2188, 'totalProduction': 1488, 'dailyProduction': 4051, 'onlineHours': 4672, 'workingHours': 2399, 'errorInfo': 'Error No :687.808'}, 'SMA121_CT': {'status': 9, 'program': 5, 'velocity': 2188, 'totalProduction': 1488, 'dailyProduction': 4051, 'onlineHours': 4672, 'workingHours': 2399, 'errorInfo': 'Error No :687.808'}, 'SMA110_4L': {'status': 9, 'program': 5, 'velocity': 2188, 'totalProduction': 1488, 'dailyProduction': 4051, 'onlineHours': 4672, 'workingHours': 2399, 'errorInfo': 'Error No :687.808'}, 'SMA111': {'status': 9, 'program': 5, 'velocity': 2188, 'totalProduction': 1488, 'dailyProduction': 4051, 'onlineHours': 4672, 'workingHours': 2399, 'errorInfo': 'Error No :687.808'}}" 2017-10-15 06:55:18.584042000,"{'SMA120C': {'status': 7, 'program': 2, 'velocity': 6004, 'totalProduction': 6661, 'dailyProduction': 3353, 'onlineHours': 10, 'workingHours': 6845, 'errorInfo': 'Error No :468.4648'}, 'SMA115_L': {'status': 7, 'program': 2, 'velocity': 6004, 'totalProduction': 6661, 'dailyProduction': 3353, 'onlineHours': 10, 'workingHours': 6845, 'errorInfo': 'Error No :468.4648'}, 'SMA121_CT': {'status': 7, 'program': 2, 'velocity': 6004, 'totalProduction': 6661, 'dailyProduction': 3353, 'onlineHours': 10, 'workingHours': 6845, 'errorInfo': 'Error No :468.4648'}, 'SMA110_4L': {'status': 7, 'program': 2, 'velocity': 6004, 'totalProduction': 6661, 'dailyProduction': 3353, 'onlineHours': 10, …
tagged with: pandas
has comment: http://stackoverflow.com/comment/80452598

http://stackoverflow.com/q/46835902
has comment: http://stackoverflow.com/comment/80619467
has comment: http://stackoverflow.com/comment/80620402
accepted answer: http://stackoverflow.com/a/46836262
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46836262
favorite count: 0
has comment: http://stackoverflow.com/comment/80619410
has title: Python: Bizarre issue with imported function within While Loop
has body: So I have a bit of a conundrum. Let's start with the relevant fragment of my code. from RECORD import recordSystem recTime = 30 #Amount of time(seconds) I want to record the audio input while True: #I want to keep this active while system is running #Standard raspberry Pi input sensors. if(GPIO.input(LedPin4) == GPIO.LOW and GPIO.input(LedPin5) == GPIO.HIGH: recordSystem(recTime) #when condition is met run the code. So the function I am trying to run comes from another script I wrote. And it works. It records analog audio and creates a .wav file in my project folder. The problem with this code is that it was working perfectly find yesterday and now is not. Nothing has been changed or touched. It just does not want to work. What happens is that the loop starts, and when the condition is met the function is launched properly and I get my "recording" notice in the compiler. Yet it NEVER stops recording. When I just do the following outside of the loop: recordSystem(recTime) The function runs through properly without any problems. So it has to do something with calling the function inside the loop. Yet, it was working without any problems for a while. Could anyone give me a best guest on what might be going on? Much appreciated!
type: AnsweredQuestion
score: 2
tagged with: audio
downvote count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/80659382
type: Comment
has text: @en_Knight. One more time! you need the [proofreader](https://stackoverflow.com/help/badges/1276/proofreader) badge
comment on: http://stackoverflow.com/a/46855838
type: AnswerComment
score: 0

python-multiprocessing
tags question: http://stackoverflow.com/q/46782908
tags question: http://stackoverflow.com/q/46778491
tags question: http://stackoverflow.com/q/46773366
tags question: http://stackoverflow.com/q/46833131
tags question: http://stackoverflow.com/q/46801439
tags question: http://stackoverflow.com/q/46837823
tags question: http://stackoverflow.com/q/46755640
tags question: http://stackoverflow.com/q/46841147
type: Tag
tags question: http://stackoverflow.com/q/46759238
tags question: http://stackoverflow.com/q/46813375
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/46899206
tags question: http://stackoverflow.com/q/46797770
tags question: http://stackoverflow.com/q/46849574
tags question: http://stackoverflow.com/q/46899862
tags question: http://stackoverflow.com/q/46801284
tags question: http://stackoverflow.com/q/46842923

http://stackoverflow.com/comment/80618914
comment on: http://stackoverflow.com/q/46833936
score: 1
has text: @martineau and RolandSmith: thanks for your questions. I added some clarifications to the original question.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46880437
downvote count: 0
has comment: http://stackoverflow.com/comment/92689380
has body: Apparently, the error happened because ARCHITECTURE was not set. You probably missed the step "Configure your MobileNet" in the doc. Please run the following command: IMAGE_SIZE=224 ARCHITECTURE="mobilenet_0.50_${IMAGE_SIZE}" before python -m scripts.retrain ....
has comment: http://stackoverflow.com/comment/93507650
upvote count: 14
answers question: http://stackoverflow.com/q/46875546
type: Answer
has comment: http://stackoverflow.com/comment/81996756
has comment: http://stackoverflow.com/comment/80717516
score: 14

http://stackoverflow.com/comment/80750700
comment on: http://stackoverflow.com/q/46901975
type: Comment
type: QuestionComment
has text: data is not a dictionary,its a list that's why doesnt have items method
score: 4

http://stackoverflow.com/comment/80447217
comment on: http://stackoverflow.com/q/46750554
score: 0
has text: Do you know what the type of `images['src']` is then? Looks like it's not even a string. So when you go to concatenate it with other strings, Python is trying to convert it into "ascii" and failing. If images['src'] is a byte array, then you need to use `decode('utf-8')`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46864779
accepted answer of: http://stackoverflow.com/q/46864740
has comment: http://stackoverflow.com/comment/80677440
answers question: http://stackoverflow.com/q/46864740
upvote count: 10
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/96174277
score: 10
type: AcceptedAnswer
has body: IIUC, use loc, retrieve those columns, and pass that to dropna. c = df.loc[0, 'b':'d'].columns # retrieve only the 0th row for efficiency df = df.dropna(subset=c, how='all') print(df) a b c d 0 1 2.0 3.0 3.0 1 10 20.0 2.0 NaN 2 10 2.0 5.0 NaN 3 1 3.0 NaN NaN

http://stackoverflow.com/comment/80707739
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46879936
has text: Any other Ideas please or another way I could use

http://stackoverflow.com/comment/80656172
type: AnswerComment
has text: do you know if this would be possible just by using the find and slicing functions with strings?
type: Comment
comment on: http://stackoverflow.com/a/46853913
score: 0

http://stackoverflow.com/q/46892392
tagged with: distinct
has title: Multi SELECT COUNT(distinct) in Pandas
tagged with: count
tagged with: python
type: AnsweredQuestion
tagged with: group-by
has body: In SQL: SELECT distinct user_id , COUNT(product_id) AS c_products , COUNT(distinct product_id) AS c_distinct_product FROM tables GROUP BY user_id How can I do that in pandas?
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/46892576
accepted answer: http://stackoverflow.com/a/46892576
score: 0
tagged with: pandas-groupby

http://stackoverflow.com/q/46778983
has comment: http://stackoverflow.com/comment/80504826
has comment: http://stackoverflow.com/comment/80504491
type: Question
has comment: http://stackoverflow.com/comment/80504044
tagged with: python
has comment: http://stackoverflow.com/comment/80504541
has comment: http://stackoverflow.com/comment/80503861
has comment: http://stackoverflow.com/comment/80504801
score: 0
has comment: http://stackoverflow.com/comment/80503973
has title: Python getter gives AttributeError object has no attribute
tagged with: oop
tagged with: encapsulation
type: UnansweredQuestion
tagged with: python-3.6
has body: I have to use the setter part of Python and I thought I understood but I guess I don't. I have tried to change the parameters of the object, I have been wrestling with the declarations in the initialization and stuff, but I just don't seem to be getting it. Python gives me the error Traceback (most recent call last): File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 71, in &lt;module&gt; frits.position['x'] += random.randint(-15,15) #make object File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 45, in position return self._position AttributeError: 'lifeform' object has no attribute '_position' Code: class lifeform(object): kind = "lifeform" def __init__(self, max_age = (100), speed = (50), sati = (80), max_sati = (100), position = {'x': random.randint(0,WIDE), 'y': random.randint(0,HIGH)}): self.age = 0 self.max_age = max_age self.speed = speed self.strength = 100 - speed self.sati = sati self.max_hunger = max_sati self.size = 10 self.color = [155,155,255] self.position = position @property def position(self): return self._position @position.setter def position(self, pos): if pos['x'] &gt; WIDE: self._position['x'] = WIDE - 20 elif pos['x'] &lt;0: self._position['x'] = 20 if pos['y'] &gt; HIGH: self._position['y'] = HIGH - 20 elif pos['y'] &lt;0: self._position['y'] = 20
linked to: http://stackoverflow.com/q/1132941
answer count: 0

http://stackoverflow.com/comment/80696927
score: 2
comment on: http://stackoverflow.com/q/46875023
has text: What have you already tried?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80575004
score: 1
type: Comment
type: QuestionComment
has text: Don't use a mutables (`[]` and `{}` in your case) as default arguments. It will have a weird side effect if you change them.
comment on: http://stackoverflow.com/q/46813910

http://stackoverflow.com/comment/80617654
type: QuestionComment
has text: How do you check if you are connected or not? This action should be performed on a cyclic basis (e.g. create a tkinter based object that is checking the connection each "X" seconds) and based on that you can then set the Label text
comment on: http://stackoverflow.com/q/46806464
score: 0
type: Comment

networkx
tags question: http://stackoverflow.com/q/46814734
tags question: http://stackoverflow.com/q/46771781
tag name: networkx
tags question: http://stackoverflow.com/q/46813318
tags question: http://stackoverflow.com/q/46794890
tags question: http://stackoverflow.com/q/46759906
type: Tag
tags question: http://stackoverflow.com/q/46816874
tags question: http://stackoverflow.com/q/46790520

http://stackoverflow.com/q/46768344
linked to: http://stackoverflow.com/q/46552587
has answer: http://stackoverflow.com/a/46770160
type: Question
has body: I managed to develop an answer to a previous problem i had (found here: How can i create a ruleset to assign values to specific columns, based on searching substrings, in Pandas?). However i am wondering if there is a more efficient way to do this. I wanted to create multiple classification columns based on strings i search for in a description column. Currently my strategy is below: android_phones = ['samsung','xperia','google'] iphone= ['iphone','apple'] def OS_rules(raw_Df): val='' if any(word in raw_Df['Names'].lower() for word in android_phones): val='android' elif any(word in raw_Df['Names'].lower() for word in iphone): val='iPhone' else: val = 'Handset' return val df.loc[:,'OS_Type']=df.apply(OS_rules,axis=1) However with this strategy, I will need to create multiple functions with 'almost' identical rules, but with different returned values. Is there a way to return multiple values from a single function? And apply those across multiple new columns? e.g. if any(word in raw_Df['Names'].lower() for word in android_phones): val1='android' val2='pixel' val3='vodafone' etc etc etc, then create new columns from those?
answer count: 1
downvote count: 0
favorite count: 0
has title: creating multiple category columns from multiple values returned from a function
tagged with: pandas
tagged with: python
upvote count: 2
type: UnansweredQuestion
score: 2
tagged with: if-statement

http://stackoverflow.com/comment/80445501
has text: try to print args.dt just after having parsed it. it works. argparser defines dynamic members from the name of your option.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46749704
score: 1

http://stackoverflow.com/q/46762796
has answer: http://stackoverflow.com/a/46764523
linked to: http://stackoverflow.com/q/23317458
tagged with: token
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80497228
linked to: http://stackoverflow.com/q/19130512
type: UnansweredQuestion
tagged with: python
has title: Python - regex tokenizer with conditions
has answer: http://stackoverflow.com/a/46762951
has comment: http://stackoverflow.com/comment/80472376
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46763970
has body: I'm trying to remove punctuation while tokenizing a sentence in python but I have several "condtitions" where I want it to ignore tokenizing using punctuation. Some examples are when I see a URL, or email address or certain symbols without spaces next to them. Example: from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer("[\w']+") tokenizer.tokenize("please help me ignore punctuation like . or , but at the same time don't ignore if it looks like a url i.e. google.com or google.co.uk. Sometimes I also want conditions where I see an equals sign between words such as myname=shecode") Right now the output looks like ['please', 'help', 'me', 'ignore', 'punctuation', 'like', 'or', 'but', 'at', 'the', 'same', 'time', "don't", 'ignore', 'if', 'it', 'looks', 'like', 'a', 'url', 'i', 'e', 'google', 'com', 'or', 'google', 'co', 'uk', 'Sometimes', 'I', 'also', 'want', 'conditions', 'where', 'I', 'see', 'an', 'equals', 'sign', 'between', 'words', 'such', 'as', 'myname', 'shecode'] But what I really want it to look like is ['please', 'help', 'me', 'ignore', 'punctuation', 'like', 'or', 'but', 'at', 'the', 'same', 'time', "don't", 'ignore', 'if', 'it', 'looks', 'like', 'a', 'url', 'i', 'e', 'google.com', 'or', 'google.co.uk', 'Sometimes', 'I', 'also', 'want', 'conditions', 'where', 'I', 'see', 'an', 'equals', 'sign', 'between', 'words', 'such', 'as', 'myname=shecode']
linked to: http://stackoverflow.com/q/15057945
type: Question
tagged with: nltk

http://stackoverflow.com/a/46906111
score: 1
upvote count: 1
type: Answer
downvote count: 0
has body: If you're using Divio Cloud for your django CMS project, the Google Analytics addon can be a good way to add Google Analytics to a site (useful if you are for example a web manager who doesn't have access to site code). If you're not, just copy and paste the JS snippet provided by Google into your template. In fact you can do that even if you're on Divio Cloud.
answers question: http://stackoverflow.com/q/46842774

http://stackoverflow.com/q/46886770
has title: Tensorflow share weights across input placeholder
type: UnansweredQuestion
tagged with: python
has body: I am trying to build a neural network with shared input weights. Given pk inputs in the form X=[x_1, ..., x_p, v_1,...,v_p,z1,...,z_p,...] and a weight matrix w of shape (p, layer1_size), I want the the first layer to be defined as sum(w, x_.) + sum(w, v_.) + .... In other words the input and the first layer should be fully connected where weights are shared across the different groups of inputs. l = tf.matmul(X, W) where each row of W must have a structure like: (w1, ... ,wp, w1, ..., wp, ...) How can I do that in tensorflow?
has answer: http://stackoverflow.com/a/46887660
tagged with: tensorflow
type: Question
tagged with: neural-network
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46887600

http://stackoverflow.com/comment/80747226
has text: Did you add `webapp` to your `INSTALLED_APPS`?
comment on: http://stackoverflow.com/q/46899816
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/57786469
type: Answer
has body: You might like the following 'Project name' in [p.project_name for p in projects]
answers question: http://stackoverflow.com/q/46850938
score: 0

http://stackoverflow.com/q/46776596
tagged with: docker-compose
has body: On a Raspberry Pi 2, I used the image resin/rpi-raspbian:stretch for running a Django application. In my Dockerfile, I Install the python3 package and start the application using ENTRYPOINT python3 manage.py runserver 0:8000. This works, BUT when my code throws error, I got NO output using docker log command. Example I have a ImportError. When I run the command manually using docker exec, I got the exception as expected: pi@pi2:/etc/docker/container/pms $ sudo docker exec -it pms_app_1 python3 manage.py runserver 0:8000 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x75de3228> [...] ImportError: No module named 'ws4redisfrontend' But when I run the container using docker-compose and then open the logs, they're empty: pi@pi2:/myapp $ sudo docker logs myapp_1 pi@pi2:/myapp $ This behaviour is only present for the manage.py call. For example, when I extend the entrypoint like this: ENTRYPOINT python3 -c "print('printed by python inline script')" && python3 manage.py runserver 0:8000 I see printed by python inline script in the container-logs. As a newbie in Python/Django, I can't understand why this happens. But as my print example works, it seems a Django issue, and no general problem of Python. What am I missing? Debug mode is activated in settings.py.
linked to: http://stackoverflow.com/q/28072259
type: Question
answer count: 2
downvote count: 0
tagged with: docker
has answer: http://stackoverflow.com/a/55898089
has answer: http://stackoverflow.com/a/46778885
has title: manage.py doesn't log to stdout/stderr in Docker on Raspberry Pi
tagged with: python
upvote count: 11
favorite count: 0
type: UnansweredQuestion
tagged with: django
score: 11
linked to: http://stackoverflow.com/q/5438642

http://stackoverflow.com/comment/80682108
has text: But I don't have any modification, that it is my problem.
comment on: http://stackoverflow.com/a/46867312
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46768655
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46768694
favorite count: 0
has body: I have looked through various SO questions solving the problem of counting duplicate rows on specific columns, most relevant is this one. The thing is, that this solution is very specific and I can't figure out how to generalize it to dataframes with many more data. I have a dataframe that has many columns, and I want to add a new column named 'A_D_E_count' that will indicate how many rows in the entire dataframe have the same value of A, D and E columns of each row. Preferably this should work using .transform function Example: Out[6]: A B C D E 0 294 41981 37597 39875 33364 1 294 39776 37597 37572 39171 2 294 44658 49408 43713 49408 3 294 58615 52065 43713 49408 4 294 44811 51238 42926 49408 Over this dataframe, I would like to add a column that will count number of rows containing the same A D and E values so the result would be Out[6]: A B C D E A_D_E_count 0 294 41981 37597 39875 33364 1 1 294 39776 37597 37572 39171 1 2 294 44658 49408 43713 49408 2 3 294 58615 52065 43713 49408 2 4 294 44811 51238 42926 49408 1
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/46768694
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35268817
upvote count: 5
has title: Using transform to add a count of duplicate rows on certain columns - Pandas
type: Question
score: 5

http://stackoverflow.com/comment/80753575
has text: You should show the expected result, because `wr.writerow` with 3 parameters just gives a syntax error, and if you make it a tuple, you will get exactly 3 columns.
score: 1
comment on: http://stackoverflow.com/q/46902801
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80630460
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/46841300
has text: Please give an example of your Input. Also, rstrip() before splitting.

http://stackoverflow.com/comment/80592762
score: 1
comment on: http://stackoverflow.com/a/46809410
type: AnswerComment
type: Comment
has text: If you look into the comments carefully, you can see why it is not working. Instead of post.comment_set.all use post.comments.all

http://stackoverflow.com/comment/80718043
type: Comment
comment on: http://stackoverflow.com/q/46885052
type: QuestionComment
score: 1
has text: Then my suggestion is to avoid having 200 Bokeh graphs in one single page.

http://stackoverflow.com/comment/80614869
has text: I think I'm seeing now that my problem is likely because I borrowed most of this script from a person/blog post that used Python 2, and I'm using Python 3. According to some comments on that blog post, apparently the code works in Python 2.7, but not Python 3.6.
score: 0
comment on: http://stackoverflow.com/q/46832760
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46889189
has body: In Python, I have estimated the parameters for the density of a model of my distribution and I would like to plot the density function above the histogram of the distribution. In R it is similar to using the option prop=TRUE. import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt # initialization of the list "data" # estimation of the parameter, in my case, mean and variance of a normal distribution plt.hist(data, bins="auto") # data is the list of data # here I would like to draw the density above the histogram plt.show() I guess the trickiest part is to make it fit. Edit: I have tried this according to the first answer: mean = np.mean(logdata) var = np.var(logdata) std = np.sqrt(var) # standard deviation, used by numpy as a replacement of the variance plt.hist(logdata, bins="auto", alpha=0.5, label="données empiriques") x = np.linspace(min(logdata), max(logdata), 100) plt.plot(x, mlab.normpdf(x, mean, std)) plt.xlabel("log(taille des fichiers)") plt.ylabel("nombre de fichiers") plt.legend(loc='upper right') plt.grid(True) plt.show() But it doesn't fit the graph, here is how it looks: ** Edit 2 ** Works with the option normed=True in the histogram function.
tagged with: statistics
downvote count: 1
has title: Plot a density function above a histogram
has comment: http://stackoverflow.com/comment/80725698
has comment: http://stackoverflow.com/comment/80729952
favorite count: 0
possible better answer: http://stackoverflow.com/a/47265392
tagged with: python
has comment: http://stackoverflow.com/comment/80727881
has answer: http://stackoverflow.com/a/47265392
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46890606
score: 1
tagged with: matplotlib
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/46890606

http://stackoverflow.com/a/46797030
has comment: http://stackoverflow.com/comment/80584983
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80614862
has comment: http://stackoverflow.com/comment/80571893
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46757272
has comment: http://stackoverflow.com/comment/91086787
has comment: http://stackoverflow.com/comment/91085751
has comment: http://stackoverflow.com/comment/80577526
has body: (Spyder developer here) So I started by installing pip by typing sudo easy_install pip in the command line. Please avoid this route entirely. You should never, ever install things into your system Python (especially in macOS) because you can risk to break your system entirely. That's because Python is used by the operating system to run certain things, so it's better to leave it alone. The simplest way to install Spyder in macOS is to download Anaconda and install it. Anaconda comes with all Spyder dependencies and also with the most important scientific Python libraries ready to be used. Other options are Homebrew or MacPorts, but Anaconda is really the easiest one.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46757272
has comment: http://stackoverflow.com/comment/80566706
has comment: http://stackoverflow.com/comment/80566925
type: Answer
has comment: http://stackoverflow.com/comment/80567769

http://stackoverflow.com/comment/80541708
has text: It's PostgreSQL.
type: Comment
comment on: http://stackoverflow.com/q/46797306
score: 0
type: QuestionComment

http://stackoverflow.com/a/46786916
upvote count: 1
has comment: http://stackoverflow.com/comment/80520475
has body: You can change the value before you write it to the csv: mapping = {0: "True", 1: "False", 50: "Pending"} # Map `SPLE` sple = my_dict['SPLE'] my_dict['SPLE'] = mapping.get(int(sple), sple) # Map `NME` nme = my_dict['NME'] my_dict['NME'] = mapping.get(int(nme), nme) w.writerow(my_dict)
has comment: http://stackoverflow.com/comment/80520171
has comment: http://stackoverflow.com/comment/80520610
has comment: http://stackoverflow.com/comment/80521309
has comment: http://stackoverflow.com/comment/80520773
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80520355
accepted answer of: http://stackoverflow.com/q/46784832
has comment: http://stackoverflow.com/comment/80520544
has comment: http://stackoverflow.com/comment/80520527
answers question: http://stackoverflow.com/q/46784832
type: Answer
has comment: http://stackoverflow.com/comment/80520121
score: 1

http://stackoverflow.com/q/46896240
score: 1
type: Question
tagged with: time-series
has title: group pandas time series by month across years
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I have the following working example where I calculate a normal distribution for every month of this timeseries. What I am looking for is an aggregated distribution that gives back 12 values, so for every month calculated across years. In other words, the subset for January includes the data form January 2011, 2012, 2013, 2014, from which the distribution is calculated from. from scipy.stats import norm import pandas as pd import numpy as np def some_function(data): mu, std = norm.fit(data) a = mu * 3 b = std * 5 return a, b rng = pd.date_range('1/1/2011', periods=4*365, freq='D') ts = pd.Series(np.random.randn(len(rng)), index=rng) ts.groupby(pd.TimeGrouper('M')).apply(some_function).apply(pd.Series).rename(columns={0: 'mu', 1: 'std'}) Cheers
has answer: http://stackoverflow.com/a/46896474
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/46896474
type: AnsweredQuestion

http://stackoverflow.com/q/46830231
has answer: http://stackoverflow.com/a/46830369
accepted answer: http://stackoverflow.com/a/46830369
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80607744
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/46830548
tagged with: dataframe
has body: I have a dataframe filled with several columns. I need to change the values of a column for data normalization like in the following example: User_id 751730951 751730951 0 163526844 ...and so on I need to replace every value in the column that is not 0 (string) in a into something like "is not empty". I have tried it now for hours but still cannot change every value that is not 0 into something else. Replace()-function don't work really good for that. Some good ideas? EDIT (my solution): finalResult.loc[finalResult['update_user'] == '0', 'update_user'] = 'empty' finalResult.loc[finalResult['update_user'] != 'empty', 'update_user'] = 'not empty'
possible better answer: http://stackoverflow.com/a/46830456
has answer: http://stackoverflow.com/a/46830456
upvote count: 2
has title: Change Values in pandas dataframe column
answer count: 3
favorite count: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/46900499
has comment: http://stackoverflow.com/comment/80787132
downvote count: 0
has comment: http://stackoverflow.com/comment/80791501
has comment: http://stackoverflow.com/comment/80748002
answers question: http://stackoverflow.com/q/46900475
has body: You can't; that representation is lost. If you want to output "\022" then you need to either process it yourself or you need to store "\\022" instead.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80789258
score: 1

http://stackoverflow.com/q/46762456
has answer: http://stackoverflow.com/a/76814958
possible better answer: http://stackoverflow.com/a/46762536
tagged with: string
has answer: http://stackoverflow.com/a/46762500
accepted answer: http://stackoverflow.com/a/46762500
favorite count: 0
has answer: http://stackoverflow.com/a/46762536
tagged with: python-3.x
has answer: http://stackoverflow.com/a/75316006
answer count: 9
tagged with: python
has body: I've been trying to understand for loops, and for the program I am supposed to write I have to use for loops. here are the instructions: "Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares the two strings. For each match, add one point to user_score. Upon a mismatch, end the game. Ex: The following patterns yield a user_score of 4: simonPattern: R, R, G, B, R, Y, Y, B, G, Y userPattern: R, R, G, B, B, R, Y, B, G, Y to start I am given this: user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY' print('User score:', user_score) I have passed the first "test" with this code: user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY' for simon_pattern in str(simon_pattern): for user_pattern in str(user_pattern): if str(simon_pattern) == str(user_pattern): user_score += 1 continue if str(simon_pattern) != str(user_pattern): break print('User score:', user_score) the problem is when it goes to do the second test my output is still User score: 4 instead of User score: 7 (the strings for simon_pattern and user_pattern change for the second test.) I know I need to compare each element in the string to each other one at a time and add +1, and as soon as two elements don't match my loop needs to stop. I have tried: user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY' for s in simon_pattern: for u in user_pattern: if simon_pattern [0] == user_pattern [0]: user_score += 1 if simon_pattern [0] != user_pattern [0]: break if simon_pattern [1] == user_pattern [1]: user_score += 1 if simon_pattern [1] != user_pattern [1]: break (and then I continue the above loops until I get to [9] and print the user_score, but that doesn't work, either.) I've tried comparing len(simon_pattern) to len(user_pattern) but that just throws back an error telling me that it can't perform that function because I have strings and not integers. What…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70139712
downvote count: 0
has title: Simon Says For Loop String Comparison
has answer: http://stackoverflow.com/a/69338248
type: Question
has answer: http://stackoverflow.com/a/74193625
has comment: http://stackoverflow.com/comment/80470213
score: 1
has answer: http://stackoverflow.com/a/64934022
has answer: http://stackoverflow.com/a/76518615
tagged with: for-loop
upvote count: 1

http://stackoverflow.com/a/53587255
type: Answer
upvote count: 1
has body: Standard Names This gets so subjective but when aggregates/collections deviate considerably from standard collections interfaces, what I prefer is just make the name plural. If we have a collection of Control with a very unusual interface that isn't like the standard containers at all, then I might name it Controls. That prevents that temptation/confusion to associate it with any existing interfaces in the standard library, and can somewhat fend off the zealots who might be tempted to make it conform to standard interfaces to generalize it in some way that has a lot of cost and little benefit for such a narrow and well-tested use case. Standard Names = Standard Expectations A practical realization to make is that if an interface does not conform to the canonical conventions associated with a name, it might confuse less and tempt less and call more attention for developers to check out the actual interface instead of assuming by simply naming it in a way that avoids such standard names in the first place. The main benefit I see of naming something in a fairly standard way is to communicate that it conforms to standard expectations. If it can't, then perhaps there is some argument that isn't too subjective to avoid the standard name outright since that actually detracts from the main benefit of having a standard name in the first place if it's going to be "overloaded" for cases which don't conform to the associated expectations. Actually that's the only benefit I can think of is that if I named it something like ControlList or ControlDict or ControlMap depending on the nature of the interface and underlying data structure instead of Controls, then people might be tempted to raise these types of questions about why it doesn't conform to standard interfaces with a similar name (which has a simple answer but I'd rather the question not be raised at all). The whole point of, say, the metric system naming conventions is that they conform to standard expectations. When we s…
score: 1
accepted answer of: http://stackoverflow.com/q/46849966
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46849966

http://stackoverflow.com/q/46818581
has answer: http://stackoverflow.com/a/46818635
answer count: 6
tagged with: percentage
has answer: http://stackoverflow.com/a/46818657
has comment: http://stackoverflow.com/comment/80584471
type: Question
has comment: http://stackoverflow.com/comment/80584481
tagged with: string
has answer: http://stackoverflow.com/a/46818599
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/46818611
tagged with: python
has answer: http://stackoverflow.com/a/46818600
tagged with: integer
tagged with: python-3.x
has title: Adding string to integer
has body: I need to have the percentage sign after the calculation, how can i change this code so the error: TypeError: unsupported operand type(s) for +: 'int' and 'str' is not displayed. To remove the decimal point the calculation is 'int'. global score score = 2 def test(score): percentage = int(((score)/5)*100) + ("%") print (percentage) test(score)
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46818668

http://stackoverflow.com/comment/80748265
comment on: http://stackoverflow.com/q/46900561
type: QuestionComment
type: Comment
has text: I'm sorry. Edited.
score: 0

http://stackoverflow.com/comment/109598858
score: 0
type: Comment
type: QuestionComment
has text: @ArshadAhmad did you figure it out? i have the same issue
comment on: http://stackoverflow.com/q/46898009

http://stackoverflow.com/comment/80622313
score: 0
comment on: http://stackoverflow.com/a/46835010
type: AnswerComment
type: Comment
has text: I'm still working on it, the issue is within the first line and I keep receiving KeyError "Org". Can this come from the reason that while reading in the excel I already set the index_col "Org"?

http://stackoverflow.com/q/46752321
accepted answer: http://stackoverflow.com/a/46753244
upvote count: 3
tagged with: pandas
downvote count: 1
answer count: 1
favorite count: 0
has title: Plotting Candle Stick in Python
has body: I am trying to plot a candle stick chart in python. Here is my code from pandas_datareader import data as pdr import plotly.plotly as py import plotly.graph_objs as go import fix_yahoo_finance as yf yf.pdr_override() mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31") mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close) data = [mcd_candle] py.iplot(data, filename='Candle Stick') This is the error I am getting PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'. Any idea how I can draw a Candle Stick Chart?
tagged with: candlestick-chart
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: plotly
type: Question
linked to: http://stackoverflow.com/q/35315726
has answer: http://stackoverflow.com/a/46753244

http://stackoverflow.com/q/46867014
tagged with: linux
has comment: http://stackoverflow.com/comment/80681645
answer count: 1
has comment: http://stackoverflow.com/comment/80681518
accepted answer: http://stackoverflow.com/a/46867084
tagged with: python
has comment: http://stackoverflow.com/comment/80681584
has comment: http://stackoverflow.com/comment/80681575
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80681878
has comment: http://stackoverflow.com/comment/80681556
score: 0
has comment: http://stackoverflow.com/comment/80681543
has body: I need to access the date and time in ubuntu from a program.This program may not use any commands to do this. So making a call to date is not an option. Is there a file or files which hold this information? Where can it be found ?
type: Question
has comment: http://stackoverflow.com/comment/80681910
has title: Where is the date and time stored in ubuntu
has answer: http://stackoverflow.com/a/46867084
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/80681597
has comment: http://stackoverflow.com/comment/80694564

http://stackoverflow.com/comment/80700927
has text: @RajKris you are right, I forget we can use views, haha
score: 0
comment on: http://stackoverflow.com/q/46876826
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80544616
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46795836
score: 0
has text: Are there any other clarifications that would be helpful?

http://stackoverflow.com/comment/80481589
comment on: http://stackoverflow.com/q/46768159
type: QuestionComment
type: Comment
has text: remove self from your function definition.
score: 0

http://stackoverflow.com/comment/80482752
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46768358
score: 0
has text: https://bugs.python.org/issue31798

http://stackoverflow.com/comment/80716433
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46884596
has text: hi this is python language?

http://stackoverflow.com/comment/80668259
comment on: http://stackoverflow.com/a/46860067
type: AnswerComment
has text: i noticed @James edit and '[^{}]'.format(string.printable) seems to work! i searched for \u in notepad++ and found no traces! what does this do? It works so well I'm wondering if it is deleting anything else?
score: 0
type: Comment

http://stackoverflow.com/comment/80660747
score: 0
type: Comment
type: QuestionComment
has text: Thanks. You didn't mention in what way it didn't work though--a good question contains not only what you tried, but what outcome you were hoping for and what outcome you obtained instead. But I think I can probably tell you. Your `inner()` function ends with `for datalive in datalive_generator: return datalive`. That means the function returns just the first element in `datalive_generator` and then returns. You probably meant `yield datalive` here.
comment on: http://stackoverflow.com/q/46856005

http://stackoverflow.com/comment/80458081
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46756302
score: 0
has text: Perfect, thank you Mykola. If you want to give a formal answer, I will accept your answer :)

http://stackoverflow.com/comment/80517754
type: QuestionComment
has text: error is clear you passed an out of bounds index value, also if this is `pandas` then tag the question appropriately
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46785693

http://stackoverflow.com/q/46800437
linked to: http://stackoverflow.com/q/45722069
upvote count: 2
has comment: http://stackoverflow.com/comment/80547810
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76840787
tagged with: python
tagged with: python-requests
has body: On the page, there is a drop-down menu and a button which displays a table on the page when clicked. I need to scrape data from this table. The '__VIEWSTATE' and '__EVENTVALIDATION' values are different from the page before the button is clicked and after. My problem is I can only get my hands on the values from the page before button is clicked using something like this. import requests from bs4 import BeautifulSoup with requests.Session() as html: s = html.get(url, headers = headers) soup = BeautifulSoup(s.content,"lxml") data.append(tuple(('__VIEWSTATE',inputvs))) data.append(tuple(('__EVENTVALIDATION',inputev))) I need the correct values in order to post the valid data. However, above script will only get me only the the values from before the button is clicked. Please HELP!!!!!!!!
score: 2
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/80570959
has title: How do I get '__VIEWSTATE' and '__EVENTVALIDATION' on an asp.net page using python
has comment: http://stackoverflow.com/comment/80571233
has comment: http://stackoverflow.com/comment/80552546
has comment: http://stackoverflow.com/comment/80571052
has comment: http://stackoverflow.com/comment/80547799
answer count: 1
tagged with: asp.net
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/46864233
type: Question
has comment: http://stackoverflow.com/comment/80676027
has comment: http://stackoverflow.com/comment/80676610
has title: Unable to join scattered text in a single row
has body: I've found a script in some post in SO where it has been used to scrape and organize a scattered piece of text in a single-line. However, instead of making my script a single liner I wanted to break it in few lines to make it more readable and understandable. With my new try, the output I'm having is somewhat messy. I'm almost there, though! Any help to produce the output in a single row with no redundant space in between will be appreciated. This is the html elements: html_elem=""" 11525 23 RDX HAMILTON, AB , S4K 2N9 , ROYAL STREET tahir20790@yahoo.com So You Are Here """ The type of solution I'm expecting is more like (not a single liner solution which is already there in that post): from lxml.html import fromstring tree = fromstring(html_elem) for item in tree.cssselect(".post-detail p"): if item.text: print(' '.join(item.text.split())) Output I'm having: 11525 23 RDX HAMILTON, AB , S4K 2N9 , ROYAL STREET What I would like to have: 11525 23 RDX HAMILTON, AB , S4K 2N9 , ROYAL STREET Btw, this was the one liner solution: print(' '.join([' '.join(item.text.split()) for item in tree.cssselect(".post-detail p") if item.text]))
score: 0
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/46864404
tagged with: python-3.x
type: UnansweredQuestion
tagged with: data-cleaning
tagged with: python
tagged with: web-scraping

http://stackoverflow.com/q/46899190
score: 0
has comment: http://stackoverflow.com/comment/80745716
has comment: http://stackoverflow.com/comment/80745602
has comment: http://stackoverflow.com/comment/80745597
has comment: http://stackoverflow.com/comment/80745862
has comment: http://stackoverflow.com/comment/80745916
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80745777
has comment: http://stackoverflow.com/comment/80745830
has body: I have a dict that looks as follows: Initial Class class Floors(object): def __init__(self, colour, speed, name): self.colour = colour self.speed = speed self.name = name The dict in question # Dict of info floorTypes = { CONCRETE: Floors(CONCRETE, 5.5, 'Concrete'), # FFF MARBLE: Floors(MARBLE, 3.5, 'Marble'), # FF3 ... GRANITE: Floors(GRANITE, 6.0, 'Granite'), # 777 STEEL: Floors(STEEL, 1/100000, 'Steel') # 000 } A Get method: def getFloorType(rgb): return floorTypes.get(rgb) I'm trying to be able to change the values based on a modifier that is passed in as a float. So if I pass in a modifier of 0.2, I want to make all the speeds equal to (speed+(speed*0.2)). I thought that the best way to go about doing that would be a set method, but when I try to run a foreach loop to set them, it doesn't work. Here is my loop, can you point out what I'm doing wrong? current loop: for floor in floorTypes: curSpeed = getFloorType(rgb).speed getFloorType(rgb).speed = curSpeed + (curSpeed * mult) Where mult is a float multiplier, like 0.2 or 2.4. Here's the traceback that is returned: ERROR:root:Traceback (most recent call last): File "robot.py", line 360, in &lt;module&gt; surfaceChanges(mult) File "robot", line 330, in surfaceChanges for i in floorTypes: NameError: global name 'rgb' is not defined
has title: Modify a value in a dict using a setter
answer count: 0
has comment: http://stackoverflow.com/comment/80745807
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/80745936
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80745745

http://stackoverflow.com/a/46773738
answers question: http://stackoverflow.com/q/46773626
has body: You need to grab it from the web first, try this from urllib.request import urlopen xml = urlopen('www.yourwebsite.com') tree = etree.parse(xml)
type: Answer
accepted answer of: http://stackoverflow.com/q/46773626
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/46799511
has title: Getting error while spark streaming with python?
has body: Using kafka_2.11-0.9.0.0 and zookeeper-3.4.9. I have started the zookeeper services as well as the producer and consumer. But when i run spark submit command it throws error. I am using below command to submit spark job: spark-submit --packages org.apache.spark:spark-streaming-kafka_2.11:1.5.0 /usr/local/spark/examples/src/main/python/streaming/kafka_wordcount.py localhost:2181 Hello-Kafka I am getting errors in log. And this is the log i am getting: 17/10/18 02:44:59 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 192.168.150.105, 44389) Traceback (most recent call last): File "/usr/local/spark/examples/src/main/python/streaming/kafka_wordcount.py", line 48, in &lt;module&gt; kvs = KafkaUtils.createStream(ssc, zkQuorum, "spark-streaming-consumer", {topic: 1}) File "/usr/local/spark/python/lib/pyspark.zip/pyspark/streaming/kafka.py", line 70, in createStream File "/usr/local/spark/python/lib/py4j-0.10.3-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/usr/local/spark/python/lib/py4j-0.10.3-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o27.createStream. : java.lang.NoClassDefFoundError: org/apache/spark/Logging at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:763) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.apache.spark.streaming.kafka.KafkaUtils$.createStream(KafkaUtils.scala:81) at org.apache.s…
tagged with: spark-streaming
tagged with: python
has answer: http://stackoverflow.com/a/46862695
type: AnsweredQuestion
score: 1
type: Question
tagged with: apache-kafka
duplicate of: http://stackoverflow.com/q/41383460
linked to: http://stackoverflow.com/q/41383460
tagged with: apache-spark
upvote count: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46862695
favorite count: 0

http://stackoverflow.com/comment/80465343
has text: The non round robin answer is what I am doing in my code. Takes about 5 seconds to generate an output, but it works given my parameters.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46759335

http://stackoverflow.com/a/46809557
has body: Does your single output list object have commas in it? If so, your reader could just be reading into those commas through the list. As far as the structure goes, which I think is the underlying issue here, you need 1 atomic value in each row to get the effect of the csv. So I would consider casting your list object into a big string separated by spaces, writing that out, then reading it in, splitting it, and casting the type back to what it is needed to be. Hope this helps. BC
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46808538

http://stackoverflow.com/comment/80630633
has text: So, I changed the order (btw why does strip have to be before split?). But I still dont get the \n stripped from my list
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46841300

http://stackoverflow.com/q/46851809
type: Question
has body: i dont know why this code not printing 'got it' when i run it it just shows me the prints the else statement , even if the answer is correct. import random as rand print('Welcome to the guessing game!') print('type a number between 1 to 9') running = True while running: value = rand.randint(1, 9) user_guess = input() if user_guess == value: print('got it') else: print('not at all') even ive tried with printing the value to make sure my answer is correct.
has comment: http://stackoverflow.com/comment/80651086
accepted answer: http://stackoverflow.com/a/46851858
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/80651070
has title: if statement and printing in python
tagged with: boolean
has answer: http://stackoverflow.com/a/46851858
tagged with: while-loop
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/80651291
answer count: 1
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/80651029
favorite count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/80650987
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80651104
tagged with: loops

http://stackoverflow.com/a/46897841
has body: below 2 queries return same results self.collection.find() self.collection.find().sort([("$natural", pymongo.ASCENDING)]) Sort Natural Order and also below 2 queries return same results self.collection.find() self.collection.find().limit(0) A limit of 0 is equivalent to no limit. source so you can combine these and write a single line query as follows self.collection.find().limit(self.limit or 0).sort(self.sort or [("$natural", pymongo.ASCENDING)]) If you have set values for limit/sort they will be applied otherwise will be ignored.
upvote count: 2
has comment: http://stackoverflow.com/comment/100249708
answers question: http://stackoverflow.com/q/46788207
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/80656633
has text: Selenium has a method called `find_element_by_id()`. Use that instead.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46852584

http://stackoverflow.com/comment/80675412
type: Comment
has text: Glad to help, i learn something too thanks to the author of this blog
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46863849

http://stackoverflow.com/a/46800647
answers question: http://stackoverflow.com/q/46800494
downvote count: 0
score: 1
has body: Don't redirect its output. Let the script print to stdout. Systemd will store its output in the systemd journal, which you can view with journalctl -u test or systemctl status test.
has comment: http://stackoverflow.com/comment/80629350
upvote count: 1
type: Answer

http://stackoverflow.com/q/46832955
has comment: http://stackoverflow.com/comment/80616434
has comment: http://stackoverflow.com/comment/80613565
answer count: 2
tagged with: for-loop
tagged with: arrays
downvote count: 0
has body: I need to square a single number to the power of a list (element wise) and append the result to a new list. for example: I have a list a = [1,2,3,4] and a digit b = 12 I would like to square b to the power a (element wise) and append the result to a new list I have tried doing this: result = [] yrs = [0,1,2] newr = 10 for u in range(len(yrs)): calc = (1 + newr) ** -u result.append(calc) print result but the loop to square to the power of the array doesn't work
has answer: http://stackoverflow.com/a/46833107
favorite count: 0
has comment: http://stackoverflow.com/comment/80615151
has comment: http://stackoverflow.com/comment/80613574
tagged with: python
has answer: http://stackoverflow.com/a/46833291
has comment: http://stackoverflow.com/comment/80613997
has comment: http://stackoverflow.com/comment/80615074
score: 2
has comment: http://stackoverflow.com/comment/80613453
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80614243
tagged with: loops
has title: Square a number to the power of an array element-wise using python loop
type: Question
has comment: http://stackoverflow.com/comment/80613816
has comment: http://stackoverflow.com/comment/80613958

http://stackoverflow.com/comment/80669499
type: QuestionComment
has text: Is there any way I can do `.append` to `numpy.ndarray` in the same manner as `list`?
comment on: http://stackoverflow.com/q/46860970
score: 0
type: Comment

http://stackoverflow.com/a/46853577
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46853247
score: 4
has body: Just a guess. Try: for _ in range(num_epochs): x, y = generate_data() history = model.fit(x, y, epochs=1, batch_size=64)
type: Answer
answers question: http://stackoverflow.com/q/46853247
upvote count: 4

http://stackoverflow.com/comment/80631516
has text: @CharlesDuffy Thanks! My problem was that my file had a \r at the end of each line, so I did some quick googling and found out that I have to use `.rstrip()` to remove it :)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46841185
type: Comment

http://stackoverflow.com/comment/80700652
has text: I think rather than doing this in the template, it will be better to do this in the view. Does that make sense?
comment on: http://stackoverflow.com/q/46876826
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/46789284
has comment: http://stackoverflow.com/comment/80554586
score: 3
has comment: http://stackoverflow.com/comment/80524918
has comment: http://stackoverflow.com/comment/80538496
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: google-cloud-functions
tagged with: python
has body: I am trying to call python script from Node.js. It is executing the python script but giving error in script as ImportError:no module named google.cloud my Node.js has following code : /** * * Background Cloud Function to be triggered by Cloud Storage. * * * * @param {object} event The Cloud Functions event. * * @param {function} callback The callback function. * */ exports.hellogcspy1 = function (event, callback) { var PythonShell = require('python-shell'); var options = { mode: 'text', pythonPath: '/usr/bin/python2.7', pythonOptions: ['-u'], scriptPath: '.', args: ['value1', 'value2', 'value3'] }; PythonShell.run('my_script.py', options, function (err, results) { if (err) throw err; console.log('results: %j', results); }); }; python script is named as my_script.py . when I run this script from the directory where python-shell and package.json is created, I dont get any import error. Package.json has following code : { "name": "python-shell", "version": "0.4.0", "description": "to test python run", "main": "Node.js", "scripts": { "test": "python my_script.py" }, "keywords": [ "python" ], "author": "", "license": "ISC", "dependencies": { "python-shell": "^0.4.0" }, "repository": {}, "devDependencies": {} } my_script.py contains import of google-cloud modules i.e. from google.cloud import storage,from google.cloud import bigquery from google.cloud.bigquery import SchemaField Its running fine on VM but not on Node.js. Can anyone please help why I am getting the error ImportError:no module named google.cloud when executed from Node.js ?
tagged with: node.js
has comment: http://stackoverflow.com/comment/80525498
upvote count: 3
has comment: http://stackoverflow.com/comment/80525247
has comment: http://stackoverflow.com/comment/80527927
has comment: http://stackoverflow.com/comment/80525119
has comment: http://stackoverflow.com/comment/80644281
type: Question
has title: Run Python script from Node.js--Getting ImportError:no module named google.cloud
downvote count: 0
tagged with: google-cloud-platform

http://stackoverflow.com/a/46845731
accepted answer of: http://stackoverflow.com/q/46845464
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/80639348
has comment: http://stackoverflow.com/comment/80639395
score: 6
has comment: http://stackoverflow.com/comment/80638972
has body: You could use a recursive function and some type tests: data = [{'a':1, 'b':{'c':2, 'd':3}, 'e':4}, {'f':5,'g':6}] def extract_nested_values(it): if isinstance(it, list): for sub_it in it: yield from extract_nested_values(sub_it) elif isinstance(it, dict): for value in it.values(): yield from extract_nested_values(value) else: yield it print(list(extract_nested_values(data))) # [1, 2, 3, 4, 5, 6] Note that it outputs a flat generator, not a list of lists.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80638983
answers question: http://stackoverflow.com/q/46845464
has comment: http://stackoverflow.com/comment/80639074

http://stackoverflow.com/a/46881058
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80709895
has comment: http://stackoverflow.com/comment/80709539
has body: The eval() is the problem. This will work: a = input() b = "." p = 0 contador = 0 while a != b: contador = contador + 1 p += int(a) a = input() if a == b: print(contador) print(p) You use eval() when you want to turn a string into python executable code. For example doing eval('print("hello")') would print hello.
type: Answer
has comment: http://stackoverflow.com/comment/80709853
accepted answer of: http://stackoverflow.com/q/46881005
score: 0
answers question: http://stackoverflow.com/q/46881005

http://stackoverflow.com/a/46831902
has body: You can try this. It will take list element from 0 to last-1 for i in range(0,len(A)-1): A1 = (A['wap'][i]-A['wap'][i+1]) + (A['wap'][i+1])
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46831819
has comment: http://stackoverflow.com/comment/80612952
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/80449381
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46751584
has text: How can I then prefill this email value in a form which is on the `/add-edit-user' page?
score: 0

http://stackoverflow.com/a/46872597
answers question: http://stackoverflow.com/q/46870707
score: 0
has comment: http://stackoverflow.com/comment/80704579
has comment: http://stackoverflow.com/comment/80704461
has comment: http://stackoverflow.com/comment/80704580
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46870707
has body: Sure, you can simply have an append function that adds to your list. E.g. def append(self, element): self.listOfQueues.append(element) That will work even after your thread's start() method has been called. Edit: for non thread-safe procedures you can use a lock, e.g.: def unsafe(self, element): with self.lock: # do stuff You would then also need to add the lock inside your run method, e.g.: with lock: for q in self.listOfQueues: q.put(bytestring) Any code acquiring a lock will wait for the lock to be released elsewhere.

http://stackoverflow.com/q/46777181
tagged with: prediction
type: UnansweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80514695
has answer: http://stackoverflow.com/a/69650032
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/80514224
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/80514056
favorite count: 0
tagged with: ensemble-learning
has comment: http://stackoverflow.com/comment/80515295
tagged with: python
has comment: http://stackoverflow.com/comment/80508601
upvote count: 6
has body: I am trying to do the following: vc = VotingClassifier(estimators=[('gbc',GradientBoostingClassifier()), ('rf',RandomForestClassifier()),('svc',SVC(probability=True))], voting='soft',n_jobs=-1) params = {'weights':[[1,2,3],[2,1,3],[3,2,1]]} grid_Search = GridSearchCV(param_grid = params, estimator=vc) grid_Search.fit(X_new,y) print(grid_Search.best_Score_) In this, I want to tune the parameter weights. If I use GridSearchCV, it is taking a lot of time. Since it needs to fit the model for each iteration. Which is not required, I guess. Better would be use something like prefit used in SelectModelFrom function from sklearn.model_selection. Is there any other option or I am misinterpreting something?
has title: How to tune weights in Voting Classifier (Sklearn)
has answer: http://stackoverflow.com/a/48118671

http://stackoverflow.com/a/46896729
has comment: http://stackoverflow.com/comment/80740687
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46896650
type: Answer
score: 0
has body: In your first code block, you are not passing a value to be removed from the list. In the second code block, you are altering the list while iterating, thus producing a skewed index-vs-value location. The best way is to filter out the Nones from the list: features= [ [[1,2,3],[1,2,3],[1,2,3]] ,None , [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]], None,None,[[1,2,3],[1,2,3],[1,2,3]] ] final_features = list(filter(lambda x:x is not None, features)) Output: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
answers question: http://stackoverflow.com/q/46896650

http://stackoverflow.com/a/46858059
upvote count: 1
has comment: http://stackoverflow.com/comment/80664680
has comment: http://stackoverflow.com/comment/80707269
has body: The error suggests that someplace you are using numpy.unhamming A quick and dirty use of frompyfunc would be: In [126]: def unhamming(i,j): ...: return bin(i^j).count('1') ...: In [127]: f = np.frompyfunc(unhamming, 2,1) The function takes 2 inputs, and returns 1. With smaller arrays: In [124]: A = np.arange(200) In [125]: B = np.arange(200,500) In [128]: C = [bin(i^j).count('1') for i in A for j in B].count(1) In [131]: C Out[131]: 336 Using the 'vectorized' function: In [129]: f(A,B[:,None]) Out[129]: array([[3, 4, 4, ..., 3, 3, 4], [4, 3, 5, ..., 2, 4, 3], [4, 5, 3, ..., 4, 2, 3], ..., [6, 5, 7, ..., 4, 6, 5], [6, 7, 5, ..., 6, 4, 5], [7, 6, 6, ..., 5, 5, 4]], dtype=object) And to find out how many 1's there are either turn it into a list, or use a numpy sum. In [130]: _.ravel().tolist().count(1) Out[130]: 336 In [132]: (f(A,B[:,None])==1).sum() Out[132]: 336 Speed is basically the same In [133]: timeit C = [bin(i^j).count('1') for i in A for j in B].count(1) 45 ms ± 380 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [134]: timeit (f(A,B[:,None])==1).sum() 46.1 ms ± 97.4 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) Sometimes frompyfunc gives up to a 2x speed improvement over direct iteration. But it still has to call your unhamming function many times. It is not true 'vectorization' (in the sense of moving calculations to C level code). I suspect there's a way of doing the same calculation with numpy expressions, broadcasting A against B[:,None]. But I'll leave that to another time or poster. C = A ^ B[:,None] does part of your function. But I haven't found a version of bin that works on arrays (np.binary_repr doesn't help). In [160]: f1 = np.frompyfunc(lambda x: bin(x).count('1'),1,1) In [161]: f1(A^B[:,None]) Out[161]: array([[3, 4, 4, ..., 3, 3, 4], [4, 3, 5, ..., 2, 4, 3], [4, 5, 3, ..., 4, 2, 3], ..., [6, 5, 7, ..., 4, 6, 5], [6, 7, 5, ..., 6, 4, 5], [7, 6, 6, ..., 5, 5, 4]], dtype=object) In [162]: (f1(A^B[:,None])==1).sum() Out[162]:…
accepted answer of: http://stackoverflow.com/q/46857066
has comment: http://stackoverflow.com/comment/80664481
answers question: http://stackoverflow.com/q/46857066
has comment: http://stackoverflow.com/comment/80664551
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80666503
type: Answer
has comment: http://stackoverflow.com/comment/80665184

http://stackoverflow.com/q/46899905
type: AnsweredQuestion
score: 0
tagged with: django-authentication
type: Question
has title: django-ouath-toolkit with social-auth
has answer: http://stackoverflow.com/a/47007176
has body: I'm trying to setup social-auth (python-social-auth) to talk to another Django project with django-oauth-toolkit. I want Django project A to login using OAuth2 from Django project B. Django project A uses social-auth and project B uses django-oauth-toolkit as the OAuth2 provider. Project A can successfully login to other OAuth2 providers such as Google, but I get the following error when trying to login using my custom made backend: AuthStateMissing at /sso/complete/custom-backend/ Session value state missing. This is how the custom backend has been implemented in Project A: class CustomBackend(BaseOAuth2): name = 'custom-backend' EXTRA_DATA = [ ('profile', 'org') ] def authorization_url(self): return "%s/oauth2/authorize" % self.setting("URL") def access_token_url(self): return "%s/oauth2/token" % self.setting("URL") def user_data(self, access_token, *args, **kwargs): resp = requests.get("%s/me/" % self.setting("URL"), headers={ 'Authorization': "Bearer %s" % access_token }) if resp.status_code != 200: raise Exception("Error while getting user details from auth source.") data = resp.json() return { 'username': data['email'], 'first_name': data['first_name'], 'last_name': data['last_name'], 'user_id': data['id'], 'email': data['email'] } There is a setting called SOCIAL_AUTH_CUSTOM_BACKEND_URL which is equal to the base URL of project B (http://localhost:8001 for testing). The URL when Project B redirects to Project A (when the error is raised) is: http://localhost:8000/sso/complete/custom-backend/?redirect_state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl&amp;code=e64by72AkD2unMVVsGZCz0V2byuUyu&amp;state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl Thoughts would be appreciated, thanks.
answer count: 1
accepted answer: http://stackoverflow.com/a/47007176
tagged with: oauth
tagged with: django
tagged with: python

http://stackoverflow.com/q/46899443
upvote count: 2
type: UnansweredQuestion
has title: Model_exec fails in subprocess.py
type: Question
has body: Dear Dakota and python users, I am using Windows 8.1, Sandia's Dakota GUI version 6.6 and Python 2.7.14 (as suggested by Dakota - https://dakota.sandia.gov/content/latest-gui-manual ). In the preferences I set the path to Dakota executable and path to python interpreter. The cantilever case from tutorial runs properly - as centered parameter study. The Dakota and python executables are detectable in cmd (as response I get the version of programs). I would like to run case using T-Axi external code ( http://gtsl.ase.uc.edu/T-AXI/ ). I set simulation model (path to model executable and parameters in input and output files), Dakota study (I set genetic algorithm - coliny_ea, variables as continuous design and continuous state with lower and upper bounds with model response) and analysis driver (I set simulation model and Dakota study - variables and response). When I try to run Dakota study, I get such problem: Dakota reported: Traceback (most recent call last): File "C:\Users\XXX\Documents\Dakota_projects\dakota_project2_files\drivers\script_python.py", line 367, in &lt;module&gt; model_exec = subprocess.Popen(shlex.split(model_exec_args), stdout=PIPE, stderr=PIPE) File "C:\Python27\lib\subprocess.py", line 390, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 640, in _execute_child startupinfo) WindowsError: [Error 2] Couldn’t file specified file The input file to Dakota is: interface analysis_drivers 'python -m script_python' fork parameters_file 'params.in' results_file 'results.out' file_tag file_save asynchronous evaluation_concurrency 4 responses descriptors 'efficiency' objective_functions 1 sense 'max' primary_scale_types 'none' no_gradients no_hessians method coliny_ea population_size 10 fitness_type merit_function crossover_rate 1 crossover_type two_point mutation_rate 1 seed 11011011 max_iterations 100 convergence_tolerance 0.001 max_function_evaluations 100 model_pointer 'tcdes' model id_model 'tcdes' single environment tabular_dat…
score: 2
has comment: http://stackoverflow.com/comment/113480630
downvote count: 0
has comment: http://stackoverflow.com/comment/113381175
tagged with: optimization
tagged with: python
has comment: http://stackoverflow.com/comment/113502764
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/113401241

http://stackoverflow.com/a/46862986
accepted answer of: http://stackoverflow.com/q/46862861
has body: Let's look a minimal example, where we create some axes with plt.subplots, also see this question, import matplotlib.pyplot as plt fig, axes = plt.subplots(ncols=2,nrows=3, sharex=True, sharey=True) for i, ax in enumerate(axes.flat): ax.scatter([i//2+1, i],[i,i//3]) plt.show() Here, axes is a numpy array of axes, print(type(axes)) &gt; &lt;type 'numpy.ndarray'&gt; print(axes.shape) &gt; (3L, 2L) axes.flat is not a function, it's an attribute of the numpy.ndarray: numpy.ndarray.flat ndarray.flat A 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object. Example: import numpy as np a = np.array([[2,3], [4,5], [6,7]]) for i in a.flat: print(i) which would print the numbers 2 3 4 5 6 7. Being an interator over the array, you can use it to loop over all the axes from the 3x2 array of axes, for i, ax in enumerate(axes.flat): For each iteration it would yield the next axes from that array, such that you may easily plot to all axes in a single loop. An alternative would be to use axes.flatten(), where flatten() is method of the numpy array. Instead of an iterator, it returns a flattened version of the array: for i, ax in enumerate(axes.flatten()): There is no difference seen from the outside between the two. However an iterator does not actually create a new array and may hence be slightly faster (although this will never be noticable in the case of matplotlib axes objects). flat1 = [ax for ax in axes.flat] flat2 = axes.flatten() print(flat1 == flat2) &gt; [ True True True True True True] Iterating a flattened version of the axes array has the advantage that you will save one loop, compared to the naive approach of iterating over rows and columns separately, for row in axes: for ax in row: ax.scatter(...)
type: AcceptedAnswer
score: 78
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46862861
upvote count: 78

http://stackoverflow.com/a/46794069
type: Answer
score: 2
has body: You were on the right track with your code you just needed to pass the row number you were currently printing to the P2() method and needed to print a row of numbers across the top. This should work. def P0(num): for i in range(num-1): print " " + str(i+1), print(" " + str(num)) def P1(): print(" ---" * game) def P2(i): print(str(i+1) + "| " * (game + 1)) game = int(input("Game board size: ")) P0(game) for i in range(game): P1() P2(i) P1()
has comment: http://stackoverflow.com/comment/80535198
accepted answer of: http://stackoverflow.com/q/46793821
answers question: http://stackoverflow.com/q/46793821
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80535324
upvote count: 2

http://stackoverflow.com/q/46890325
has comment: http://stackoverflow.com/comment/80752832
favorite count: 0
linked to: http://stackoverflow.com/q/46682793
has title: PyPi: How to upload documentation and how to change the package description?
linked to: http://stackoverflow.com/q/2746692
tagged with: python
has comment: http://stackoverflow.com/comment/80736046
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46894485
tagged with: python-sphinx
has body: 1. Documentation How can I add the zipped sphinx documentation to a package on PyPi? There used to be an upload documentation button, but this was replaced by a destroy documentation one. This button does exactly what it says. I destroyed my old docs -.- Still, even after wiping out my old docs, the button is still there, I cannot upload the new docs. 2. Package info Moreover, can I change the package description on PyPi? My Readme.md file contains badges that are not interpreted by pypi (see my pypet package on pypi), but that are known to github. I need to manually remove them from the package description. How can I do this? There used to be a button for this, too...
upvote count: 1
type: Question
score: 1
tagged with: pypi
has comment: http://stackoverflow.com/comment/80727827
has answer: http://stackoverflow.com/a/46894485
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/80634766
has text: Yeah even I want to know the answer for your qn @cᴏʟᴅsᴘᴇᴇᴅ.
score: 0
comment on: http://stackoverflow.com/q/46842723
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46760863
has body: Pickle writes out the data you give it in a special format, e.g. it will write some header/metadata/etc, to the file you give it. It is not intended to work this way; concatenating two pickle files doesn't really make sense. To achieve a concatenation of your data, you'd need to first read whatever is in the file into your urlsToDump, then update your urlsToDump with any new data, and then finally dump it out again (overwriting the whole file, not appending).
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46760771
type: Answer
answers question: http://stackoverflow.com/q/46760771
score: 2

http://stackoverflow.com/comment/80499400
score: 0
comment on: http://stackoverflow.com/q/46776746
type: Comment
type: QuestionComment
has text: Ah interestingly the error is now about csrf tokens!

http://stackoverflow.com/comment/80675685
type: QuestionComment
type: Comment
has text: It works for me after copy/pasting your code as written (along with the appropriate imports). Have you tried running it in a fresh Python interpreter? What version of SQLAlchemy?
comment on: http://stackoverflow.com/q/46863993
score: 1

http://stackoverflow.com/comment/80835299
comment on: http://stackoverflow.com/a/46903875
has text: @JAG Ah crud, forgot to add `self` (also there was another type). See edit, thanks.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80748999
type: AnswerComment
comment on: http://stackoverflow.com/a/46901004
has text: Double backslashes, my bad. That is needed because some characters like `\n` create different behaviour. `\t` is a tabulation and \n adds a new line. In order to avoid adding such issues, we use \\ to escape the unicode characters.
type: Comment
score: 0

http://stackoverflow.com/comment/80595503
type: QuestionComment
comment on: http://stackoverflow.com/q/46823662
has text: @cᴏʟᴅsᴘᴇᴇᴅ I fully trust you on that, but I would like to see an explanation of the rationale behind it. Do you have a link?
type: Comment
score: 0

http://stackoverflow.com/comment/80697345
comment on: http://stackoverflow.com/q/46873915
has text: your class Meta:model = User looks wrong. you dont create a model object.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46842398
has body: Im a windows 10 user and this is my version of python at the moment Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 and when i try to install tensorflow with pip this pop up tensorflow_gpu-0.12.1-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform. I ve looking on the internet which suggest that tensorflow now only work on python 3.5.2. Is it true? if not then how do i bypass that error?
type: UnansweredQuestion
tagged with: tensorflow
has answer: http://stackoverflow.com/a/46842547
type: Question
answer count: 1
score: 0
tagged with: python
has title: Is it true that tensorflow ONLY work on python3.5.2?

http://stackoverflow.com/comment/80519781
comment on: http://stackoverflow.com/q/46786505
has text: Raise this issue in the bokeh community ;)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80665369
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46858845
has text: A variable can't change its value between the `print` and `f.write` lines. I suspect you're looking at the wrong file.

http://stackoverflow.com/comment/80509023
score: 4
has text: Do you know what `this == rewrite` is doing?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46781397

http://stackoverflow.com/comment/80528421
type: QuestionComment
comment on: http://stackoverflow.com/q/46787980
score: 0
has text: Without seeing the commands you typed and the output, it's impossible to diagnose this.
type: Comment

http://stackoverflow.com/comment/80602343
comment on: http://stackoverflow.com/a/46827498
type: AnswerComment
type: Comment
has text: May be `{print $0 "\tnew"}` to align the header too?
score: 0

http://stackoverflow.com/comment/80727818
has text: ```I need to use machine learning to solve that problem``` Why? (don't!)
comment on: http://stackoverflow.com/q/46888182
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80515848
comment on: http://stackoverflow.com/q/46784648
type: Comment
type: QuestionComment
has text: Ok, and you want a single number that represents the mean over the batch size or a batch size of distances? What should the output shape be?
score: 0

http://stackoverflow.com/comment/80449208
type: QuestionComment
has text: You are replotting all the data with default cycling colours. Specify a color manually, or even better: plot once and only update the data later. Nothing to do with `ion`. For an infinite loop use `while True:`. You'll also have to stop your program somehow; that's why it keeps reopening.
comment on: http://stackoverflow.com/q/46751667
score: 0
type: Comment

http://stackoverflow.com/q/46839401
has body: I‘m trying to simplify my iteration through the second level of a dictionary. I know this works for simple lists: if new not in existing_list: dosomestuff Is there any chance to do something similar for a dictionary y where each entry looks like this? {'fields': {'ID': 123, 'name': 'test'}, 'otherfield': 'value' } What I need to do is to compare a variable (let‘s called it x) against each y['fields']['ID']. Currently I‘m just iterating through y but I thought there must be a smarter way to find a match.
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46839670
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46839759
type: Question
has comment: http://stackoverflow.com/comment/80626631
has comment: http://stackoverflow.com/comment/80626745
has answer: http://stackoverflow.com/a/46839803
answer count: 6
has title: Match a variable against second level in a dictionary
tagged with: search
has answer: http://stackoverflow.com/a/46839639
upvote count: 1
has answer: http://stackoverflow.com/a/46840423
favorite count: 0
has answer: http://stackoverflow.com/a/46839900
type: UnansweredQuestion

http://stackoverflow.com/a/46803814
has comment: http://stackoverflow.com/comment/80558237
type: Answer
has comment: http://stackoverflow.com/comment/80555031
has comment: http://stackoverflow.com/comment/80555421
has comment: http://stackoverflow.com/comment/80555364
score: 1
accepted answer of: http://stackoverflow.com/q/46802763
upvote count: 1
answers question: http://stackoverflow.com/q/46802763
has comment: http://stackoverflow.com/comment/80558379
has comment: http://stackoverflow.com/comment/80557986
has comment: http://stackoverflow.com/comment/80554676
has comment: http://stackoverflow.com/comment/80554632
has comment: http://stackoverflow.com/comment/80554662
has body: As discussion above from comments, you can put exception handling in code and put logger in the code. For example: import logging class TagView(LoginRequiredMixin, generic.CreateView): form_class = forms.TagForm def post(self, request, *args, **kwargs): try: post_data = request.POST.copy() post_data.update({'user': request.user.pk}) form = forms.TagForm(post_data) if form.is_valid(): tag = form.save(commit=False) tag.user = request.user tag.email = request.user.email tag.save() else: return HttpResponse(form.errors, status=400) return HttpResponseRedirect(reverse_lazy('users:dashboard')) except Exception as exp: logging.error(exp) # For python 3 return HttpResponse(exp, status=400) And view the error logs using log monitoring tool like this blog mentioned: https://cloud.google.com/python/monitor-and-debug/logging-application-events Details about exception handling: https://docs.python.org/3/tutorial/errors.html *** As per discussion in the comments in the answer, the problem resides in ALLOWED_HOSTS. Setting ALLOWED_HOSTS=['*'] or Setting the IP of the Server in Allowed Host solved the issue.
has comment: http://stackoverflow.com/comment/80558945
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80555050
has comment: http://stackoverflow.com/comment/80555330
has comment: http://stackoverflow.com/comment/80555066

http://stackoverflow.com/comment/80593909
type: QuestionComment
has text: Why don't you create numbers from 1 to 50 and mlutiply by 2?
score: 0
comment on: http://stackoverflow.com/q/46822789
type: Comment

http://stackoverflow.com/comment/80594462
comment on: http://stackoverflow.com/a/46823196
type: AnswerComment
has text: df['ChangeInVolume'] = df.groupby('symbol')['totalTradedVolume'].diff() failed saying ValueError
score: 0
type: Comment

http://stackoverflow.com/a/46900930
type: Answer
upvote count: 1
score: 1
has body: The function quantity builds and returns a property instance defined by the statement return property(qty_getter, qty_setter). The property itself is built enclosing two nested functions qty_getter and qty_setter. Enclosing functions can access to the parent's function arguments (in a way similar to closures). When you call self.weight (in the subtotal function) you are telling python to call the getter function (qty_getter) of the property assigned to self.weight. To the getter (or setter) function, by property contract, is provided the instance of the object that holds the property itself (LineItem in this case) that in turn can access to the storage_name variable.
downvote count: 0
answers question: http://stackoverflow.com/q/46900824

http://stackoverflow.com/a/46885294
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/46885052
type: AcceptedAnswer
has body: It sounds like your Firefox version is having issues with said webpage. Although I'd say that the design of such site trying to show 200 JS driven plots seems questionable. As far as I know, there is little that you can do besides updating Firefox, they have been busy lately improving many elements of performance, or trying another browser with better JS performance like Chrome. If you're in a corporate network it might be many not possible for you to upgrade or install, then you have to go to you IT department looking for help. Now, since you're generating the HTML with the graphs, perhaps would it be a better idea for you to make a "dashboard" where you show a few and then use dropdown menus or sliders to control which plots are shown at any given time. I've seen solutions using using bokeh itself to do so, or if you want eventually somethign fancier you can also use flask.
answers question: http://stackoverflow.com/q/46885052
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/46872850
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46873257
has title: Detecting shift-click drag in QTextEdit using Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/46873257
tagged with: python
tagged with: qt
type: AnsweredQuestion
score: 2
tagged with: qtextedit
upvote count: 2
type: Question
has body: I'd like to subclass QTextEdit so that the user can change a text selection by moving either side of the selection using shift-click. Right now, shift-click does not permit the anchor to move. The first step, I believe is to override the default shift-click functionality. I've tried to do this using a mousePressEvent and also a mouseMoveEvent, but neither event triggers when I shift-click and move the mouse. How can I detect the shift-click drag currently used to modify the selection? My code is below. I vaguely remember reading that within a mouseMoveEvent, buttons equals "none". I cannot find that reference now though. If this is true, I'm even more perplexed. import sys from PySide.QtCore import * from PySide.QtGui import * class TextEditor(QTextEdit): def __init__(self, parent=None, text=None): super().__init__(parent) self.setReadOnly(True) self.setText(text) self.setMouseTracking(True) # Not sure if I will need this def mousePressEvent(self, event): if event.buttons==Qt.LeftButton: modifiers = QApplication.keyboardModifiers() if modifiers == Qt.ShiftModifier: print("Shift+Left Click") # This never triggers super().mousePressEvent(event) def mouseMoveEvent(self, event): if event.buttons==Qt.LeftButton: modifiers = QApplication.keyboardModifiers() if modifiers == Qt.ShiftModifier: print("Move and Shift + Left Button") # This never triggers super().mouseMoveEvent(event) if __name__ == '__main__': app = QApplication(sys.argv) window = TextEditor(text="Faction leaders unanimously decided to form a parliamentary inquiry committee...") window.show() sys.exit(app.exec_())
tagged with: pyside
tagged with: mousemove

reddit
tags question: http://stackoverflow.com/q/46840319
tags question: http://stackoverflow.com/q/46759912
type: Tag
tags question: http://stackoverflow.com/q/46872236
tag name: reddit

http://stackoverflow.com/comment/80686388
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46869446
has text: It seems tensorflow supports cuDNN 6.0 --- question: are you using jupyter? If so, have you created an environment and installed this tensorflow in this environment?

http://stackoverflow.com/q/46858506
tagged with: gradient
tagged with: tensorflow
type: Question
has title: Error while clipping gradient
score: 3
has answer: http://stackoverflow.com/a/46947231
answer count: 1
downvote count: 0
has body: I was following this tensorflow tutorial for gradient clipping while working with a multilayer perceptron. grads_and_vars = optimizer.compute_gradients(cross_entropy_loss, trainable_variable) capped_grads_and_vars = [(tf.clip_by_global_norm(gv[0],5), gv[1]) for gv in grads_and_vars] optimizer.apply_gradients(capped_grads_and_vars) tensorflow shows the following error, in clip_by_global_norm raise TypeError("t_list should be a sequence") trainable_variable is a list which I created while creating the model. assume I have a trainable variable(tf.Variable), I add this variable to trainable_variable list by the following command. trainable_variable.append(var) #where ver is a trainable variable in tensorflow
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46947231
upvote count: 3

http://stackoverflow.com/a/46778885
has body: docker logs shows by default the I/O streams STDOUT and STDERR. Check if Django logging in your settings.py is properly configured. For example: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler' }, }, 'loggers': { '': { # 'catch all' loggers by referencing it with the empty string 'handlers': ['console'], 'level': 'DEBUG', }, }, } Source Also worth to mention: Changed in Django 1.10: In older versions, log messages were written to sys.stderr instead of being handled through Python logging. https://docs.djangoproject.com/en/1.11/ref/django-admin/#runserver
downvote count: 0
score: 12
upvote count: 12
type: Answer
answers question: http://stackoverflow.com/q/46776596

http://stackoverflow.com/q/46826093
score: 2
tagged with: anaconda
has answer: http://stackoverflow.com/a/60997462
type: Question
has title: Permission Error For Conda Update
has answer: http://stackoverflow.com/a/46826425
answer count: 3
downvote count: 0
has body: Python newbie here. I have encountered a permission problem with anaconda. Everything runs ok, but I do not seem to be able to update conda, create new environments or install new packages. When I try to update (conda update conda) it I get: Fetching package metadata ..... An unexpected error has occurred. Please consider posting the following information to the conda GitHub issue tracker at: https://github.com/conda/conda/issues Current conda version: platform : osx-64 conda version : 4.3.29 conda is private : False conda-env version : 4.3.29 conda-build version : not installed python version : 2.7.11.final.0 requests version : 2.14.2 root environment : /anaconda (writable) default environment : /anaconda envs directories : /anaconda/Users/Tina/.conda/envs package cache : /anaconda/Users/Tina/.conda/pkgs channel URLs : https://conda.anaconda.org/anaconda-fusion/osx-64 https://conda.anaconda.org/anaconda-fusion/noarch https://repo.continuum.io/pkgs/main/osx-64 https://repo.continuum.io/pkgs/main/noarch https://repo.continuum.io/pkgs/free/osx-64 https://repo.continuum.io/pkgs/free/noarch https://repo.continuum.io/pkgs/r/osx-64 https://repo.continuum.io/pkgs/r/noarch https://repo.continuum.io/pkgs/pro/osx-64 https://repo.continuum.io/pkgs/pro/noarch config file : /Users/Tina/.condarc netrc file : None offline mode : False user-agent : conda/4.3.29 requests/2.14.2 CPython/2.7.11 Darwin/15.5.0 OSX/10.11.5 UID:GID : 501:20 $ /anaconda/bin/conda update conda Traceback (most recent call last): File "/anaconda/lib/python2.7/site-packages/conda/exceptions.py", line 640, in conda_exception_handler return_value = func(*args, **kwargs) File "/anaconda/lib/python2.7/site-packages/conda/cli/main.py", line 140, in _main exit_code = args.func(args, p) File "/anaconda/lib/python2.7/site-packages/conda/cli/main_update.py", line 65, in execute install(args, parser, 'update') File "/anaconda/lib/python2.7/site-packages/conda/cli/install.py", line 231, in install unknown=index_args['unk…
favorite count: 0
has answer: http://stackoverflow.com/a/46826627
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: permissions

http://stackoverflow.com/a/46762341
has body: As they mentioned, you need to keep a track of the list to get the min and max. Following your code structure : l = [] while True: reply = raw_input("Enter text, (type [stop] to quit): ") print reply.lower() if reply == 'stop': break l.append(int(reply)) #store the values x = min(l) y = max(l) print "Min is ", x print "Max is ", y IMP : Do not forget the int conversion Another space conservative method you can try is to compute the min and max as you get the input. import sys #placeholders maximum = -(sys.maxint) - 1 #highest negative value minimum = sys.maxint #highest positive value while True: reply = raw_input("Enter text, (type [stop] to quit): ") print reply.lower() if reply == 'stop': break reply=int(reply) if reply&lt;minimum : minimum = reply if reply&gt;maximum : maximum = reply print "Min is ", minimum print "Max is ", maximum
type: Answer
answers question: http://stackoverflow.com/q/46762195
score: 0

http://stackoverflow.com/q/46831389
has answer: http://stackoverflow.com/a/46831547
possible better answer: http://stackoverflow.com/a/46831682
tagged with: loops
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80610266
has title: Creating an if/else loop in Python
has answer: http://stackoverflow.com/a/46831682
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80610304
downvote count: 1
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/80611675
has comment: http://stackoverflow.com/comment/80610286
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
has body: I'm new to Python and I'm trying to create a very specific kind of loop. Nothing I read has really helped me. Maybe because it's not what I mean, or maybe because I don't understand. I'll try asking and hope someone understands me. I'm basically just trying to replay the four lines from the top. def defoption(): option = ("Give an input") #&lt;- Trying to replay this line option_input = input("Input: ") #&lt;- and then this if (option_input == 'a'): print("Option a works") else: return option and print("Option unavailable") defoption()
accepted answer: http://stackoverflow.com/a/46831547
tagged with: python
has comment: http://stackoverflow.com/comment/80610249
upvote count: 0
has comment: http://stackoverflow.com/comment/80610283

mapreduce
tags question: http://stackoverflow.com/q/46818020
type: Tag
tags question: http://stackoverflow.com/q/46826437
tags question: http://stackoverflow.com/q/46749342
tags question: http://stackoverflow.com/q/46880193
tag name: mapreduce
tags question: http://stackoverflow.com/q/46900034
tags question: http://stackoverflow.com/q/46882380

http://stackoverflow.com/q/46801390
has body: As shown in the following screenshot - pyspark 2.2.0 is recognized within the python 2.7.10 SDK: And the Intellij project is using that python sdk: However, the interpreter is not "agreeing" with the sdk: Furthermore the program can not be run:
tagged with: python
has comment: http://stackoverflow.com/comment/80553030
score: 0
accepted answer: http://stackoverflow.com/a/46816820
answer count: 1
has comment: http://stackoverflow.com/comment/80550195
tagged with: intellij-idea
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46816820
type: Question
has title: Python libraries not found even though available in the Project SDK Packages

http://stackoverflow.com/q/46880365
has answer: http://stackoverflow.com/a/46880385
tagged with: python
has body: I've been trying to break apart numbers and for some reason, the multiplication in line 6 doesn't seem to be working. number=list(input("Print number")) length = len(number) x=0 for x in range (0,len(number)): length = length - 1 a = number[x] * (10 ** length) print(a) Sample input: 123 Expected output: 100 20 3
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80707930
accepted answer: http://stackoverflow.com/a/46880385
type: Question
has answer: http://stackoverflow.com/a/46880635
has comment: http://stackoverflow.com/comment/80707947
has title: How to break apart numbers in Python?
has comment: http://stackoverflow.com/comment/80707923
has comment: http://stackoverflow.com/comment/80707916
possible better answer: http://stackoverflow.com/a/46880416
score: 0
has answer: http://stackoverflow.com/a/46880442
has answer: http://stackoverflow.com/a/46880416

http://stackoverflow.com/q/46752472
has comment: http://stackoverflow.com/comment/80451204
has comment: http://stackoverflow.com/comment/80450848
score: 0
has comment: http://stackoverflow.com/comment/80450855
has title: checking string presence in nested loop
answer count: 1
has body: I am writing on function which trying to extract the user name from Resume. Most of the time first line contains username but sometime also my students write Resume, CV title in first line. So I want to ignore such line and check for the next line. IF line without skip words within first four line of resume occurs, then consider it as a person name def name_extractor(self, text): skip_words = ['CURRICULUM', 'VITAE', 'resume'] text_lines = text.split('\n') name = '' # pdb.set_trace() for i in range(0,4): if text_lines[i]: for word in skip_words: if word.lower() in text_lines[i]: break else: name = text.split('\n')[i] # print name return name return name Here I tried to write the logic but it is not correctly working. If there is first line as resume, even it gives the name as resume. How can I skip any begining lines which have any word from skip_list and print the correct name. I appreciate any help on this.
has comment: http://stackoverflow.com/comment/80450743
tagged with: break
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46752779
accepted answer: http://stackoverflow.com/a/46752779
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/80450717

http://stackoverflow.com/comment/80722062
comment on: http://stackoverflow.com/q/46887127
has text: This is caused because you redefine (substitute) your `body` block from the base.html in the entry.html . I agree with the the @senaps you have to move it out or re-think your template's structure.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80623436
type: QuestionComment
type: Comment
has text: @user1190882 list of tablenames
comment on: http://stackoverflow.com/q/46837820
score: 0

http://stackoverflow.com/q/46866093
favorite count: 0
has body: After registration a pop up alert with ok message 'successfully registered' appeared. I tried handle that with below code. alert1= driver.switch_to_alert() alert1.accept() it is throwing below error. selenium.common.exceptions.NoAlertPresentException: Message: no alert open Is there any way to handle the popup ok message.
tagged with: python
possible better answer: http://stackoverflow.com/a/46866257
has answer: http://stackoverflow.com/a/46866241
has comment: http://stackoverflow.com/comment/80679898
has title: how to handle popup ok message accept with selenium alert
downvote count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/80679912
has comment: http://stackoverflow.com/comment/80679696
type: AnsweredQuestion
score: -2
has answer: http://stackoverflow.com/a/46866257
type: Question
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/46866241

http://stackoverflow.com/a/46882168
upvote count: 4
downvote count: 0
has body: You could use filter def get_non_empty_list(s, delimiter): return list(filter(str.strip, s.split(delimiter)))
type: Answer
answers question: http://stackoverflow.com/q/46881946
score: 4

http://stackoverflow.com/comment/80828851
has text: @Alex So, were you able to try out the posted suggestions?
type: AnswerComment
comment on: http://stackoverflow.com/a/46870227
score: 0
type: Comment

http://stackoverflow.com/comment/106870679
score: 1
comment on: http://stackoverflow.com/a/57567444
type: AnswerComment
type: Comment
has text: Thanks. Didn't know that command existed. Runs it, gets fixed instantly. Thanks.

http://stackoverflow.com/q/46757220
has answer: http://stackoverflow.com/a/46758059
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46758061
possible better answer: http://stackoverflow.com/a/46758061
type: Question
tagged with: numpy
has title: Can anyone explain this list comprehension?
answer count: 2
accepted answer: http://stackoverflow.com/a/46758059
score: 0
has body: def unpack_dict(matrix, map_index_to_word): table = sorted(map_index_to_word, key=map_index_to_word.get) data = matrix.data indices = matrix.indices indptr = matrix.indptr num_doc = matrix.shape[0] return [{k:v for k,v in zip([table[word_id] for word_id in indices[indptr[i]:indptr[i+1]] ], data[indptr[i]:indptr[i+1]].tolist())} \ for i in range(num_doc) ] wiki['tf_idf'] = unpack_dict(tf_idf, map_index_to_word) map_index_to_word is dictionary of word:index for few thousand words. tf_idf is TFIDF sparse vector DataFrame wiki is displayed in screenshot here
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/a/46834050
has comment: http://stackoverflow.com/comment/80635232
score: 1
has body: I think that execution time will be about constant in most cases, with the notable exception of data modifying CTEs (see below). If the CTE never gets used, it is not executed. The exception to this rule is if there is a data modifying statement in the CTE; in this case, the CTE is always executed. I don't think there is a better way in PL/Python. If you write a C function you could probably prepare the statement and then get its result columns, but it's probably non-trivial as well. No cool story to share... The planning time is independent of the size of the tables.
upvote count: 1
has comment: http://stackoverflow.com/comment/80616816
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46833173
accepted answer of: http://stackoverflow.com/q/46833173
type: Answer

http://stackoverflow.com/q/46814785
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80586008
tagged with: python
has body: I use a portable install of SublimeText on a USB drive with the Anaconda plugin installed for python work. This tells me how to change which python interpreter to use. My issue is that I want to carry a version of python with me on the same USB stick. As you're all probably aware, different computers will assign the stick different drive letters, so I can't just use E:\MyPython\python.exe. I need to and hope it's possible to use a relative path. I'm not sure where the path is starting from, so I don't know how many ..\..\..\etc. I need to add to get to my python. I'm using (or at least experimenting with using) WinPython or WinPythonZero, since they seem to be the most actively maintained versions of a portable python ecosystem. (I require pip in addition to just the plain python interpreter). Has anyone else tried a setup like this? Any help would be awesome! Thanks! Oh, I'm sticking with Python3 as well.
tagged with: sublime-anaconda
downvote count: 0
answer count: 0
score: 1
type: Question
upvote count: 1
has title: How to set a relative path to a python interpreter in sublime's Anaconda IDE
tagged with: sublimetext3
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/46852757
score: 1
has comment: http://stackoverflow.com/comment/80653207
has body: Create file like not_main_start.py with only one line import main.py (I guess this is your main file). Run then this file. Output should show no main. __name__ would be name __main__ only if you call this file directly. If you use it as module then it will have name of the module.
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46850810

http://stackoverflow.com/q/46896443
has body: I want to iterate through a list of items and log a score for each item. I do not know how to define a function to wait until a key is pressed. I have tried mscvrt and cv. I do not want to use input(), because I want it to work whatever the screen is on. I just want it to know if that key is pressed and then continue. I use python 3. def wait_for_key(): #wait until a key is pressed, return that key def score_list(): a = [jack, lauren, taylor] b = [] for item in a: score = wait_for_key() itemscore = item + ", " + score b.append(itemscore)
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/13380938
has title: Pythonic way to wait for pressed key for each item in a list - then do something based on key pressed-
answer count: 0
tagged with: pressed
type: Question
has comment: http://stackoverflow.com/comment/80740155
tagged with: wait
has comment: http://stackoverflow.com/comment/80740100
score: 0
tagged with: key

http://stackoverflow.com/a/46886742
has comment: http://stackoverflow.com/comment/80754298
has comment: http://stackoverflow.com/comment/80796146
has comment: http://stackoverflow.com/comment/80801500
type: Answer
has comment: http://stackoverflow.com/comment/80801665
accepted answer of: http://stackoverflow.com/q/46883245
has comment: http://stackoverflow.com/comment/80760642
has body: For it to work you need to do a couple of things, first cv2.blur needs a destination and not a number. This can be achieved with: image[y:y+h, x:x+w] = cv2.blur(image[y:y+h, x:x+w] ,(23,23)) Since you are saving the image to the same file in every loop, you can just save it after the loop. Since you wanted a circular bur, you need to create a circular mask, then apply it to the image, here is how your code will look like (only the loop part): # create a temp image and a mask to work on tempImg = image.copy() maskShape = (image.shape[0], image.shape[1], 1) mask = np.full(maskShape, 0, dtype=np.uint8) # start the face loop for (x, y, w, h) in faces: #blur first so that the circle is not blurred tempImg [y:y+h, x:x+w] = cv2.blur(tempImg [y:y+h, x:x+w] ,(23,23)) # create the circle in the mask and in the tempImg, notice the one in the mask is full cv2.circle(tempImg , ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (0, 255, 0), 5) cv2.circle(mask , ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (255), -1) # oustide of the loop, apply the mask and save mask_inv = cv2.bitwise_not(mask) img1_bg = cv2.bitwise_and(image,image,mask = mask_inv) img2_fg = cv2.bitwise_and(tempImg,tempImg,mask = mask) dst = cv2.add(img1_bg,img2_fg) cv2.imwrite("/home/pi/Desktop/cricle-test/output_0020.jpg" ,dst) This seems to work, at least in my test, you may try adjusting the kernel size (this (23,23) in the blur) to get less or more blurred image, for example, try this code with (7,7) it will have more details. Update If you want to use ellipses instead of circles just change the circle instruction to: cv2.ellipse(mask , ( ( int((x + x + w )/2), int((y + y + h)/2 )),(w,h), 0), 255, -1) The same way you can change it to a rectangle, polygon, or any other shape.
has comment: http://stackoverflow.com/comment/80769314
upvote count: 12
has comment: http://stackoverflow.com/comment/80723836
has comment: http://stackoverflow.com/comment/80752441
score: 12
answers question: http://stackoverflow.com/q/46883245
has comment: http://stackoverflow.com/comment/80721333
has comment: http://stackoverflow.com/comment/80721335
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80721388

http://stackoverflow.com/comment/80506492
has text: So you are converting a string to a list, and use a list comprehension to convert that list to a string ? Why? Please show `fields`
score: 0
comment on: http://stackoverflow.com/q/46780221
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46855434
downvote count: 0
has comment: http://stackoverflow.com/comment/80658374
has comment: http://stackoverflow.com/comment/80658581
has comment: http://stackoverflow.com/comment/80658405
accepted answer: http://stackoverflow.com/a/46855653
favorite count: 0
has title: Django model cannot call app module methods
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: django-models
has answer: http://stackoverflow.com/a/46855653
has body: I have a django app with the following structure: . ├── admin.py ├── apps.py ├── Business ├── __init__.py ├── migrations ├── models ├── __pycache__ ├── templates ├── tests.py ├── urls.py └── views In the model folder I have an __init__.py file which contain the following code: from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from web.Business.rockynodeZabbix import Zabbix @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_zabbix_group(sender, instance=None, created=False, **kwargs): if created: Zabbix.component("HostGroup").create(instance.id) The issue it that i cannot import my app web module methods in the models since in several classes in the Business module am calling the model module: import web.models as models If I import the app module web.Business.xxxx in my model i get the following error: File "/Users/kheshav/Linux_projects/rockynode.io/App/web/models/__init__.py", line 11, in &lt;module&gt; from web.Business.rockynodeZabbix import Zabbix File "/Users/kheshav/Linux_projects/rockynode.io/App/web/Business/__init__.py", line 1, in &lt;module&gt; from .test import test File "/Users/kheshav/Linux_projects/rockynode.io/App/web/Business/test.py", line 1, in &lt;module&gt; import web.models as models AttributeError: module 'web' has no attribute 'models How do i call my app module function in the model since i want to trigger it when a user is created.
type: Question
answer count: 1

http://stackoverflow.com/comment/80667598
has text: Is is to long to read?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46859942
type: Comment

http://stackoverflow.com/comment/80466974
has text: @AmritpalsinghThethi Did you check for the ending `\n` new line characters?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46760661

http://stackoverflow.com/q/46894995
has answer: http://stackoverflow.com/a/46895014
type: Question
score: -1
answer count: 1
accepted answer: http://stackoverflow.com/a/46895014
has comment: http://stackoverflow.com/comment/80737129
has comment: http://stackoverflow.com/comment/80737159
favorite count: 0
has title: Create custom list in python
tagged with: python
tagged with: dictionary
has body: ccode = ['#005a32', '#ddf2a7', '#bfe596', '#ffffcc'] I am looking to generate the following output with the above color code array. Is there anyway that I can run this a loop? For the large sized Color Code array it will be useful. df1['style'] = [ {'fillColor': '#005a32', 'weight': 2, 'color': 'black'}, {'fillColor': '#ddf2a7', 'weight': 2, 'color': 'black'}, {'fillColor': '#bfe596', 'weight': 2, 'color': 'black'}, {'fillColor': '#ffffcc', 'weight': 2, 'color': 'black'}, ]
has comment: http://stackoverflow.com/comment/80737658
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
downvote count: 2
upvote count: 1

http://stackoverflow.com/a/46807912
type: Answer
answers question: http://stackoverflow.com/q/46807782
has body: Use string.Formatter from string import Formatter s = 'Hello {name}. Are you {debil_status}' keys = [i[1] for i in Formatter().parse(s)] print keys &gt;&gt;&gt; ['name', 'debil_status']
score: 0

http://stackoverflow.com/comment/80722586
comment on: http://stackoverflow.com/q/46887098
score: 0
has text: @DoctorDoom Yeah, you're right. I was using Python 3 which gave a different result. I have updated my answer for use with Python 2
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46855523
answers question: http://stackoverflow.com/q/46844834
upvote count: 3
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/46844834
has comment: http://stackoverflow.com/comment/80691117
has body: If that worked previously I'd say it was unintentional undefined behavior. The show function has always had in mind that it was for replacing the output in the next output cells, so running it multiple times in one cell was never a usage pattern that was considered. In any event, adding support for support JupyterLab has necessitated various changes to notebook display machinery, and that's probably the immediate reason you are seeing a difference. However, I would say that the current behavior is correct, and what should be expected going forward. The right way to do something like this is to collect the plots in a layout of some kind, and then show the layout: from bokeh.layouts import column layout = column() for x in foo: p = figure() layout.children.append(p) show(layout)
type: AcceptedAnswer

http://stackoverflow.com/q/46850698
accepted answer: http://stackoverflow.com/a/46850796
tagged with: python
favorite count: 0
upvote count: 2
has title: Pandas DataFrame seems not to have "factorize" method
type: Question
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80657854
has answer: http://stackoverflow.com/a/46850796
possible better answer: http://stackoverflow.com/a/46850910
has comment: http://stackoverflow.com/comment/80649485
has answer: http://stackoverflow.com/a/46850910
tagged with: python-3.5
downvote count: 0
has body: I am currently studying the jupyter course of Machine Learning from https://github.com/ageron/handson-ml in chapter02, the Pandas DataFrame "housing_cat" should be factorized by pandas method "factorize" housing_cat.factorize() However, python tells me 'DataFrame' object has no attribute 'factorize' When I type "housing_cat." and use TAB for method selection I cannot find "factorize", too. Pandas is imported by "import pandas" and type(housing_cat) also tells me it is a pandas dataframe. I use pandas v0.20.3 So what could be the problem here?
has answer: http://stackoverflow.com/a/48477049
answer count: 3
tagged with: pandas

http://stackoverflow.com/a/46890545
has comment: http://stackoverflow.com/comment/80728537
answers question: http://stackoverflow.com/q/46890464
has comment: http://stackoverflow.com/comment/80728262
has body: Your apache config is using Django 1.8.7 as you can see in your error. And you're using a newer method for including urls (url(r'^users/', include('users.urls'), name='users') inside urls.py which wasn't supported in Django 1.8. Since your switched from python 2.7 to python 3.5 it's quite likely your mod_wsgi module is still the one compiled with python 2.7. Here's what the WSGI docs say about that: When using a Python virtual environment with mod_wsgi, it is very important that it has been created using the same Python installation that mod_wsgi was originally compiled for. It is not possible to use a Python virtual environment to force mod_wsgi to use a different Python version, or even a different Python installation. You cannot for example force mod_wsgi to use a Python virtual environment created using Python 3.5 when mod_wsgi was originally compiled for Python 2.7. This is because the Python library for the Python installation it was originally compiled against is linked directly into the mod_wsgi module. In other words, Python is embedded within mod_wsgi. When mod_wsgi is used it does not run the command line python program to run the interpreter and thus why you can’t force it to use a different Python installation. So try re-installing mod_wsgi using python 3.5. That should then be able to find the Django package you installed with python 3.5.
accepted answer of: http://stackoverflow.com/q/46890464
has comment: http://stackoverflow.com/comment/80728467
has comment: http://stackoverflow.com/comment/80729950
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80728389
score: 0
type: Answer

http://stackoverflow.com/q/46840637
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/44574086
answer count: 1
has title: Understand the syntaxe X[Y == c] in Numpy
has answer: http://stackoverflow.com/a/46840656
accepted answer: http://stackoverflow.com/a/46840656
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/44574086
type: Question
has body: Please I don't understant how this syntax works: current_x = X[Y == c]. I've printed out in Ipython some sample with the code (I use pandas here as pd): In [120]: pd.DataFrame(X) Out[120]: 0 1 2 3 4 5 6 7 8 9 ... 475 \ 0 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 1 0.070588 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 2 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 3 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 4 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 5 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 6 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 7 0.596078 0.596078 0.062745 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 8 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 9 0.000000 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 476 477 478 479 480 481 482 483 484 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 3 0.0 0.0 0.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 5 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 7 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 9 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 [10 rows x 485 columns] In [121]: pd.DataFrame(Y) Out[121]: 0 0 1 1 7 2 9 3 4 4 5 5 1 6 1 7 6 8 1 9 1 In [122]: pd.DataFrame(X[Y == 5]) Out[122]: 0 1 2 3 4 5 6 7 8 9 ... 475 476 477 478 \ 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 479 480 481 482 483 484 0 0.0 0.0 0.0 0.0 0.0 0.0 [1 rows x 485 columns] I don't How X[Y == 5] has come with that result. Please hep-lp
tagged with: numpy

http://stackoverflow.com/a/46880535
downvote count: 0
has comment: http://stackoverflow.com/comment/80708450
has comment: http://stackoverflow.com/comment/80708426
has body: In my case, this problem was caused by sys.path looking in the 2.7 site-packages directory before looking in 3.6. In your sys.path, it looks like you're having a similar issue. Calling python3 loads Python 3.5 from Anaconda. But all of the Anaconda 3.5 site-package directories are checked after the 2.7 directories. # from OP sys.path /usr/local/lib/python2.7/site-packages /usr/local/Cellar/matplotlib/2.0.2/libexec/lib/python2.7/site-packages /usr/local/Cellar/numpy/1.13.3/libexec/nose/lib/python2.7/site-packages /Users/mymacbook/anaconda/lib/python3.5/site-packages # &lt;-- should be before 2.7 ^ That's what's causing the problem. I tried a number of different solutions to fix this, including getting rid of .pth files and re-routing sys.path in-script. Eventually I just removed the numpy directory from the 2.7 site-packages, as I didn't need it, and I was frustrated trying to trace exactly how sys.path was constructed and re-order it permanently. If you don't want to be that extreme, have a look at the site docs if you want to trace exactly how sys.path is put together.
type: Answer
has comment: http://stackoverflow.com/comment/80708867
has comment: http://stackoverflow.com/comment/80708651
answers question: http://stackoverflow.com/q/46880388
upvote count: 1
has comment: http://stackoverflow.com/comment/80708979
score: 1
has comment: http://stackoverflow.com/comment/80708709
has comment: http://stackoverflow.com/comment/80723048

http://stackoverflow.com/q/46857179
has comment: http://stackoverflow.com/comment/80662068
has comment: http://stackoverflow.com/comment/80662134
has body: I'm having trouble getting images to upload to an S3 bucket from Django The error I'm getting is: 'InMemoryUploadedFile' object has no attribute 'get' I've looked at similar questions, but haven't found a solution from them (or others not listed below): ModelForm has no attribute get Django image uploading django 'User' object has no attribute 'get' error Here's my code: forms.py from django import forms from .models import UploadImage, UploadAudio class ImageForm(forms.ModelForm): class Meta: model = UploadImage fields = ['myimage'] views.py from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect from .forms import ImageForm, AudioForm from .models import UploadImage def ImageCreate(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES['myimage']) if form.is_valid(): image = form.save(commit=False) image.author = request.user image.save() messages.success(request, "Uploaded successfully") return redirect('mytimer') else: messages.error(request, "Unable to upload at this time") else: form = ImageForm() return render(request, "myimages.html", {'form': form}) models.py from __future__ import unicode_literals from django.db import models from django.conf import settings class UploadImage(models.Model): """ Define how the user will upload images """ # link author to registered user author = models.ForeignKey(settings.AUTH_USER_MODEL) myimage = models.ImageField(upload_to='myimages/') uploaded_at = models.DateTimeField(auto_now_add=True) Thank you so much in advance for any help. traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/myimages/ Django Version: 1.11.6 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello…
score: 5
accepted answer: http://stackoverflow.com/a/46857292
tagged with: python
type: AnsweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/80662297
tagged with: amazon-s3
linked to: http://stackoverflow.com/q/28336247
upvote count: 5
linked to: http://stackoverflow.com/q/33445812
has title: 'InMemoryUploadedFile' object has no attribute 'get'
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80662088
linked to: http://stackoverflow.com/q/7241743
has answer: http://stackoverflow.com/a/46857292
tagged with: media
favorite count: 0

http://stackoverflow.com/q/46839075
score: 1
has comment: http://stackoverflow.com/comment/80626122
has comment: http://stackoverflow.com/comment/80626174
favorite count: 0
has answer: http://stackoverflow.com/a/46839981
has title: Index of a numpy array within a sequence
has comment: http://stackoverflow.com/comment/80626108
has comment: http://stackoverflow.com/comment/80625931
has comment: http://stackoverflow.com/comment/80626111
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80626575
tagged with: python
has comment: http://stackoverflow.com/comment/80626303
has answer: http://stackoverflow.com/a/46839203
has answer: http://stackoverflow.com/a/46839296
upvote count: 1
has comment: http://stackoverflow.com/comment/80626392
has body: I want to find the index of a particular numpy array with in a sequence. For example, given: import numpy as np WHITE = np.array([255, 255, 255]) BLUE = np.array([0, 0, 255]) GRAY = np.array([192, 192, 192]) BLACK = np.array([0, 0, 0]) GREEN = np.array([0, 255, 0]) YELLOW = np.array([255, 255, 0]) COLORS = (WHITE, BLUE, GRAY, BLACK, GREEN) I'd like to be able to ask for something like print(COLORS.index(GRAY)) but this leads to the error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I do have a workaround, but it feels overly acrobatic: def index_of(x, sequence): eq = list((item == x).all() for item in sequence) return eq.index(True) print(index_of(GRAY, COLORS)) Is there are more elegant/Pythonic way to do this?
has comment: http://stackoverflow.com/comment/80627101
type: Question
tagged with: numpy
downvote count: 0
answer count: 3

http://stackoverflow.com/a/46822127
answers question: http://stackoverflow.com/q/46821761
score: 0
type: Answer
has body: If you're willing to import from functools, you can use the partial class and the iter function, which can take a sentinel argument to tell the iterator on which input to terminate. from functools import partial def listave(list): UserInput = iter(partial(input, 'Enter integer (q to quit):'), 'q') for inp in UserInput: try: list.append(int(inp)) except ValueError: pass print('Average: ', float(sum(list) / len(list))) listave(list)

http://stackoverflow.com/comment/80555851
score: 0
type: Comment
has text: also when i try to use the same logic for the project scores it comes up with the same number for quiz scores as it does for project scores even though ive changed the variables, any idea whats going on there>?
comment on: http://stackoverflow.com/a/46803284
type: AnswerComment

http://stackoverflow.com/comment/80581380
type: Comment
comment on: http://stackoverflow.com/q/46816545
score: 0
type: QuestionComment
has text: [Here's](https://stackoverflow.com/a/45164619/4014959) a demo I wrote that processes user input while performing another task in a separate thread.

http://stackoverflow.com/q/46755932
has body: In the code below I have tried to find out if an object is green in colour and draw a contour around it. With that information I would also like to find the corners of the shape and crop it, but I get an error related to the ConvexHull function which I have not used in the code. I have used python 3 and Opencv 3.2.0 The code that I have written gives me this error Traceback (most recent call last): File "/home/pi/Desktop/SelfDrivingCar/code/picamsense2.py", line 29, in &lt;module&gt; points = cv2.minAreaRect(contour) error: /home/pi/opencv/opencv-3.2.0/modules/imgproc/src/convhull.cpp:136: error: (-215) total &gt;= 0 &amp;&amp; (depth == CV_32F || depth == CV_32S) in function convexHull Here is my code from picamera import PiCamera import time import cv2 import numpy as np camera = PiCamera() camera.start_preview() time.sleep(5) camera.capture('/home/pi/Desktop/piImage/image.jpg') camera.stop_preview() img = cv2.imread('/home/pi/Desktop/piImage/image.jpg', 1) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower = np.array([46, 100, 100]) upper = np.array([86, 255, 255]) mask = cv2.inRange (hsv, lower, upper) blur = cv2.GaussianBlur(mask, (7,5),0 ) erosion =cv2.erode(blur, (5,5), iterations = 3) contour =np.array( cv2.findContours(erosion, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]) cv2.drawContours(img, contour, -1, (0,255,0), 3) for cnt in contour: approx = cv2.approxPolyDP(cnt, 0.04*cv2.arcLength(cnt, True), True) if len (approx)== 3: print "triangle" elif len (approx) == 4 : print "quadrilateral" elif len(approx) &gt; 4: print "circle" points = cv2.minAreaRect(contour) points = cv2.boxPoints(points) points = np.int0(points) for p in points : pt = (p[0],p[1]) print pt print points cv2.imshow('eroded', blur) cv2.imshow('original', img) while (1): k = cv2.waitKey(0) if(k == 27): break cv2.destroyAllWindows() I have been trying to look for a fix for quiet some time now Any help would be appreciated thanks in advance -Sam
tagged with: python
accepted answer: http://stackoverflow.com/a/46759205
upvote count: 2
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/80457617
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69777557
has title: Error with cv2.minAreaRect , gives me Error related to convex hull function which i haven't used
possible better answer: http://stackoverflow.com/a/67325096
tagged with: raspberry-pi
answer count: 3
has answer: http://stackoverflow.com/a/46759205
has answer: http://stackoverflow.com/a/67325096
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/46877280
type: Answer
has body: Use the 'count' action rather than 'store_true': In [373]: parser = argparse.ArgumentParser() In [374]: parser.add_argument('filename', nargs='+'); In [375]: parser.add_argument('-i', action='count'); In [376]: args = parser.parse_args('-i -i myfile.txt'.split()) In [377]: print(args) Namespace(filename=['myfile.txt'], i=2) In [378]: for i in range(args.i): print(args.filename) ['myfile.txt'] ['myfile.txt'] Without -i: In [379]: args = parser.parse_args('myfile.txt'.split()) In [380]: print(args) Namespace(filename=['myfile.txt'], i=None) With the default None, you'd need catch the None case with: if args.i: # do the rest Setting the default to 0 would simplify that testing: parser.add_argument('-i', action='count', default=0);
answers question: http://stackoverflow.com/q/46876092
score: 0

http://stackoverflow.com/a/46901997
has comment: http://stackoverflow.com/comment/80750773
has body: You need a list comprehension, not a dict comprehension: lowercase_data = [v.lower() for v in data]
type: Answer
has comment: http://stackoverflow.com/comment/80750876
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/80750749
has comment: http://stackoverflow.com/comment/80750796
score: 5
answers question: http://stackoverflow.com/q/46901975

http://stackoverflow.com/a/62314386
score: 2
has body: the simply way to convert data format is to use the following formula. In this case it is possible to convert any array to a new custom format. # In the case of image, or matrix/array conversion to the uint8 [0, 255] # range Import numpy as np new_data = (newd_ata - np.min(new_data)) * ((255 - 0) / (np.max(new_data) - np.new_data))) + 0
downvote count: 0
answers question: http://stackoverflow.com/q/46866586
upvote count: 2
type: Answer

http://stackoverflow.com/q/46832115
has comment: http://stackoverflow.com/comment/80614797
has comment: http://stackoverflow.com/comment/80613766
has answer: http://stackoverflow.com/a/46833611
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80613429
favorite count: 0
has comment: http://stackoverflow.com/comment/80613168
type: Question
upvote count: 2
has title: Why is the Django decimal max_digits validation failing with strange behaviour?
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/46833611
has comment: http://stackoverflow.com/comment/80621445
linked to: http://stackoverflow.com/q/1995615
has comment: http://stackoverflow.com/comment/80612744
has comment: http://stackoverflow.com/comment/80621156
has body: I have a model field full_time_equivalent: full_time_equivalent = models.DecimalField( max_digits=5, decimal_places=2, default=100, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100)) ] ) To ensure that the validators fire I have override save with: def save(self, *args, **kwargs): # Run validations self.full_clean() return super().save(*args, **kwargs) With the following test: project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=10.01 ) When I step into the validation the following value is shown and respective error: Decimal('10.0099999999999997868371792719699442386627197265625') django.core.exceptions.ValidationError: {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.'] What am I doing wrong?
answer count: 1

http://stackoverflow.com/comment/80557054
type: Comment
comment on: http://stackoverflow.com/a/46804977
type: AnswerComment
has text: it gives me this error: if data.count("}") > data.count("{"): AttributeError: 'file' object has no attribute 'count'
score: 0

http://stackoverflow.com/a/46878731
has body: Create your User model like so: from django.core import validators from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=75, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' 'underscores characters'), validators=[ validators.RegexValidator(re.compile('^[\w]+$'), _('Enter a valid username.'), 'invalid') ]) first_name = models.CharField(_('first name'), max_length=254, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), max_length = 254, unique = True, null = True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name'] def get_full_name(self): return self.name def get_short_name(self): return self.username Don't forget to add your custom fields! Use a custom admin like so: @admin.register(models.User) class CustomUserAdmin(UserAdmin): list_display = ('name', 'username', 'is_staff', ) list_filter = ('is_staff', ) search_fields = ('first_name', 'last_name', 'username', ) readonly_fields = ('date_joined', 'last_login', ) fieldsets = ( (None, { 'fields': ('username', 'password') }), ("Personal Information", { 'fields': ('first_name', 'last_name', 'email') }), ("Permissions", { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), ("Important Dates", …
type: Answer
answers question: http://stackoverflow.com/q/46877213
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80743266
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46877213
has comment: http://stackoverflow.com/comment/80743301

http://stackoverflow.com/comment/80604610
has text: @andrea56, ok then you can ignore my suggestion. Did the regex solution work? And, I don't understand your last statement. I don't speak your language.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46827395

http://stackoverflow.com/q/46881673
type: Question
accepted answer: http://stackoverflow.com/a/46883682
possible better answer: http://stackoverflow.com/a/46882076
has answer: http://stackoverflow.com/a/46882076
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
has body: Hello I was trying to test selenium and chrome webdriver by creating a script that will open up the browser to a specific site. Here is my code below: import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys def open_browser(user_string): browser = webdriver.Chrome() browser.get(user_string) def main(): x = input("Where would you like to open the internet to? ") open_browser(x) if __name__ == '__main__': main() However, when I run this in the shell, a blank window opens for a few seconds then closes and I get these errors: 124:63332:1022/202611.560:ERROR:persistent_memory_allocator.cc(815)] Corruption detected in shared-memory segment. 124:60160:1022/202621.325:ERROR:shader_disk_cache.cc(237)] Failed to create shader cache entry: -2 I have no idea what could be causing these errors.
has answer: http://stackoverflow.com/a/46883682
has title: Chrome webdriver selenium memory error- python 3
tagged with: selenium
tagged with: google-chrome

http://stackoverflow.com/comment/80703365
type: QuestionComment
comment on: http://stackoverflow.com/q/46872668
score: 0
has text: I'm not here to teach people how to program; I'm not paid enough to do so, and I have better things to do anyway. I try to make people think, but I don't always succeed.
type: Comment

http://stackoverflow.com/comment/80674723
has text: The point is not that i suppose.. I mean, the function will return the url in future, but the error remains even if i add something to return
type: Comment
comment on: http://stackoverflow.com/a/46863634
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80610504
has text: The order of the path matters, sorry, ill add that to the question too.
comment on: http://stackoverflow.com/q/46830943
type: QuestionComment
type: Comment
score: 0

rx-py
tag name: rx-py
tags question: http://stackoverflow.com/q/46876527
type: Tag

http://stackoverflow.com/comment/80704354
has text: For POSIX, yes, because `/bin/sh` is by definition the system shell.
comment on: http://stackoverflow.com/a/46878360
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80705164
comment on: http://stackoverflow.com/q/46879025
has text: If your container runs a service, poke the service to see if it's operational.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46835633
upvote count: 22
type: AnsweredQuestion
downvote count: 0
tagged with: widget
accepted answer: http://stackoverflow.com/a/46836189
tagged with: django
type: Question
tagged with: overriding
has answer: http://stackoverflow.com/a/46836189
has title: Django widget template override does not search in the project template directory. How to fix?
answer count: 1
score: 22
favorite count: 0
has body: I am attempting to override a built in widget template in Django 1.11. I seem to be doing everything that the docs say to do in this regard, but for the widget templates, Django is not looking in my project at all, and I get a TemplateDoesNotExist error. Here's what I have for the override: class MyFileWidget(widgets.FileInput): template_name = 'myapp/my_file_widget.html' The template is definitely there. If I pass the template to a render call, it finds it fine. Problem is an issue of paths. When calling render from a view, it checks the following: projectroot/templates/myapp/my_file_widget.html djangoroot/forms/templates/myapp/my_file_widget.html When it finds the template in my project, it renders it. This is NOT happening when I provide the template path in the class above. In that case, it does not check in my project templates, where the file actually exists, and begins checking in the django path, where it does not. Hence the error message. So I have no clue why this the loader would check my project templates on render calls, but then fail to do so when looking for the "template_name" of the widget override. Any ideas?
tagged with: python
tagged with: templates

http://stackoverflow.com/comment/80462246
has text: do a for loop that loops through all of the lines list and compares them to the input
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46758445
score: 0

http://stackoverflow.com/a/46815085
has comment: http://stackoverflow.com/comment/80607359
type: Answer
has body: If I understand the problem correctly, it looks like you don't want measure to return until after the loop has finished running. If that is the case, you can use tkinter's ability to wait for a variable to be set before continuing. You might try modifying your code to look like this: def measure(name): flag = BooleanVar() ... def loop(): ... if voltage &gt; -0.01: ... print 'data', data flag.set(True) ... loop() root.wait_variable(1000, loop) With the above, measure will not return until the flag is set, and the flag won't be set until the loop completes. An event-based solution Personally I would never do it like that, however. It seems that what you're trying to do is say "do something when the voltage rises above a threshold". A rising voltage can be thought of as just another event, just like clicking a button or typing some text. If that is the case, you might want to create and bind to virtual events. For example, you might want to create the events "&lt;&lt;Voltage-A&gt;&gt;" and "&lt;&lt;Voltage-B&gt;&gt;" which represent the A and B voltages rising. You can bind to those events so that when they happen, you do whatever it is you need to do. Also, since you want to measure B only after the voltage on A has risen, you can trigger the measurement of B on the same event. Here's a somewhat contrived example based on your original code: from Tkinter import * def measure(name): global voltage, data data = [] if name == "A": voltage = -0.2 limits = +0.2 else: voltage = -0.1 limits = +0.1 def loop(): global voltage , data data.append(round(voltage,3)) voltage += 0.02 if voltage &gt; -0.01: voltage = 0 data.append(round(voltage,3)) root.after_cancel(loop) event_name = "&lt;&lt;Voltage-%s&gt;&gt;" % name print 'data', data root.event_generate(event_name) else: root.after(1000, loop) loop() def print_data(name): global data print name, data root = Tk() root.title("A Tool") Button(root, text="Test other",width=38, height = 8, bg='gray',command=lambda:measure("A")).pack(…
answers question: http://stackoverflow.com/q/46807716
accepted answer of: http://stackoverflow.com/q/46807716
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/46826725
has comment: http://stackoverflow.com/comment/80601064
score: 0
has comment: http://stackoverflow.com/comment/80601074
answers question: http://stackoverflow.com/q/46826617
type: Answer
has body: In your case, col looks like some kind of a collection. You probably want to do this: List_of_dummy_names.append('BINARY_'+string)

http://stackoverflow.com/q/46788908
tagged with: python
has comment: http://stackoverflow.com/comment/80533703
linked to: http://stackoverflow.com/q/4789837
type: Question
has body: I have a python script and it will call ssh process to create remote process A. A will create a ssh subprocess to server B. When I run the script and Ctrl-C to interrupt it, the A will close in remote side. But the ssh forked by A still executed. Here's my script: import os import inspect import logging import sys import subprocess import signal CURRENT_DIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) PYTHON_PATH = '/usr/local/bin/python' SNAPSYNC_PATH = CURRENT_DIR + '/snapsync.py' EXECUTE_PATH = PYTHON_PATH + ' ' + SNAPSYNC_PATH if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) cmd = 'ssh -p 22 -C -oServerAliveInterval=600 -oServerAliveCountMax=3 remote_ip "a.py" ' logging.info(cmd) try: handle = subprocess.Popen(cmd, bufsize=0, stdin=None, shell=True) except KeyboardInterrupt: print "Caught KeyboardInterrupt, terminating workers" handle.terminate() handle.kill() I want to know how to kill the B process when I Ctrl-C to the local script?
score: 0
tagged with: linux
has title: how to kill sub-processes(ex ssh) forked by remote subprocess called by local python script
tagged with: ssh
has comment: http://stackoverflow.com/comment/80524921
tagged with: subprocess
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/46762884
linked to: http://stackoverflow.com/q/34253996
accepted answer: http://stackoverflow.com/a/46762941
possible better answer: http://stackoverflow.com/a/46762950
linked to: http://stackoverflow.com/q/5737196
has comment: http://stackoverflow.com/comment/80471048
type: Question
has comment: http://stackoverflow.com/comment/80471033
has title: How could I make an infinite "For" loop able to save values, without using "while"?
has comment: http://stackoverflow.com/comment/80472657
has comment: http://stackoverflow.com/comment/80471194
has body: I'm learning Python (using 3.6.2) and on my last class, they asked me to do something where I need to make an infinite for loop. For some reason, the teacher doesn't want us to use while for the entire practice. This is where it gets complicated... So, I've been looking for a way to do it. But, it's also difficult because the teacher doesn't want us to use any commands we haven't seen in class. So I can't use .append, sys functions, well, I can't even use a break. I must find a way to do with "simple" commands. I thought I could do it this way; x=1 for i in range(x): do_something() x += 1 However, it didn't seemed to work. I think that's because Python doesn't read the value for the range again? I couldn't find a way, but after hours of thinking I found myself a small workaround I could use: def ex(): print("Welcome") for i in range(1): math = int(input("Please insert grades obtained at Math, or insert 666 to exit" )) if(math &gt; 0 and math &lt; 60): print("Sorry. You failed the test") return ex(): elif(math &gt;= 60 and math &lt;= 100): print("Congratulations. You passed the test") return ex(): elif(math == 666): return exit() else: print("ERROR: Please insert a valid number") return ex(): def exit(): pass As you can see, what makes it "infinite" is that it returns to the function once and once again, until you tell the program to "exit", by entering "666". I'd also like to have a more proper way to exit the function. I'm still wondering if there's a better way to make my for loop infinite until the user calls it to stop. However, one way or another I got this exercise working. The problem came when I started with the second one, which is more or less like this: Imagine the same past program, but this time, it will not just show you if you passed the test or not. It wants to collect as many grades you enter through the input, and then calculate the average of all the grades. I'm not able to save those values (the grades) because I kind of "restart" my own function…
upvote count: 4
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80571708
linked to: http://stackoverflow.com/q/46782017
linked to: http://stackoverflow.com/q/13591970
has comment: http://stackoverflow.com/comment/80570099
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/46762941
has comment: http://stackoverflow.com/comment/80471909
favorite count: 0
has answer: http://stackoverflow.com/a/46763245
has comment: http://stackoverflow.com/comment/80471102
has comment: http://stackoverflow.com/comment/80471099
tagged with: python
has answer: http://stackoverflow.com/a/46762950
answer count: 4
has comment: http://stackoverflow.com/comment/80510417
has answer: http://stackoverflow.com/a/46764417
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80471093
has comment: http://stackoverflow.com/comment/80471008

http://stackoverflow.com/comment/80462629
has text: At this point I would probably work on python fundamentals for you https://www.learnpython.org/
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46758389
type: QuestionComment

http://stackoverflow.com/q/46787428
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41170997
type: Question
has title: python - from apache_beam.io import fileio gives error: cannot import name fileio
tagged with: apache
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46833461
has body: I want to read a csv file into a list in an apache beam application, where each element in the list is a tuple or list (don't really matter), so that I would have the csv 1,2,3 4,5,6 become [(1,2,3) , (4,5,6)] or [ [1,2,3], [4,5,6] ] I tried following the instructions in How to convert csv into a dictionary in apache beam dataflow but when I try to use from beam_utils.sources import CsvFileSource I get from beam_utils.sources import CsvFileSource Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/site-packages/beam_utils/sources.py", line 9, in &lt;module&gt; from apache_beam.io import fileio ImportError: cannot import name fileio If I try to directly import from apache_beam.io import fileio I get the same issue, however I can use both of import apache_beam.io import beam_utils without any issues. Anyone got a good idea of what the issue might be or got a good idea of how I could do this in a different way? I currently have with beam.Pipeline(options = pipeline_options) as p: csvfile = p | ReadFromText(known_args.input) so if I can turn csvfile to the desired format in another way that works well too
favorite count: 0

http://stackoverflow.com/a/46844399
has body: np.sort does not seem to support inplace sorting as far as i understand the documentation. np.ndarray.sort however does. So np.sort(lasPoints["point"]["gps_time"]) print(lasPoints) will always be unsorted. But to your problem: You could slice the list of GPS-times out of your list and use argsort to get the indices for a sorted list. These can then be used to sort your laspoints. e.g.: sorted_ind = np.argsort(list_of_gpstimes) laspoints = laspoints[sorted_ind]
accepted answer of: http://stackoverflow.com/q/46844233
answers question: http://stackoverflow.com/q/46844233
type: Answer
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/80636444
type: AcceptedAnswer

http://stackoverflow.com/comment/121559746
type: QuestionComment
comment on: http://stackoverflow.com/q/46851479
has text: For the actual question you're having refer to [python - Sort a list by multiple attributes? - Stack Overflow](https://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes). For the question in title, see [the answer below](https://stackoverflow.com/a/46851576/5267751).
score: 0
type: Comment

http://stackoverflow.com/comment/80646652
type: Comment
has text: Which container is `myfile.csv` in, `django` or `db`? Which container are you exec'ing into? `django` or `db`?
comment on: http://stackoverflow.com/q/46849539
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80706313
type: QuestionComment
type: Comment
has text: @melpomene Oh, that makes sense. Thanks.
comment on: http://stackoverflow.com/q/46879508
score: 0

http://stackoverflow.com/a/46758901
answers question: http://stackoverflow.com/q/46758663
type: Answer
downvote count: 1
score: 2
has body: You can convert a uint8 numpy array (shape M, N, 3 RGB image) to QPixmap as follows: from skimage import img_as_ubyte arr = img_as_ubyte(arr) img = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_RGB888) pixmap = QPixmap.fromImage(img)
has comment: http://stackoverflow.com/comment/80463298
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46758663
upvote count: 3

http://stackoverflow.com/comment/80558220
comment on: http://stackoverflow.com/a/46805565
has text: Thanks a lot. This answers my puzzle why it `/` didn't work on Selenium but worked on my past python scripts. I will mark your answer as the correct answer. I am sorry I do not have enough votes to upvote it.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80552801
type: Comment
score: 0
has text: Have you checked what is returned from the requests, you may need to change your user agent string to avoid the bot block.
type: QuestionComment
comment on: http://stackoverflow.com/q/46803077

http://stackoverflow.com/q/46902141
has body: I have a list like this [u'-107', u'-103', u'-109', u'-101', u'-110', u'-110', u'-110', u'-110', u'-110', u'-110', u'-105', u'-105', u'-105', u'-115', u'-110', u'-110' This list was created from parsing html with BeautifulSoup. I want to only have the numbers inside the string and the +- sign, for example: -107 for the first list value. Then I want to create a new list with these values. Like this: [-107,-103,-109. . . . . . . .] Bonus Question: Why is the u showing up? Solved Solution: The following code is what ended up working for me: odds_matrix_cleaned = [str(x) for x in odds_matrix_dirty] odds_matrix_cleaned = map(int, odds_matrix_cleaned)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80773783
type: Question
has title: Delete all characters but numbers and -+ in a list, Python 2.7
has comment: http://stackoverflow.com/comment/80750979
linked to: http://stackoverflow.com/q/22129324
answer count: 2
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/80751006
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46902187
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/46902176
tagged with: list

http://stackoverflow.com/comment/80758635
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46846295
has text: You don't need to download full nltk, If you just need `punkt` why not download just that?

http://stackoverflow.com/q/46776982
has body: I'm new to python and I'm trying to figure out the largest sequence of prime numbers from an array. I wrote a function to figure if a number is prime or not and using this I'm trying to find the largest sequence of prime numbers in an array. For example: array1 = [1,2,5,4,2,2,3,4] For this array, the largest sequence of prime numbers is 2,2,3. To figure this I tried using this approach: def primeSequence(s): l=[] k=[] j=0 for i in range(1,len(s)+1): if isPrime(s[i]): l.append(s[i]) else: break print(l) k.append(l) print(k); Basically, I went through the array and check if the number is prime. If it is, I store it in an array. Then that array I store it in another array and in the end the plan was to go through that k array and find which array is the largest. The problem is that the for loop breaks when it find the 4 (which is not prime) and I don't know how to traverse the array again from that point.. I'm not sure if I was clear enough.. Any suggestions how can I do this? Thanks a lot.
upvote count: 1
type: AnsweredQuestion
tagged with: algorithm
score: 1
has answer: http://stackoverflow.com/a/46777072
accepted answer: http://stackoverflow.com/a/46777072
type: Question
tagged with: arrays
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has title: Largest sequence of prime numbers from array

http://stackoverflow.com/q/46751028
type: UnansweredQuestion
tagged with: python
tagged with: css
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/46963554
type: Question
has answer: http://stackoverflow.com/a/46777731
has body: wanna have a script that scrapes the titles of a list of URLs, but it could be super slow if we need to wait until the whole page gets loaded. The title is the only thing I am looking for. Can we stop page loading when the title gets loaded? maybe with something like EC.title_contains.
score: 0
answer count: 2
has title: Selenium python: How to stop page loading when the head/title gets loaded?
linked to: http://stackoverflow.com/q/43734797

http://stackoverflow.com/comment/80523000
has text: Please make a sample, how your data should look like
comment on: http://stackoverflow.com/q/46787536
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80538003
has text: Is the php file setting a content-type header?
comment on: http://stackoverflow.com/q/46795467
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80748939
type: Comment
comment on: http://stackoverflow.com/a/46900952
type: AnswerComment
has text: You have to create the file at the path you provide to open().
score: 0

http://stackoverflow.com/comment/96813826
comment on: http://stackoverflow.com/a/51894355
score: 0
type: Comment
has text: Your code has also a problem. You are using the variable `points` in the `MD_detectOutliers` function which is not defined anywhere. I could not understand what `points` are because you are computing the mean of them (so I suggest that they are vectors from R^n) but you compare them with scalars: `MD[i] > up_t`? I mean `MD[i]` is a scalar, but as I know `up_t` is a vector. How should this work?
type: AnswerComment

http://stackoverflow.com/a/46878888
score: -1
has comment: http://stackoverflow.com/comment/80706124
upvote count: 0
answers question: http://stackoverflow.com/q/46878575
has body: You can use HTMLParser to read the HTML code and urllib.urlretrieve to download the URL.
type: Answer
downvote count: 1

http://stackoverflow.com/a/46906566
downvote count: 0
answers question: http://stackoverflow.com/q/46905399
type: Answer
has body: For others in future, have a look into RF docs about creating user libraries http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#id216 The name of a test library that is used when a library is imported is the same as the name of the module or class implementing it. For example, if you have a Python module MyLibrary (that is, file MyLibrary.py), it will create a library with name MyLibrary. Similarly, a Java class YourLibrary, when it is not in any package, creates a library with exactly that name. Python classes are always inside a module. If the name of a class implementing a library is the same as the name of the module, Robot Framework allows dropping the class name when importing the library. For example, class MyLib in MyLib.py file can be used as a library with just name MyLib. This also works with submodules so that if, for example, parent.MyLib module has class MyLib, importing it using just parent.MyLib works. If the module name and class name are different, libraries must be taken into use using both module and class names, such as mymodule.MyLibrary or parent.submodule.MyLib.
upvote count: 3
score: 3

http://stackoverflow.com/a/53719601
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/46797224
has comment: http://stackoverflow.com/comment/94314896
type: Answer
score: 2
has body: It seems now it is available in python notebook as well. https://github.com/jupyterlab/jupyterlab/pull/2191 If I open a python notebook in Kaggle (www.kaggle.com) and select a text, it lets me run only the highlighted part.
accepted answer of: http://stackoverflow.com/q/46797224
has comment: http://stackoverflow.com/comment/137659483
type: AcceptedAnswer

http://stackoverflow.com/comment/80527143
type: QuestionComment
comment on: http://stackoverflow.com/q/46790390
score: 1
has text: There is something wrong with your path / file-argument. Make sure the file exists in the folder you are running python from. Maybe add more details on how you call this script and from where.
type: Comment

http://stackoverflow.com/comment/80679428
score: 0
type: Comment
has text: Sure, I'll put it in question.
comment on: http://stackoverflow.com/a/46771950
type: AnswerComment

http://stackoverflow.com/a/46882770
has body: You can use db_table attribute to map your tables with your models and db_column to map columns with fields. References: Model Meta options - db_table Model Field Meta options - db_column
type: Answer
answers question: http://stackoverflow.com/q/46882674
score: 0

environment-variables
tags question: http://stackoverflow.com/q/46836319
tags question: http://stackoverflow.com/q/46849585
tags question: http://stackoverflow.com/q/46800456
tag name: environment-variables
type: Tag

http://stackoverflow.com/comment/80681107
type: AnswerComment
has text: Thing is, `reload` is exactly what I want because I want the aforementioned objects to be different. I want new code to be executed and completely new object created.
type: Comment
comment on: http://stackoverflow.com/a/46852679
score: 0

http://stackoverflow.com/q/46778621
tagged with: numpy
score: -2
has comment: http://stackoverflow.com/comment/80504222
tagged with: python-2.7
has body: I'm studying machine learning and I found this code in github, but I'm having some problems to make it work correctly, and I also do not have experience with python which is not making things much easier hahaha filhos = np.zeros( (n_filhos, n_vars) ) is returning this error: Traceback (most recent call last): File "D:\GitHub\evoman_framework\optimization_individualevolution_demo.py", line 272, in filhos = cruzamento(pop) # crossover File "D:\GitHub\evoman_framework\optimization_individualevolution_demo.py", line 171, in cruzamento filhos = np.zeros( (n_filhos, n_vars) ) TypeError: only integer scalar arrays can be converted to a scalar index ############################################################################### # EvoMan FrameWork - V1.0 2016 # # DEMO : Neuroevolution - Genetic Algorithm with perceptron neural network. # # Author: Karine Miras # # karine.smiras@gmail.com # ############################################################################### # imports framework import sys sys.path.insert(0, 'evoman') from environment import Environment from controller import Controller # imports other libs import time import numpy as np from math import fabs,sqrt import glob, os # genetic algorithm params run_mode = 'train' # train or test stateread = None # 'state_1' statesave = 'state_1' n_vars = (env.get_num_sensors()+1)*5 # perceptron #n_vars = (env.get_num_sensors()+1)*10 + 11*5 # multilayer with 10 neurons #n_vars = (env.get_num_sensors()+1)*50 + 51*5 # multilayer with 50 neurons dom_u = 1 dom_l = -1 npop = 100 gens = 30 mutacao = 0.2 last_best = 0 # crossover def cruzamento(pop): total_filhos = np.zeros((0,n_vars)) for p in range(0,pop.shape[0], 2): p1 = torneio(pop) p2 = torneio(pop) n_filhos = np.random.randint(1,3+1, 1) filhos = np.zeros( (n_filhos, n_vars) ) for f in range(0,n_filhos): cross_prop = np.random.uniform(0,1) filhos[f] = p1*cross_prop+p2*(1-cross_prop) # mutation for i in filhos[f]: if np.random.uniform(0 ,1)&lt;=mutacao: filhos[f][i] = filho…
answer count: 2
favorite count: 0
has title: how to properly use numpy.zeros in python
has comment: http://stackoverflow.com/comment/80503262
tagged with: python
possible better answer: http://stackoverflow.com/a/46778851
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46778849
has answer: http://stackoverflow.com/a/46778851
downvote count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/46778849
type: Question

http://stackoverflow.com/comment/80725714
type: QuestionComment
type: Comment
has text: Why do you think that "matplotlib must get the screen size somewhere"? This is exactly the purpose of a backend. So yes, each matplotlib backend will be able to determine the screen size or let it be determined by some method (e.g. `showMaximized()` for Qt).
comment on: http://stackoverflow.com/q/46888448
score: 0

http://stackoverflow.com/comment/80552190
comment on: http://stackoverflow.com/q/46802586
score: 0
type: Comment
type: QuestionComment
has text: @nightgaunt backtracker is a custom python module written by my coworker that I should be using.

http://stackoverflow.com/comment/80566569
type: QuestionComment
comment on: http://stackoverflow.com/q/46807838
score: 0
has text: @Him I added the code of my dags however I think my tasks are correctly assigned to the tasks thanks to the parameter dag=dag
type: Comment

http://stackoverflow.com/comment/106050081
type: Comment
has text: Don't really recommend a `While True` clause, a simple exception can cause an infinite loop.
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/46986804

http://stackoverflow.com/q/46769933
has comment: http://stackoverflow.com/comment/80486067
has comment: http://stackoverflow.com/comment/80493959
has comment: http://stackoverflow.com/comment/80488906
has title: convert a sparse matrix to dense and get the full eigenvalues
tagged with: python
has comment: http://stackoverflow.com/comment/80485356
has comment: http://stackoverflow.com/comment/80494306
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80488502
linked to: http://stackoverflow.com/q/22558215
accepted answer: http://stackoverflow.com/a/46772002
type: Question
possible better answer: http://stackoverflow.com/a/46772007
has comment: http://stackoverflow.com/comment/80488216
has comment: http://stackoverflow.com/comment/80488721
has answer: http://stackoverflow.com/a/46772007
has body: recently I'm working on a problem which requires diagonalizing a huge hermitian matrix to get all the eigenvalues. Currently I'm using Mathematica to do the job. However it is not applicable due to the limitation of memory when the matrix size approaches (2^15,2^15), where the diagonalization costs approximately 32 GBs memory. I've tried using python by importing the matrix from mathematica, import numpy as np from scipy.io import mmread from scipy.sparse import csc_matrix #importing sparse matrix to save space h = mmread("h.mtx") h = csc_matrix(h) #diagonlizing the dense one ev = np.linalg.eigvalsh(h.todense()) It works but unfortunately an order of magnitude slower than Mathematica. So, is there any other possible solutions, say, C++? I know nothing about C++ so I guess the simplest way may be importing the matrix to C++ and diagonalizing. Thanks!
has comment: http://stackoverflow.com/comment/80485513
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80489816
has comment: http://stackoverflow.com/comment/80485250
tagged with: matrix
has comment: http://stackoverflow.com/comment/80486370
has answer: http://stackoverflow.com/a/46772002

http://stackoverflow.com/comment/121249077
type: Comment
type: QuestionComment
has text: @aleksei I've the exact same question, what did you end up doing?
comment on: http://stackoverflow.com/q/46770748
score: 0

http://stackoverflow.com/comment/80693602
has text: Yes, looks like it. at the time, wasnt formatted as is now, and only visible difference was the space
type: Comment
comment on: http://stackoverflow.com/a/46865381
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80535790
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46791336
has text: There must be something wrong.... check the shape of the "duplicated removed" df and then test by hand and you would see that there are many more than 5 equal notations.... I have no idea why this is not working

http://stackoverflow.com/comment/80499798
has text: I asummed the OP is handling it. But yes. I'll change it.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46777072

http://stackoverflow.com/a/46894533
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80736855
has comment: http://stackoverflow.com/comment/80736686
has body: You need to split the lines: my_list = [] for lines in file: my_list.append(lines.split(',')) print(my_list)
accepted answer of: http://stackoverflow.com/q/46894436
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46894436
score: 1

http://stackoverflow.com/q/46879764
answer count: 2
has title: Saving "The Economist" Style in matplotlib as default in mplstyle
has body: I created "The Economist" style by modifying the example given here. However, I would like to make this style appear under plt.style.use(your_style). I am having trouble converting in the format it is required. For example, here's my code that creates "The Economist" style: import matplotlib.pyplot as plt import numpy as np x = np.random.randn(1000) y = np.sin(x) fig, ax = plt.subplots(facecolor='#CAD9E1', figsize=(12, 10)) ax.set_facecolor('#CAD9E1') ax.yaxis.grid(color='#ffffff', linewidth=2) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.tick_params(axis='y', length=0) ax.xaxis.set_ticks_position('bottom') # Lengthen the bottom x-ticks and set them to dark gray ax.tick_params(direction='in', axis='x', length=7, color='0.1') plt.scatter(x, y, color='#006767') The output is the following: I opened the default mplstyles that are available and found that I can change the face and grid lines color using the following: axes.facecolor: cad9e1 grid.color: ffffff However, I do not know how to implement the rest, for example: ax.yaxis.grid(color='#ffffff', linewidth=2) ax.spines['left'].set_visible(False) ax.tick_params(axis='y', length=0) ax.xaxis.set_ticks_position('bottom') ax.tick_params(direction='in', axis='x', length=7, color='0.1')
favorite count: 0
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/46884966
type: Question
has answer: http://stackoverflow.com/a/46884966
linked to: http://stackoverflow.com/q/29859565
possible better answer: http://stackoverflow.com/a/46884476
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46884476
score: 4

http://stackoverflow.com/a/46888308
has comment: http://stackoverflow.com/comment/80774894
type: Answer
has comment: http://stackoverflow.com/comment/80724647
has comment: http://stackoverflow.com/comment/80724511
has comment: http://stackoverflow.com/comment/80724598
downvote count: 0
has comment: http://stackoverflow.com/comment/80724724
has comment: http://stackoverflow.com/comment/80725610
has comment: http://stackoverflow.com/comment/80766714
has comment: http://stackoverflow.com/comment/80723902
has comment: http://stackoverflow.com/comment/80773802
has comment: http://stackoverflow.com/comment/80723992
accepted answer of: http://stackoverflow.com/q/46888273
score: 1
answers question: http://stackoverflow.com/q/46888273
has comment: http://stackoverflow.com/comment/80774350
upvote count: 1
has comment: http://stackoverflow.com/comment/80773754
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80725183
has body: You can try this: import re def read_data(file_name): data = open(file_name).read() keys = [filter(lambda x:bool(x), i)[0][1:-1] for i in re.findall("{(.*?)\:|(?&lt;=,\n\s)(.*?)\:", data)] values = [filter(lambda x:bool(x), i)[0][1:-1] for i in re.findall('(?&lt;=:\s)(.*?)(?=,\n)|(?&lt;=\s)(.*?)(?=})', data)] final_data = {a:b for a, b in zip(keys, values)} return final_data Output: {'Read1': 'GGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTCGTCCAGACCCCTAGC', 'Read3': 'GTCTTCAGTAGAAAATTGTTTTTTTCTTCCAAGAGGTCGGAGTCGTGAACACATCAGT', 'Read2': 'CTTTACCCGGAAGAGCGGGACGCTGCCCTGCGCGATTCCAGGCTCCCCACGGG', 'Read5': 'CGATTCCAGGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTC', 'Read4': 'TGCGAGGGAAGTGAAGTATTTGACCCTTTACCCGGAAGAGCG', 'Read6': "'Read6': 'TGACAGTAGATCTCGTCCAGACCCCTAGCTGGTACGTCTTCAGTAGAAAATTGTTTTTTTCTTCCAAGAGGTCGGAGT"} Edit: import ast def read_data(file_name): final_data = ast.literal_eval(open(file_name).read()) return final_data Edit 1: Regarding the removal of the brackets, just access the value by indexing: final_answer = {a:b[0] for a, b in answer.items()} print(final_answer) If you are having issues printing the value returned from read_data, you can try this: answer = read_data("the_file.txt") print(answer) Edit 3: def read_data(file_name): with open(file_name, "r") as document: answer = {} for line in document: line = line.split() if line: answer[line[0]] = line[1:] return {a:b[0] for a, b in answer.items()} print(read_data("sequencing_reads.txt"))
has comment: http://stackoverflow.com/comment/80773714
has comment: http://stackoverflow.com/comment/80774861
has comment: http://stackoverflow.com/comment/80724307

http://stackoverflow.com/comment/80512102
has text: What should the expected result look like?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46782871

http://stackoverflow.com/q/46843992
favorite count: 0
has answer: http://stackoverflow.com/a/46844144
accepted answer: http://stackoverflow.com/a/46844144
tagged with: python
possible better answer: http://stackoverflow.com/a/46844146
type: Question
type: AnsweredQuestion
score: -1
has body: staffs： 50 - 100 year_turnover： 0 url： http://www.chinaanigu.com how to re.findall() year_turnover: after and staffs: after
answer count: 2
downvote count: 2
has title: python re how to Extract fields use findall()?
upvote count: 1
has answer: http://stackoverflow.com/a/46844146

http://stackoverflow.com/comment/80683465
comment on: http://stackoverflow.com/q/46868000
type: Comment
type: QuestionComment
has text: The instead of making it a list-comp make it a gen-exp?
score: 0

http://stackoverflow.com/comment/80718428
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46827534
has text: also liked the article. It does go in the spirit of my own thoughts.

http://stackoverflow.com/q/46782083
type: UnansweredQuestion
has title: How to create a random list of numbers using a random.randint for loop?
has answer: http://stackoverflow.com/a/46782150
has comment: http://stackoverflow.com/comment/80510535
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/80510499
type: Question
answer count: 2
tagged with: random
tagged with: for-loop
upvote count: 0
has body: For my IT class we need to do 10 different tasks and this is the last one that I'm completely stumped on. The goal is to make a list with 20 numbers between -500 and 500. We have two lines of code to sample off of and finish this with. for i in range(10) print(i) and import random print (random.randint(0,100)) Please help me figure this out so I can get a better understanding of the code.
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80510544
tagged with: list
has answer: http://stackoverflow.com/a/46782145

http://stackoverflow.com/q/46856276
tagged with: dataframe
has title: drop non-json object rows from python dataframe column
has answer: http://stackoverflow.com/a/46856468
has comment: http://stackoverflow.com/comment/80660392
answer count: 3
has answer: http://stackoverflow.com/a/46856758
tagged with: pandas
linked to: http://stackoverflow.com/q/46858848
downvote count: 0
accepted answer: http://stackoverflow.com/a/46856679
favorite count: 0
has comment: http://stackoverflow.com/comment/80660425
upvote count: 2
linked to: http://stackoverflow.com/q/46856988
tagged with: python
tagged with: object
score: 2
type: AnsweredQuestion
has body: I have a dataframe such that the column contains both json objects and strings. I want to get rid of rows that does not contains json objects. Below is how my dataframe looks like : import pandas as pd df = pd.DataFrame({'A': ["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"a":9,"b":10,"c":11}]}) print(df) How should i remove the rows that contains only strings, so that after removing those string rows, I can apply below to this column to convert json object into separate columns of dataframe: from pandas.io.json import json_normalize df = json_normalize(df['A']) print(df)
has comment: http://stackoverflow.com/comment/80663152
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/46856679
type: Question
possible better answer: http://stackoverflow.com/a/46856468

http://stackoverflow.com/q/46827814
answer count: 1
has title: Querying a column in a data frame using a variable
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46827877
type: Question
has body: I have written a method that pulls in a data-frame rawDatabase, a list of validations 'validationLists' and a field or column name to apply the validations to in the database. The code looks like: rawDatabase = GetStandardisedField(rawDatabase,validationLists,"Status") def GetStandardisedField(rawDatabase,validationLists,field): print('Standardising ', field,' ...') my_list = validationLists[field] l1=[] print(rawDatabase.head()) for x in rawDatabase.field: print('here') choice = process.extractOne(x, my_list)[0] l1.append(choice) rawDatabase['choice']=l1 rawDatabase[field] = rawDatabase['choice'] del rawDatabase['choice'] return rawDatabase In a previous version of the code I used the actual field name, for example: for x in rawDatabase.Status: This used to work fine but to make my code reusable and simpler I rewrote it as: for x in rawDatabase.field: The code stops running 'here' and I'm wondering if Python does not allow you to use a variable to select a column in a data-frame
score: 0
tagged with: pandas

http://stackoverflow.com/q/46749573
has answer: http://stackoverflow.com/a/46749751
accepted answer: http://stackoverflow.com/a/46749751
tagged with: numpy
answer count: 1
score: 0
tagged with: pandas
tagged with: python
has body: I am trying to process a dataframe. This includes creating columns and updating their values based on the values in other columns. In this case I have a given payment_typethat I want to classify. It can fall under three categories: cash, deb_cred, gift_card. I want to add three new columns to the dataframe that are comprised of either 1's or 0's based on the given parameter I am currently able to do this, it's just really slow (multiple hours on a AWS M4 instance on a dataset of ~70k rows, ~20 columns)... Original column sample: _id Payment tender types 1 debit 2 comptant 3 visa 4 mastercard 5 tim card 6 cash 7 gift Desired output: _id Payment tender types pay_cash pay_deb_cred pay_gift 1 debit 0 1 0 2 comptant 1 0 0 3 visa 0 1 0 4 mastercard 0 1 0 5 tim card 0 0 1 6 cash 1 0 0 7 gift 0 0 1 My current code: Note: data is a dataframe (70000,20) that has been loaded prior to this snippet # For 'Payment tender types' we will use the following classes: payment_cats = ['pay_cash', 'pay_deb_cred', 'pay_gift_card'] # [0, 0, 0] would imply 'other', hence no need for a fourth category # note that certain types are just pieces of the name: e.g. master for "mastercard" and "master card" types = ['debit', 'tim', 'cash', 'visa', 'amex', 'master', 'digital', 'comptant', 'gift', 'débit'] cash_types = ['cash', 'comptant'] deb_cred_types = ['debit', 'visa', 'amex', 'master', 'digital', 'débit' 'discover', 'bit', 'mobile'] gift_card_types = ['tim','gift'] # add new features to dataframe, initializing to nan for cat in payment_cats: data[cat] = np.nan for row in data.itertuples(): # create series to hold the result per row e.g. [1, 0, 0] for `cash` cat = [0, 0, 0] index = row[0] # to string as some entries are numerical payment_type = row.paymenttendertypes.lower() if any(ct in payment_type for ct in cash_types): cat[0] = 1 if any(dbt in payment_type for dbt in deb_cred_types): cat[1] = 1 if any(gct in payment_type for gct in gift_card_types): cat[2] = 1 # add series to payment_cat da…
has title: Optimized iteration over dataframe (rows)
type: Question
type: AnsweredQuestion
tagged with: dataframe

netcdf4
tags question: http://stackoverflow.com/q/46816111
tags question: http://stackoverflow.com/q/46849934
tag name: netcdf4
type: Tag

http://stackoverflow.com/q/46803788
upvote count: 1
type: Question
has body: I am new to python, and more used to C++. I want to create a list of instances and did the following: from copy import deepcopy class C: c1="" c2="" Cs=[] C.c1="Hello" C.c2="World" Cs.append(deepcopy(C)) C.c1="Why" C.c2="this?" Cs.append(deepcopy(C)) for c in Cs: print (c.c1, c.c2) I expected the following output: Hello World Why this? but got: Why this? Why this? Why is the deep copy not working?
has title: List of class instances in python
tagged with: deep-copy
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/1680528
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46803876
tagged with: python
duplicate of: http://stackoverflow.com/q/22079916
score: 1
has comment: http://stackoverflow.com/comment/80554973
linked to: http://stackoverflow.com/q/1680528
linked to: http://stackoverflow.com/q/22079916

http://stackoverflow.com/comment/80619416
score: 0
type: QuestionComment
type: Comment
has text: Sorry. Yeah. Doing it. Was not really sure that is the complete question and whether it would help others since the answer sounded too simple.
comment on: http://stackoverflow.com/q/46835866

http://stackoverflow.com/a/46867092
accepted answer of: http://stackoverflow.com/q/46866469
score: 1
answers question: http://stackoverflow.com/q/46866469
upvote count: 1
downvote count: 0
type: AcceptedAnswer
has body: You can create a range column using np.where df['range'] = np.where(df['D'].dt.hour.between(10, 17.30), 1,\ np.where(df['D'].dt.hour.between(17.31, 20.30), 2, np.nan)) And then groupby df.groupby(['B', 'C','range'])['A', 'E'].mean().reset_index().\ .rename(columns = {'A': 'A_mean', 'E': 'E_mean'}) B C range A_mean E_mean 0 0 0 1.0 14372.0 25.0 1 0 0 2.0 14948.5 17.5
type: Answer

http://stackoverflow.com/a/46815161
score: 0
has body: Since you have written for chr in mes, you have shadowed the built-in name chr. Now, chr refers to your string, not the python function. Replace it with something like: chr(ord(mychar)+key) for mychar in mes
has comment: http://stackoverflow.com/comment/80578068
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46815115
answers question: http://stackoverflow.com/q/46815115
type: Answer
has comment: http://stackoverflow.com/comment/80577908

http://stackoverflow.com/comment/80572466
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46811800
has text: BTW pyinstaller works fine on Linux e.g. it's what Docker Compose uses.

http://stackoverflow.com/comment/80529435
has text: @cricket_007 As i said that also makes use of for loop and takes same time.
comment on: http://stackoverflow.com/q/46791139
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46749550
tagged with: flask-sqlalchemy
answer count: 1
favorite count: 0
has body: Using SQLAlchemy I have defined my own TypeDecorator for storing pandas DataFrames in a databased encoded as JSON string. class db_JsonEncodedDataFrameWithTimezone(db.TypeDecorator): impl = db.Text def process_bind_param(self, value, dialect): if value is not None and isinstance(value, pd.DataFrame): timezone = value.index.tz.zone df_json = value.to_json(orient="index") data = {'timezone': timezone, 'df': df_json, 'index_name': value.index.name} value = json.dumps(data) return value def process_result_value(self, value, dialect): if value is not None: data = json.loads(value) df = pd.read_json(data['df'], orient="index") df.index = df.index.tz_localize('UTC') df.index = df.index.tz_convert(data['timezone']) df.index.name = data['index_name'] value = df return value This works fine for first time database save, and loading is fine too. The problem comes when I augment the value, i.e. change the DataFrame and try to alter the database. When I invoke db.session.add(entity) db.session.commit() I get a traceback which points to comparing values being the problem: x == y ValueError: Can only compare identically-labeled DataFrame Objects. So I suspect my problem has something to do with coercing comparators. I have tried three things, all have failed and I really don't know what to do next: #1st failed solution attempt inserting coerce_to_is_types = (pd.DataFrame,) #2nd failed solution attempt inserting def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value) #3rd failed solution attempt class comparator_factory(db.Text.comparator_factory): def __eq__(self, other): try: value = (self == other).all().all() except ValueError: value = False return value
has title: SQLAlchemy TypeDecorators and Comparison Errors
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/46751960
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/46751960

http://stackoverflow.com/a/70003461
score: 0
type: Answer
has body: Stats For Nerds are retrieved by the player via an internal Youtube API (InnerTube). URL: https://www.youtube.com/youtubei/v1/player?key=[DERIVATED_API_KEY] Play with web developper to get the derivated API key and disable CORS via "--web-security" to allow cross domain ajax calls. for Loudness info : function getLoudness(videoId) { $.ajax({ type: "POST", url: "https://www.youtube.com/youtubei/v1/player?key="+ytApiKeyV1, contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({ "videoId": videoId, "context": { "client": { "clientName": "WEB_EMBEDDED_PLAYER", "clientVersion": "1.20211110.01.01" }, "thirdParty": { "embedUrl": "https://xxx.xxxxx.tld/" } } }), success: function(response) { if(response.playerConfig.audioConfig) { setLoudness(response.playerConfig.audioConfig); } } }) }
answers question: http://stackoverflow.com/q/46819958

http://stackoverflow.com/comment/112028960
score: 0
type: Comment
has text: From what I understood, in ´random´ the model is just evaluating the metric for each feature and then pick one randomly (with probabilities based on the metric). This can be seen in the 3rd plot on the left. The distribution is very similar to the gini score. (on 1000 model fitted, it has chosen the feature 12 for the first split around 300 times which is quite similar to the gini score of the proline of 38%)
comment on: http://stackoverflow.com/a/46759065
type: AnswerComment

http://stackoverflow.com/a/46868996
downvote count: 0
has comment: http://stackoverflow.com/comment/80685254
has comment: http://stackoverflow.com/comment/80685165
has comment: http://stackoverflow.com/comment/80701280
has comment: http://stackoverflow.com/comment/80685429
type: Answer
accepted answer of: http://stackoverflow.com/q/46868855
upvote count: 6
answers question: http://stackoverflow.com/q/46868855
has comment: http://stackoverflow.com/comment/80685219
score: 6
has comment: http://stackoverflow.com/comment/80701227
has comment: http://stackoverflow.com/comment/80701683
has comment: http://stackoverflow.com/comment/80697671
has comment: http://stackoverflow.com/comment/80699372
has body: Here's one way, provided you have a small dictionary/min and max values, this may be more efficient, you work around the negative index by adding the array min: In [11]: indexer = np.array([d.get(i, -1) for i in range(a.min(), a.max() + 1)]) In [12]: indexer[(a - a.min())] Out[12]: array([[4, 1, 3, 0], [2, 0, 2, 3], [1, 4, 3, 3]]) Note: This moves the for loop to the lookup table, but if this is significantly smaller than the actual array this could be a lot faster.
type: AcceptedAnswer

http://stackoverflow.com/comment/80555031
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46803814
type: AnswerComment
has text: Is your domain is set in `Allowed Hosts` ?

http://stackoverflow.com/comment/80490820
comment on: http://stackoverflow.com/a/46772062
type: AnswerComment
has text: Yes, the last output is what I am expecting
type: Comment
score: 0

http://stackoverflow.com/comment/80520195
has text: True, this is though just an example. What I am asking is the iteration process. I will update the condition to make a bit more sense
comment on: http://stackoverflow.com/q/46786868
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46801905
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/46792424
type: Answer
has comment: http://stackoverflow.com/comment/80562428
upvote count: 4
has body: You could try Anaconda Fusion (also the video here), which let's you use Python inside of Excel. This could possibly work since you can link figures/data elements between Excel and PowerPoint (but special restrictions might apply when the figure is created via Python rather than standard Excel). Anaconda Fusion is free to try for a couple of months. Another solution would be to use the Jupyter Notebook to create your presentation instead of PowerPoint. Go to View -&gt; Cell Toolbar -&gt; Slideshowand you can choose which code cells should become slides. A third approach would be to create an animation of the figure as the data frame changes and then include the animation (GIF or video) in PowerPoint.

http://stackoverflow.com/comment/80737225
type: AnswerComment
type: Comment
has text: That doesn't help me I am giving the key to the validator, but it's it doesn't match the schema so it doesn't drop it - it's a known field
comment on: http://stackoverflow.com/a/46894253
score: 0

http://stackoverflow.com/a/46768818
accepted answer of: http://stackoverflow.com/q/46768777
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46768777
type: Answer
score: 1
upvote count: 1
has body: Use merge: df = pd.merge(df1, df2, how='left') print (df) index type blah 0 1 0 abc 1 2 0 abc 2 3 2 ghi 3 4 1 def If want add only one column faster is map: df1['blah'] = df1['type'].map(df2.set_index('type')['blah']) print (df1) index type blah 0 1 0 abc 1 2 0 abc 2 3 2 ghi 3 4 1 def

http://stackoverflow.com/q/46835197
has comment: http://stackoverflow.com/comment/129480002
accepted answer: http://stackoverflow.com/a/46835352
tagged with: python
upvote count: 7
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80618102
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46835570
tagged with: list
has answer: http://stackoverflow.com/a/46835570
score: 7
type: Question
linked to: http://stackoverflow.com/q/2612802
downvote count: 0
has answer: http://stackoverflow.com/a/46835352
has comment: http://stackoverflow.com/comment/115027584
linked to: http://stackoverflow.com/q/240178
has title: List of dictionary stores only last appended value in every iteration
has body: I have this list of dictionary: MylistOfdict = [ {'Word': 'surveillance', 'Word No': 1}, {'Word': 'equivocal', 'Word No': 2}] I want to create a new list of dictionary (word_db2) that has 3 dictionaries for each dictionary in MylistOfdict. In addition to key and values of MylistOfdict, each of those dictionary should have 'Card Type' key with value Type 1, Type 2, Type 3 and 'Card Key' key with incremental value Code: word_db2 = [] key = 1 for i in MylistOfdict: for j in range(1, 4): i['Card Type'] = 'Type ' + str(j) i['Card Key'] = key print(i) word_db2.append(i) key += 1 Output: {'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 1', 'Card Key': 1} {'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 2', 'Card Key': 2} {'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3} {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 1', 'Card Key': 4} {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 2', 'Card Key': 5} {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6} This output is correct, but word_db2 stores only last appended value in every iteration: [{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3}, {'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3}, {'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3}, {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6}, {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6}, {'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6}]
answer count: 4
has answer: http://stackoverflow.com/a/46835471
favorite count: 0
has answer: http://stackoverflow.com/a/46835315

http://stackoverflow.com/a/46824375
answers question: http://stackoverflow.com/q/46822744
upvote count: 1
has body: Download the geckodriver and Drag and Drop the geckodriver.exe file to the project root folder. In this way, there is no need of adding the geckodriver path in your code and again try to execute the code. No error will come
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/46749916
has comment: http://stackoverflow.com/comment/80445903
has comment: http://stackoverflow.com/comment/80445982
has comment: http://stackoverflow.com/comment/80446004
upvote count: 2
has comment: http://stackoverflow.com/comment/80446077
type: Answer
has comment: http://stackoverflow.com/comment/80454492
answers question: http://stackoverflow.com/q/46749867
has comment: http://stackoverflow.com/comment/80446310
has comment: http://stackoverflow.com/comment/80445932
has body: You probably need to have empty __init__.py file in the same directory to mark directory as a module
downvote count: 0
has comment: http://stackoverflow.com/comment/80445972
score: 2

http://stackoverflow.com/q/46772698
has comment: http://stackoverflow.com/comment/80491251
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
tagged with: python
tagged with: regex
has body: I have below string, I am able to grab the 'text' what I wanted to (text is warped between pattern). code is give below, val1 = '[{&amp;quot;vmdId&amp;quot;:&amp;quot;Text1&amp;quot;,&amp;quot;vmdVersion&amp;quot;:&amp;quot;text2&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text3&amp;quot;},{&amp;quot;vmId&amp;quot;:&amp;quot;text4&amp;quot;,&amp;quot;vmVersion&amp;quot;:&amp;quot;text5&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text6&amp;quot;}]' temp = val1.split(',') list_len = len(temp) for i in range(0, list_len): var = temp[i] found = re.findall(r':&amp;quot;([^(]*)\&amp;quot\;', var) print ''.join(found) I would like to replace values (Text1, text2, tex3, etc) with new values provided by user / or by reading from another XML. (Text1, tex2 .. are is totally random and alphanumeric data. below some details Text1 = somename text2 = alphanumatic value text3 = somename Text4 = somename text5 = alphanumatic value text6 = somename anstring = [{&amp;quot;vmdId&amp;quot;:&amp;quot;newText1&amp;quot;,&amp;quot;vmdVersion&amp;quot;:&amp;quot;newtext2&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;newtext3&amp;quot;},{&amp;quot;vmId&amp;quot;:&amp;quot;newtext4&amp;quot;,&amp;quot;vmVersion&amp;quot;:&amp;quot;newtext5&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;newtext6&amp;quot;}] I decided to go with replace() but later realize data is not constant. hence seeking for help again. Appreciate your response. Any help would be appreciated. Also, if let me know if I can improve the way i am grabing the value right now, as i new with regex.
accepted answer: http://stackoverflow.com/a/46772919
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80491201
upvote count: 2
has comment: http://stackoverflow.com/comment/80515410
has comment: http://stackoverflow.com/comment/80494278
type: Question
has title: python to search and update string with regex
has comment: http://stackoverflow.com/comment/80491184
has comment: http://stackoverflow.com/comment/80494417
has comment: http://stackoverflow.com/comment/80510744
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46772919

http://stackoverflow.com/comment/80528309
type: Comment
has text: Use `[]` or `()` instead of `{}` for list or tuple definition, correspondingly
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46790942

http://stackoverflow.com/comment/80771226
type: Comment
comment on: http://stackoverflow.com/a/46903864
type: AnswerComment
has text: I will be sure to try this. Are there any resources you know of that have more information on Action Modules in Ansible 2.X? I can only find information pre-2.0. Thanks for the help!
score: 0

http://stackoverflow.com/comment/80635938
comment on: http://stackoverflow.com/a/46843210
has text: I think the rest of the format is same as always HH:MM:SS right? Format issue is only with month, day and year I guess. I dont know much other than that
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47472416
has body: Having experimented with both approaches over the last couple of weeks I have settled on the first option: Adding the Anaconda binary path to the PATH variable in user .bashrc files. I have found the benefits of this method to be: Regardless of whether the Anaconda activate script is sourced in the user's .bashrc, when the user switches to one of their virtual environments and then runs source deactivate to deactivate the current environment they will always end up outside of the Anaconda environment. In this case, unless the Anaconda binary path has also been explicitly added to their PATH variable the deactivate script will remove the Ansible binary path from the PATH variable. The Anaconda activate script performs a bunch of actions which may be an unnecessary overhead when performing non-Python related actions in ones shell, if it is sourced every time a new shell is started. If one sets the Anaconda binaries to be in their PATH variable then it's simple enough to run source activate to enable the "root" Anaconda environment. (With either solution, something similar has to be done anyway if one is commonly making use of virtual environments.)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46887939
score: 0
accepted answer of: http://stackoverflow.com/q/46887939
type: Answer

http://stackoverflow.com/q/46812430
tagged with: input
tagged with: python
has body: I've got this little guessing-game #Guessing-Game.py import random random.seed() randomnumber = random.randint(1,10) def guess(number): while number!=randomnumber: number = int(input("Guess: ")) if number &lt; randomnumber: print("to low") else: print("to high") else: print("correct, it's", number) and I would like it to be solved by another python script. Something like #Guessing-Script import Guessing-Game for n in range(1,11): Guessing-Game.guess(n) but obviuosly this dont work because it's asking for an input. How to solve my problem? Thanks a lot
type: UnansweredQuestion
type: Question
tagged with: automation
has comment: http://stackoverflow.com/comment/80572183
score: 0
has answer: http://stackoverflow.com/a/46812585
answer count: 1
has title: automate input with python in another python file

http://stackoverflow.com/q/46874336
type: AnsweredQuestion
has title: Get pgrep to determine length pid has been running
has answer: http://stackoverflow.com/a/46874486
has body: I stubbed out some code to outline what Im trying to do. I just cant seem to get the syntax correct, can someone help? def calc_execution(): import subprocess #get the proc id of detectmotion; need help converting into subprocess detectmotion_file_pid = subprocess.call(pgrep -f "detectmotion.py") if detectmotion_file_pid: #determine how long pid has been running; note this seems to be incorrect len_run_time=subprocess.call(ps -o etime= -p detectmotion_file_pid) print len_run_time My problem is getting the syntax for var detectmotion_file_pid and len_run_time to work correctly. Can someone please help? Thanks
type: Question
has comment: http://stackoverflow.com/comment/80695694
answer count: 1
score: 0
tagged with: python
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/46874486

http://stackoverflow.com/a/48839789
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46905254
score: 1
upvote count: 1
has body: Given some time has past, I assume it is appropriate to post (one potential) solution, in case people find this in the future: from z3 import * def get_decoded(target): """ Helper function to "decode" a target string using Z3 """ # # We create a Z3 array for the contents of the string (this saves # needing have multiple copies of the "s[i]" variables. # # However, this could be less efficient, but this isn't a concern for this # puzzle # string = Array("string", BitVecSort(32), BitVecSort(32)) # # We save a copy of the string as the "initial" string, as we need to # interrogate the string _before_ the updates are made # initial_string = string # # Create a Z3 solver # s = Solver() # # We now iterate over the length of the "target" string, and construct the # encoding as per the CTF instance # for idx in range(len(target)): # # Extract the single character at "idx" from the target string # single_c = target[idx] # # Find its ASCII value # ord_val = ord(single_c) # # Generate the corresponding Z3 constant # ord_const = BitVecVal(ord_val, 32) # # Generate the cell position as a Z3 constant # cell_pos = BitVecVal(idx, 32) # # Calculate the non-conditional part of the update # add_rem = string[cell_pos] + SRem(string[cell_pos], 10) # # Calculate the conditional part of the update using a Z3 If # to_store = If(add_rem &gt; 123, -100 - add_rem, add_rem) # # Update the string with our calculated value # string = Store(string, idx, to_store) # # Assert that our calculated position is equal to the input value # s.add(string[cell_pos] == BitVecVal(ord_val, 32)) # # Check the SMT instance and obtain the model # assert s.check() == sat model = s.model() # # We now interrogate the model to find out what the "original" string was # output = [] # # Output string is the same length as the input string # for idx in range(len(target)): # # As before, calculate the cell position # cell_pos = BitVecVal(idx, 32) # # Extract the value for the index in the string # model_val = model.eval(i…

http://stackoverflow.com/a/46813947
type: Answer
accepted answer of: http://stackoverflow.com/q/46813689
answers question: http://stackoverflow.com/q/46813689
has body: You can use math.isnan to check if a value is nan and skip it. Alternatively, you can also replace nan with zero or something else and then apply your function on it. It really depends on what you want to achieve. A simple example: import math test_variable = math.nan if math.isnan(test_variable): print("it is a nan value") Just incorporate this logic into your code as you deem fit.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/46751140
score: 5
has title: running librosa & numba on raspberry pi 3
upvote count: 5
downvote count: 0
tagged with: librosa
tagged with: raspberry-pi3
favorite count: 0
has body: I am trying to run librosa on my raspberry pi 3. After hours of searching through the internet I was finally able to install it but it still throws an error when I try to import it. First, I had problems to install the dependency llvmlite. I finally installed it with the following code: conda install -c numba llvmlite. I use python 3.4 build with miniconda. After llvmlite was installed I was able to install librosa with pip (not possible with conda) pi@raspberrypi:~ $ pip install librosa Collecting librosa Using cached https://www.piwheels.hostedpi.com/simple/librosa/librosa- 0.5.1-py3-none-any.whl Requirement already satisfied: resampy&gt;=0.1.2 in ./miniconda3/lib/python3.4/site-packages (from librosa) Requirement already satisfied: scipy&gt;=0.13.0 in ... Installing collected packages: librosa Successfully installed librosa-0.5.1 Apparently librosa is installed. pi@raspberrypi:~ $ pip list DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format= (legacy|columns) in your pip.conf under the [list] section) to disable this warning. anaconda-client (1.0.2) audioread (2.1.5) awscli (1.11.170) boto3 (1.4.7) botocore (1.7.28) clyent (0.4.0) colorama (0.3.7) conda (3.16.0) conda-env (2.4.2) Cython (0.27.1) decorator (4.1.2) docutils (0.14) jmespath (0.9.3) joblib (0.11) librosa (0.5.1) llvmlite (0.7.0.dev0+21.gcda19bd.dirty) mock (2.0.0) numba (0.35.0) numpy (1.13.3) pbr (3.1.1) Pillow (2.9.0) pip (9.0.1) protobuf (3.4.0) pyasn1 (0.3.7) PyAudio (0.2.11) pycosat (0.6.1) pycrypto (2.6.1) python-dateutil (2.6.1) pytz (2015.4) PyYAML (3.12) requests (2.7.0) resampy (0.2.0) rsa (3.4.2) s3transfer (0.1.11) scikit-learn (0.18.2) scipy (0.19.1) setuptools (18.1) six (1.11.0) tensorflow (1.1.0) Werkzeug (0.12.2) wheel (0.30.0) Trying to import librosa throws the following error though: pi@raspberrypi:~ $ python Python 3.4.3 |Continuum Analytics, Inc.| (default, Aug 21 2015, 00:53:08) [GCC 4.6.3] on linux Type…
possible better answer: http://stackoverflow.com/a/50250155
has answer: http://stackoverflow.com/a/61628219
answer count: 5
tagged with: numba
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48244595
has answer: http://stackoverflow.com/a/64517963
has answer: http://stackoverflow.com/a/46840976
accepted answer: http://stackoverflow.com/a/46840976
type: Question
tagged with: raspbian
has answer: http://stackoverflow.com/a/50250155

http://stackoverflow.com/comment/80616340
comment on: http://stackoverflow.com/q/46833670
has text: @Bharathshetty, Currently 100 rows, but in the future could be N rows as our processes grow
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80619743
score: 2
has text: replace `%d` with `%s`
comment on: http://stackoverflow.com/q/46836086
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81347795
type: AnswerComment
comment on: http://stackoverflow.com/a/46876493
type: Comment
has text: @Brooke_W If the answer solved your problem you should accept the answer
score: 0

http://stackoverflow.com/a/46815653
answers question: http://stackoverflow.com/q/46814724
has body: This date converter expects a regular string, which in Py3 is unicode. But loadtxt loads the text as bytestrings: In [12]: mdates.strpdate2num('%Y-%m-%d')(b'1999-01-31') --------------------------------------------------------------------------- .... TypeError: strptime() argument 0 must be str, not &lt;class 'bytes'&gt; Modifying the converter to decode the bytestring should take care of the issue: In [13]: fn = lambda astr: mdates.strpdate2num('%Y-%m-%d')(astr.decode()) In [14]: fn(b'1999-01-01') Out[14]: 729755.0 testing in loadtxt: In [15]: txt=b"""1999-01-01 ...: 2000-03-03 ...: 2015-12-12 ...: """ In [16]: np.loadtxt(txt.splitlines(), converters={0:fn}) Out[16]: array([ 729755., 730182., 735944.])
has comment: http://stackoverflow.com/comment/80580577
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46814724
upvote count: 2
has comment: http://stackoverflow.com/comment/93985721
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46832127
score: 0
has title: Python can't decode a character set
answer count: 1
has answer: http://stackoverflow.com/a/46832462
accepted answer: http://stackoverflow.com/a/46832462
tagged with: python
type: AnsweredQuestion
tagged with: character-encoding
type: Question
has body: I've been using a program to process tick data. Recently it stopped working and crashed as soon as it starts processing the file. It seems that something has changed with how the vendor renders the data. So let's say I simply run: with open("N:\\2017\\2017-09-28 Daily.CAP") as f: i = 0 while True: c = f.read(1) I get this error: Traceback (most recent call last): File "C:/Users/b.karjoo/Documents/PycharmProjects/untitled1/test.py", line 4, in &lt;module&gt; c = f.read(1) File "C:\Users\b.karjoo\py3_virt_env\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 1799: character maps to &lt;undefined&gt; Any suggestions?

http://stackoverflow.com/q/46793033
answer count: 4
has comment: http://stackoverflow.com/comment/80533247
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46793107
possible better answer: http://stackoverflow.com/a/46793164
has comment: http://stackoverflow.com/comment/80533182
has answer: http://stackoverflow.com/a/46793164
favorite count: 0
has comment: http://stackoverflow.com/comment/80533155
type: Question
has comment: http://stackoverflow.com/comment/80532699
has comment: http://stackoverflow.com/comment/80533152
tagged with: python
tagged with: dictionary
has title: Pythonic way to check empty dictionary and empty values
has comment: http://stackoverflow.com/comment/80533405
has answer: http://stackoverflow.com/a/46802648
has comment: http://stackoverflow.com/comment/80532697
has comment: http://stackoverflow.com/comment/80532958
upvote count: 7
has comment: http://stackoverflow.com/comment/80532754
downvote count: 1
has comment: http://stackoverflow.com/comment/80533027
has comment: http://stackoverflow.com/comment/80533494
has body: I am using these kind of dictionaries, they can be or totally empty like collection_a or contain a single one level nested dictionary which might be empty. It wont have more levels. collection_a = {} collection_b = {"test": {}} print is_empty(collection_a) print is_empty(collection_b) def is_empty(collection): return not all(collection.values()) or def is_empty(collection): return not bool(collection.values()) Isnt there an unique way to check if a or b have values? You can check all(collection_b.values()) but that wont work for collection_a where it will return True You can also check bool(collection_a.values()) but that wont work for collection_b where it will return True... Isnt there an unique way to include both cases?
has comment: http://stackoverflow.com/comment/80533283
has comment: http://stackoverflow.com/comment/80532988
has answer: http://stackoverflow.com/a/46793617
has comment: http://stackoverflow.com/comment/80533725
score: 6
has answer: http://stackoverflow.com/a/46793107

http://stackoverflow.com/comment/80565735
comment on: http://stackoverflow.com/a/46808413
has text: Had to change it to this but did get a big bump in speed:out = [] for i in range(len(counts)): out += list(counts[i] * chr(i + 97))
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80602043
has text: @JonClements The base url is set correctly, if I take it and append the relative href manually it works. I'm using `start_urls`rather than `start_requests`. But, I don't think that the function is working correctly - see the update for what happens when I run it in idle?
comment on: http://stackoverflow.com/q/46804324
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/104120658
comment on: http://stackoverflow.com/a/46961512
type: Comment
has text: That it is. Changed batch size to -1 from a fixed size (2000), of input and label placeholders and it's fixed.
score: 0
type: AnswerComment

http://stackoverflow.com/q/46789979
has title: How can I manipulate shapes (colors) in PowerPoint using Python and win32com.client?
tagged with: powerpoint
type: Question
tagged with: win32com
has answer: http://stackoverflow.com/a/46851195
answer count: 1
downvote count: 0
has body: As I've made slight progress with the problem at hand since i posted this question, I've found it necessary to split it in two parts to maintain clarity. How can I manipulate shape colors in PowerPoint using Python and win32com.client? How can I inspect com objects in Python using dir()? 1. Manipulate shape colors in PowerPoint using Python There are some examples on how to edit PowerPoint slides using the pptx library here. However, I find it much easier to manipulate an active PowerPoint presentation using win32com.client as described here. Using an example from Microsoft Developer Network I've found that I can easily replicate parts of the functionality of this VBA snippet... With ActivePresentation.Slides(1).Shapes(1) With .TextFrame.TextRange.Font .Size = 48 .Name = "Palatino" .Bold = True .Color.RGB = RGB(255, 127, 255) End With End With ...with this Python snippet: import win32com.client Application = win32com.client.Dispatch("PowerPoint.Application") Presentation = Application.Activepresentation slidenr = Presentation.Slides.Count slide = Presentation.slides(slidenr) shape1 = slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=100,Width=100,Height=100) shape1.TextFrame.TextRange.Text='Hello, world' #Manipulate font size, name and boldness shape1.TextFrame.TextRange.Font.Size=20 shape1.TextFrame.TextRange.Characters(1, 4).Font.Name = "Times New Roman" shape1.TextFrame.TextRange.Font.Bold=True Here I'm able to manipulate font size and name. I can also change the orientation of the textbox by changing Orientation=0x1 to Orientation=0x5 in shape1 = slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=100,Width=100,Height=100). What seems impossible though, is editing the box or font color. This does not work: shape1.TextFrame.TextRange.Font.Color.RGB = RGB(255, 127, 255) Error message: I had high hopes to fix this by importing some RGB functionality following the information on pypi.python.org But I'm having trouble here as well with pip install colour: By now …
favorite count: 0
accepted answer: http://stackoverflow.com/a/46851195
tagged with: python
linked to: http://stackoverflow.com/q/27370768
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/a/46864342
downvote count: 0
score: 3
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/46862704
answers question: http://stackoverflow.com/q/46862704
has body: Parameters must be separated by commas. See http://openpyxl.readthedocs.io/en/2.4/usage.html#using-formulae

http://stackoverflow.com/q/46833364
tagged with: python-2.7
has answer: http://stackoverflow.com/a/46839642
has title: How to store a pointer in a custom embedded Python object
answer count: 1
has comment: http://stackoverflow.com/comment/80617433
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80618740
has comment: http://stackoverflow.com/comment/80618691
has comment: http://stackoverflow.com/comment/80618011
has comment: http://stackoverflow.com/comment/80616169
has comment: http://stackoverflow.com/comment/80617885
type: Question
upvote count: 2
has body: I have created a custom Python type in C as per the tutorial https://docs.python.org/2.7/extending/newtypes.html#the-basics. In my C I receive a pointer to a struct, I want to be able to get and set the values in the struct from Python without taking a copy of it. I.e. a = myObject.x() # gets the x value in the struct. or myObject.x(255) # sets the x value in the struct. However I cannot see how to store the pointer in the python object. My current object definition is currently just the basic object implementation from the python website. typedef struct { PyObject_HEAD myStruct *s; } KeyObject; static PyTypeObject KeyType = { PyVarObject_HEAD_INIT(NULL, 0) "ckb.Key", /* tp_name */ sizeof(KeyObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Key objects", /* tp_doc */ }; static PyMethodDef key_methods[] = { {NULL} /* Sentinel */ };
tagged with: http://stackoverflow.com/tag/c
tagged with: pointers

http://stackoverflow.com/a/46884882
answers question: http://stackoverflow.com/q/46884402
upvote count: 1
type: Answer
has body: One interesting thing to do is to simply insert a space before a capital letter. For example: &gt;&gt;&gt; re.sub('(?=[A-Z])', ' ', data[0]) ' Total Amt' However notice that a space will be inserted at the beginning. For that you can just strip the string ... &gt;&gt;&gt; re.sub('(?=[A-Z])', ' ', data[0]).strip() 'Total Amt' The ?= does a "non capturing version" of the match and hence this is possible ... For applying the above scheme to all data, use list comprehension like everyone else ... &gt;&gt;&gt; [re.sub('(?=[A-Z])', ' ', d).strip() for d in data] ['Total Amt', 'Program Services Amt', 'Desc'] The advantage of this is that you will not have to check whether the return value is a None or not. This checking sometimes gets annoying when we use regex ... &gt;&gt;&gt; re.sub('(?=[A-Z])', ' ', 'dljlksdjf').strip() 'dljlksdjf'
downvote count: 0
score: 1

http://stackoverflow.com/comment/80524860
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46788960
has text: This is my output Welcome to Trustees Investment Bank Compound Interest Calculator Interest is calculated at 3.15% per annum Enter initial deposit above £1000? jj Enter initial deposit above £1000? hgh Enter initial deposit above £1000? 500 Not valid amount, please enter deposit above £1000 500 1 515.75 2 532.00 3 548.75 4 566.04 5 583.87 6 602.26 7 621.23 8 640.80
score: 0

http://stackoverflow.com/comment/80703199
score: 0
type: AnswerComment
has text: What about `x = list(zip(*T_OLD.items()))`?
type: Comment
comment on: http://stackoverflow.com/a/46797395

list
tags question: http://stackoverflow.com/q/46800055
type: Tag
tags question: http://stackoverflow.com/q/46895463
tags question: http://stackoverflow.com/q/46853662
tags question: http://stackoverflow.com/q/46903438
tags question: http://stackoverflow.com/q/46837040
tags question: http://stackoverflow.com/q/46768733
tags question: http://stackoverflow.com/q/46874343
tags question: http://stackoverflow.com/q/46856642
tags question: http://stackoverflow.com/q/46897270
tags question: http://stackoverflow.com/q/46859181
tags question: http://stackoverflow.com/q/46878117
tags question: http://stackoverflow.com/q/46756686
tags question: http://stackoverflow.com/q/46831228
tags question: http://stackoverflow.com/q/46875023
tags question: http://stackoverflow.com/q/46757906
tags question: http://stackoverflow.com/q/46862450
tags question: http://stackoverflow.com/q/46770574
tags question: http://stackoverflow.com/q/46901975
tags question: http://stackoverflow.com/q/46782083
tags question: http://stackoverflow.com/q/46751527
tags question: http://stackoverflow.com/q/46902226
tags question: http://stackoverflow.com/q/46820909
tags question: http://stackoverflow.com/q/46856519
tags question: http://stackoverflow.com/q/46869275
tags question: http://stackoverflow.com/q/46863866
tags question: http://stackoverflow.com/q/46823540
tags question: http://stackoverflow.com/q/46881270
tags question: http://stackoverflow.com/q/46859770
tags question: http://stackoverflow.com/q/46881246
tags question: http://stackoverflow.com/q/46751249
tags question: http://stackoverflow.com/q/46814477
tags question: http://stackoverflow.com/q/46830351
tags question: http://stackoverflow.com/q/46862018
tags question: http://stackoverflow.com/q/46878559
tags question: http://stackoverflow.com/q/46851479
tags question: http://stackoverflow.com/q/46819239
tags question: http://stackoverflow.com/q/46769257
tags question: http://stackoverflow.com/q/46853754
tags question: http://stackoverflow.com/q/46870075
tags question: http://stackoverflow.com/q/46869685
tags question: http://stackoverflow.com/q/46803997
tags question: http://stackoverflow.com/q/46864899
tags question: http://stackoverflow.com/q/46864259
tags question: http://stackoverflow.com/q/46797134
tags question: http://stackoverflow.com/q/46777086
tags question: http://stackoverflow.com/q/46838639
tags question: http://stackoverflow.com/q/46852711
tags question: http://stackoverflow.com/q/46885789
tags question: http://stackoverflow.com/q/46812748
tags question: http://stackoverflow.com/q/46794141
tags question: http://stackoverflow.com/q/46842412
tags question: http://stackoverflow.com/q/46770748
tags question: http://stackoverflow.com/q/46765425
tags question: http://stackoverflow.com/q/46902141
tags question: http://stackoverflow.com/q/46830943
tags question: http://stackoverflow.com/q/46872550
tag name: list
tags question: http://stackoverflow.com/q/46903638
tags question: http://stackoverflow.com/q/46820714
tags question: http://stackoverflow.com/q/46852156
tags question: http://stackoverflow.com/q/46795665
tags question: http://stackoverflow.com/q/46779821
tags question: http://stackoverflow.com/q/46857500
tags question: http://stackoverflow.com/q/46761490
tags question: http://stackoverflow.com/q/46752026
tags question: http://stackoverflow.com/q/46787536
tags question: http://stackoverflow.com/q/46824949
tags question: http://stackoverflow.com/q/46749172
tags question: http://stackoverflow.com/q/46829577
tags question: http://stackoverflow.com/q/46777637
tags question: http://stackoverflow.com/q/46819586
tags question: http://stackoverflow.com/q/46771858
tags question: http://stackoverflow.com/q/46852081
tags question: http://stackoverflow.com/q/46862148
tags question: http://stackoverflow.com/q/46824610
tags question: http://stackoverflow.com/q/46885741
tags question: http://stackoverflow.com/q/46758628
tags question: http://stackoverflow.com/q/46798399
tags question: http://stackoverflow.com/q/46757190

http://stackoverflow.com/q/46877090
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80701241
has body: How to import my new custom password hasher ? It just gives me this error : NameError at /accounts/register/ name 'Honeyword' is not defined hashers.py : class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = 36000 digest = hashlib.sha256 def salt(self): salt = get_random_string() while Honeyword.objects.filter(salt=salt).exists(): salt = get_random_string() return salt -----EDITED----- import for hashers.py : from __future__ import unicode_literals import base64 import binascii import hashlib import importlib import passlib import hashlib from collections import OrderedDict from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.db import models from django.contrib.auth.hashers import BasePasswordHasher, PBKDF2PasswordHasher from django.utils.crypto import ( constant_time_compare, get_random_string, pbkdf2, ) from django.utils.encoding import force_bytes, force_text from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _ i just add the import based on the https://docs.djangoproject.com/en/1.11/_modules/django/contrib/auth/hashers/ . kinda confused on how to import the my new hasher. i already create the app(honeywordHasher) and install it in INSTALLED_APP and also in the PASSWORD_HASHERS in settings.py
has comment: http://stackoverflow.com/comment/80701502
downvote count: 1
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/46877740
has comment: http://stackoverflow.com/comment/80701700
has comment: http://stackoverflow.com/comment/80701275
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80701347
has comment: http://stackoverflow.com/comment/80701117
has title: Django: NameError at /accounts/register/ name 'Honeyword' is not defined
has comment: http://stackoverflow.com/comment/80701621
favorite count: 0
tagged with: hash
accepted answer: http://stackoverflow.com/a/46877740
tagged with: django
upvote count: 1
tagged with: python
tagged with: passwords

http://stackoverflow.com/comment/80784595
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46838428
score: 0
has text: hi, in my function i dont do it . I mean when I apply the filter in the same view. Also, I've tried adding it with a conditional : if 'project' in 'groupby': but as the same result.

http://stackoverflow.com/q/46751474
answer count: 2
tagged with: python-3.5
has answer: http://stackoverflow.com/a/46751666
has answer: http://stackoverflow.com/a/46751731
accepted answer: http://stackoverflow.com/a/46751731
favorite count: 0
possible better answer: http://stackoverflow.com/a/46751666
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: The number of ways to find unique numbers that sum to a number in Python
downvote count: 1
type: Question
score: -1
has body: This is the description of the problem: There is a list of integers, sequence. There is another integer argument, target. The objective is to return the number of unique ways target can be expressed as the sum of four distinct numbers in sequence. This is my code: def __main__(sequence, target): big = 0 for elem in sequence: for elem_ in sequence: for _elem_ in sequence: for _elem__ in sequence: if (elem + elem_ + _elem_ + _elem__ == target): big+=1 print(str(big)) __main__([2, 1, 1, 1, 2, 1, 2, 2, 1], 6) The algorithm seems fine to me. But I keep getting the answer 2400 for this, when according to the test case, the answer should be 60. I suspect I'm going over one method four times, but then again dividing 2400 by 4 does not give you 60.

http://stackoverflow.com/comment/80562933
has text: Some of the lookups can be quite expensive, yes. However, silly me. I didn't think about `if '{name}' in my_string:`... of course that works too.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46807782
type: QuestionComment

http://stackoverflow.com/a/46770525
upvote count: 21
has body: You can use psycopg2.sql.Identifier to interpolate an identifier to a query, e.g.: from psycopg2.sql import Identifier, SQL query = SQL('SELECT * FROM {}.{}').format(*map(Identifier, (schema, table))) print(query.as_string(conn)) cur.execute(query) As per the linked documentation page, in psycopg2 v2.8+ you can also pass multiple strings to Identifier to represent a qualified name, i.e. a dot-separated sequence of identifiers: query = SQL('SELECT * FROM {}').format(Identifier(schema, table))
answers question: http://stackoverflow.com/q/46770201
score: 21
accepted answer of: http://stackoverflow.com/q/46770201
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80639455
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46844284
has text: @Month Never underestimate Tkinter's ability to bewilder you with its various quirks. ;)
type: Comment

http://stackoverflow.com/q/46796138
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46796305
has title: reading a file for certain input python
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80539096
linked to: http://stackoverflow.com/q/14507591
type: Question
has answer: http://stackoverflow.com/a/46796549
answer count: 3
has body: So I am doing a code to login and create a username and password and when logging in, i am reading an external file that contain all the user name and passwords in dictionary form e.g. {"aaaaaaaa": "aaaaaaA999"} This is the code to read it f3 = open("helloworld.txt","r") user = input("Enter login name: ") if user in f3.read(): passw = input("Enter password: ") print("") if user in f3.read() and passw in f3.read(): print ("Login successful!\n") else: print("") print("User doesn't exist!\n") f3.close() However when I try and read it it keeps saying that the user doesn't exist, any suggestions
has comment: http://stackoverflow.com/comment/80539153
has answer: http://stackoverflow.com/a/46796218
downvote count: 0

http://stackoverflow.com/q/46774991
has comment: http://stackoverflow.com/comment/80495720
answer count: 2
accepted answer: http://stackoverflow.com/a/46775784
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80495869
has body: For file: Year Grade 2000 100 2002 95 2001 88 2012 99 2000 66 and so forth, I have created a function that would calculate the average of grade of each following year. However, what I found was that instead of getting a list at the very end, I am continuously getting a tuple. I have to get a list instead of tuple to pass the assertion test. years, average_grades = [],[] d = {} with open(file,'r') as f: next(f) for line in f: year, grade = (s.strip() for s in line.split(',')) if year in d: d[year][0] += int(grade) d[year][1] += 1 else: d[year] = [int(grade),1] for year, grades in d.items(): years.append(int(year)) average_grades.append(float(grades[0]) / grades[1]) years, average_grades = zip(*sorted(zip(years, average_grades), key= lambda p: p[0])) return years, average_grades This function actually gives me Year, Grade 2000, 83 2001, 88 2002, 95 2012, 99 Something similar to this. It gives me the average of each year. However, it should be in orderly fashion (according to years), so I have done the last step. Should pass this: years_answer = [i+2000 for i in range(0,5)] assert_equal(years, years_answer) The error I am getting: AssertionError: (2000, 2001, 2002, 2003, 2004, 2005, 2006[62 chars]2017) != [2000, 2001, 2002, 2003, 2004, 2005, 2006[62 chars]2017] Any suggestions in fixing such problems?
has comment: http://stackoverflow.com/comment/80496402
tagged with: python
has comment: http://stackoverflow.com/comment/80495702
has comment: http://stackoverflow.com/comment/80495604
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80496517
has comment: http://stackoverflow.com/comment/80495738
possible better answer: http://stackoverflow.com/a/46775552
upvote count: 3
has comment: http://stackoverflow.com/comment/80497047
downvote count: 2
has answer: http://stackoverflow.com/a/46775552
has title: tuple to list issue: can't find where I have made mistakes
has answer: http://stackoverflow.com/a/46775784
type: Question

http://stackoverflow.com/comment/80668350
type: Comment
comment on: http://stackoverflow.com/a/46860389
has text: Right, but you are using the built in sort function. I am looking to use the one I have built to sort a list. How can I do it with the one I provided below (merge sort)?
score: 0
type: AnswerComment

http://stackoverflow.com/q/46803803
answer count: 1
tagged with: excel
has body: The program would follow the below steps: Click on executable program made through python File explorer pops up for user to choose excel file to alter Choose excel file for executable program to alter Spits out txt file OR excel spreadsheet with newly altered data to same folder location as the original spreadsheet
has comment: http://stackoverflow.com/comment/80590847
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46803941
has comment: http://stackoverflow.com/comment/80554587
type: Question
accepted answer: http://stackoverflow.com/a/46803941
tagged with: explorer
tagged with: python
tagged with: exe
has title: Python - how to get executable program to get the windows file browser to pop up for user to choose an excel file or any other document?
score: 0
tagged with: file

http://stackoverflow.com/q/46888448
has comment: http://stackoverflow.com/comment/80724269
has comment: http://stackoverflow.com/comment/80724370
has comment: http://stackoverflow.com/comment/80725869
answer count: 0
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80724429
upvote count: 1
has comment: http://stackoverflow.com/comment/80728069
has comment: http://stackoverflow.com/comment/80725925
has comment: http://stackoverflow.com/comment/80724146
type: Question
has comment: http://stackoverflow.com/comment/80725853
tagged with: graphics
has comment: http://stackoverflow.com/comment/80724127
has title: programmatically adapt figures to screen size in matplotlib across platforms and backends
has body: I can create very nice figures with import matplotlib.pyplot as plt fig = plt.figure() often, I need to generate large figures and I do fig = plt.figure(figsize=(80,60)) which is fine, but generates figures that are larger than the screen and need to be manually resized. This is desired behavior, if I read the documentation I see: figsize w,h tuple in inches So I have found the sizes of my screen manually, and now it generate nice fullscreen figures. However, if I change monitor I need to repat this. How do I find programmtatically the size of the screen in use? I have found many answers, but they all rely on external libraries or are platform-specific, or back-end specific Any solution that I could trasparently use across OS, backends, without adding dependencies to my project? How to determine screen size in matplotlib. I have tried window = plt.get_current_fig_manager().window screen_x, screen_y = window.wm_maxsize() but I am seeing the following exception: AttributeError: 'MainWindow' object has no attribute 'wm_maxsize' I am using Python 2.7 within Anaconda on Linux, Win 7+ with a automatic graphic backend. UPDATE It seems that many ways exist https://www.blog.pythonlibrary.org/2015/08/18/getting-your-screen-resolution-with-python/ How do I get monitor resolution in Python? https://stackoverflow.com/a/42355364/2666859 However, none of them is platform or backend independent. Perhaps an alternative is first detect platform and then the backend in use and cascade in a long multicase if with all the particular solutions as cases? Apparently, such a chain solution exists https://stackoverflow.com/a/21213145/4124317 Is this pythonic?Is the best way to go?
has comment: http://stackoverflow.com/comment/80724423
has comment: http://stackoverflow.com/comment/80725517
has comment: http://stackoverflow.com/comment/80725714
has comment: http://stackoverflow.com/comment/80725368
linked to: http://stackoverflow.com/q/29087072
has comment: http://stackoverflow.com/comment/80725241
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/3129322
has comment: http://stackoverflow.com/comment/80724057
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42354515
tagged with: python

http://stackoverflow.com/a/46817165
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46816736
type: Answer
answers question: http://stackoverflow.com/q/46816736
has body: Looks like you're mistakenly iterating over the columns, so to iterate over the elements of the pkg column you should try for pkg in df['pkg'] : with open('C:\Users\viru\Desktop\Test\{}\{}.json'.format(pkg,pkg)) as data_file: data = json.load(data_file) print data
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/46806820
has body: So you want to use instead of WX+b a different function for your neurons. Well in tensorflow you explicitly calculate this product, so for example you do y_ = tf.matmul(X, W) you simply have to write your formula and let the network learn. It should not be difficult to implement. In addition what you are trying to do (according to the paper you link) is called batch normalization and is relatively standard. The idea being you normalize your intermediate steps (in the different layers). Check for example https://www.google.ch/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;ved=0ahUKEwikh-HM7PnWAhXDXRQKHZJhD9EQFggyMAE&amp;url=https%3A%2F%2Farxiv.org%2Fabs%2F1502.03167&amp;usg=AOvVaw1nGzrGnhPhNGEczNwcn6WK or https://www.google.ch/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=4&amp;ved=0ahUKEwikh-HM7PnWAhXDXRQKHZJhD9EQFghCMAM&amp;url=https%3A%2F%2Fbcourses.berkeley.edu%2Ffiles%2F66022277%2Fdownload%3Fdownload_frd%3D1%26verifier%3DoaU8pqXDDwZ1zidoDBTgLzR8CPSkWe6MCBKUYan7&amp;usg=AOvVaw0AHLwD_0pUr1BSsiiRoIFc Hope that helps, Umberto
has comment: http://stackoverflow.com/comment/80563011
type: Answer
has comment: http://stackoverflow.com/comment/80561642
upvote count: 1
has comment: http://stackoverflow.com/comment/80560784
has comment: http://stackoverflow.com/comment/80563019
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46806127
has comment: http://stackoverflow.com/comment/80562986
has comment: http://stackoverflow.com/comment/80562927

http://stackoverflow.com/a/46786613
has body: You should change this line res = r.post(blast_url, headers = headers, params = data).text to res = r.post(blast_url, headers = headers, data = data).text Also, before using some tools, please read documentation of this tool, for example, dosc for requests you can find here
answers question: http://stackoverflow.com/q/46786548
has comment: http://stackoverflow.com/comment/80519940
upvote count: 1
score: 0
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80519743

http://stackoverflow.com/comment/80641138
type: Comment
type: QuestionComment
score: 0
has text: Also, I don't understand what does it mean a lot faster? Is it bad?
comment on: http://stackoverflow.com/q/46846708

http://stackoverflow.com/comment/80675968
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46864127
has text: I’m a beginner in python and this code is from a lot of different sources and I don’t know indentation that well. Please just try to understand and help.
type: QuestionComment

http://stackoverflow.com/comment/80576806
comment on: http://stackoverflow.com/q/46784115
type: QuestionComment
type: Comment
has text: Virtualenvwrapper sourcing line is not properly added to your `.bashrc` in the container. In the penultimate line, `&& echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc`, use single quotes instead of the double ones.
score: 1

http://stackoverflow.com/comment/116239504
has text: Had the same question about testing __init__. This answer makes sense to me but, to clarify one point... seems to me that, if it's just assigning values, __init__ likely inherently gets tested when you test it's methods or subclasses. However, if it has conditional logic in it you probably need to test it explicitly to make sure that conditional logic is operating correctly.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46859655
score: 0

http://stackoverflow.com/a/46778575
type: Answer
upvote count: 1
score: 1
has body: You can grab the links using requests and BeautifulSoup with only six liner code. Although the script is mostly identical to Sir Andersson, the library and the usage applied here is slightly different. import requests ; from bs4 import BeautifulSoup base_url = "http://www.europarl.europa.eu/news/en/press-room/page/{}" for url in [base_url.format(page) for page in range(10)]: soup = BeautifulSoup(requests.get(url).text,"lxml") for link in soup.select('[title="Read more"]'): print(link['href'])
answers question: http://stackoverflow.com/q/46768629
downvote count: 0

http://stackoverflow.com/comment/80701577
type: AnswerComment
score: 0
type: Comment
has text: What if i tried by using `Appointment.user_id.any(Appointment.user_id != overlapping.user.id)`, so i am getting all the users except the busy one, and the overlapping will be the condition so when it return **True** i will assign it to results, but still one problem that if overlapping returns more than one i must run it inside a for loop , am i right ?
comment on: http://stackoverflow.com/a/46876993

http://stackoverflow.com/q/46815435
linked to: http://stackoverflow.com/q/24929
has answer: http://stackoverflow.com/a/46815557
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has title: SQLITE DB Table Differences
type: Question
tagged with: sqlite
tagged with: python
accepted answer: http://stackoverflow.com/a/46815557
has body: I have two tables in a SQLITE DB (Table 1 and Table 2). I need to determine which items in table 1 are not in table two, and then print the results. I think I may have a working prototype, but am not familiar with SQL too much. import sqlite3 sqlite_file = 'data.db' conn = sqlite3.connect(sqlite_file) c = conn.cursor() c.execute("SELECT PK FROM Table1 WHERE NOT EXISTS(SELECT 1 FROM Table2 WHERE PK = Table1.pk)") results = list(c) count = len(results) print(results) print(count) Can someone confirm that this looks right? Is there a better way to do this? If not, any help would be much appreciated
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/80674286
score: 0
type: Comment
type: QuestionComment
has text: I don't see anywhere in that code where you call `clc` without passing a third arg.
comment on: http://stackoverflow.com/q/46863394

pyside
tags question: http://stackoverflow.com/q/46765402
tags question: http://stackoverflow.com/q/46834065
tags question: http://stackoverflow.com/q/46872850
tags question: http://stackoverflow.com/q/46900110
tags question: http://stackoverflow.com/q/46772790
type: Tag
tags question: http://stackoverflow.com/q/46835109
tag name: pyside
tags question: http://stackoverflow.com/q/46899540

http://stackoverflow.com/comment/80600939
has text: the MDN article, its based on HTTP protocol, rest is different than HTTP, it is simple representational state transfer, the underlying logic is client remembers everything required for the action to be performed by the server. On fulfilling those requirements by the client, the server returns the response and that is it. Implementing get method is your requirement, it will not affect your restful architecture.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46826501
score: 0

http://stackoverflow.com/comment/80684422
comment on: http://stackoverflow.com/q/46868482
type: QuestionComment
has text: @Wyatt x is just for me to print out to see the original against the print out I am looking for. xx was to .join so it wouldn't print out like abcde instead of ['a','b','c','d','e']. I basically just did that, in the beginning, to see if I got it to print out correctly and never removed them.
score: 0
type: Comment

http://stackoverflow.com/comment/80453246
comment on: http://stackoverflow.com/a/46753543
has text: how wow! The missing *return* was just a copy-past error, while the real error was that the resampler needs to return a *list*, not a *dict*!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46898757
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/46898893
has answer: http://stackoverflow.com/a/46898770
favorite count: 0
has title: Replace a word in a string if it is in a list of words
has answer: http://stackoverflow.com/a/46898797
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/80744771
tagged with: string
accepted answer: http://stackoverflow.com/a/46898770
has answer: http://stackoverflow.com/a/46898893
has body: I have the following string: s = 'in may 1999, nothing really happened, same as in june 1999' month_set = {'may', 'june', 'july'} I want to replace all words that match words in the month_set list with the word month. The output should look like 'in month 1999, nothing really happened, same as in month 1999' The for month in month_set: sentence = s.replace(month, 'date') print(sentence) but that returned the following: in may 1999, nothing really happened, same as in june 1999 in date 1999, nothing really happened, same as in june 1999 in may 1999, nothing really happened, same as in date 1999 Beside, if the above works, I need to apply it to a big list of strings which will make it slow, I think.
upvote count: 3

http://stackoverflow.com/comment/80449446
type: Comment
has text: @YaroslavSurzhikov. Absolutely! Your previous answer had the old style super call though.
type: AnswerComment
comment on: http://stackoverflow.com/a/46751598
score: 0

http://stackoverflow.com/q/46768733
has title: .remove() method is removing words from another variable?
linked to: http://stackoverflow.com/q/2612802
has body: I have a list of strings text text = ["this","is","a","string","identifier","identifier","identifier","identifier","identifier","identifier","identifier","identifier","please","help"] I want to get rid of some of the duplicates in this list, not all. So for example in the list above there are 8 instances of the word "identifier", I want to get rid of all but 2 of these instances while leaving the original instances in the same position; for example, the desired output would be text = ["this","is","a","string","identifier","identifier","please","help"] I have a list of strings of the duplicates I want to get rid of, stored in the variable delete_words delete_words = ["identifier"] To do this, I have: from collections import Counter temp_text = text # set up a static temporary variable so indexing issues don't arise for word in temp_text: # keep count of words in _text_ temp_word_counter_dict = dict(Counter([word for word in text])) if word in delete_words and temp_word_counter_dict[word] &gt; 2: text.remove(word) The problem with the code above is that The for loop doesn't iterate through every word, it only iterates through the first 10 words, so the resulting text variable still has 4 instances of the word "identifier" rather than 2 For some reason I can't understand, the temporary variable temp_text is having it's words removed as well even though I specify text.remove(word), so I have no idea what is going on here. Can anyone advise on how I can delete the duplicate words from the list while leaving 2 dupes in their original position? Thanks
score: 0
has comment: http://stackoverflow.com/comment/80482667
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/80482729
tagged with: duplicates
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has comment: http://stackoverflow.com/comment/80482775

http://stackoverflow.com/comment/80486442
score: 0
type: AnswerComment
type: Comment
has text: What if I want [help me](I'm trapped) to be one element instead of two?
comment on: http://stackoverflow.com/a/46770336

http://stackoverflow.com/comment/80611797
type: Comment
comment on: http://stackoverflow.com/a/46831995
type: AnswerComment
has text: @Henrij, try it on the example from your question.
score: 0

http://stackoverflow.com/a/46879046
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46877202
type: Answer
has body: To divide every row in each Var/Type grouping by a specific Level, use groupby and divide. For example, to divide by Unexposed, as in your example output: def divide_by(g, denom_lvl): cols = ["Metric1", "Metric2", "Metric3"] num = g[cols] denom = g.loc[g.Level==denom_lvl, cols].iloc[0] return num.divide(denom).fillna(0).round(2) df.groupby(['Var','Type']).apply(divide_by, denom_lvl='Unexposed') Output: Metric1 Metric2 Metric3 0 1.00 1.00 1.00 1 1.55 1.76 -0.01 2 0.58 0.66 -0.03 3 0.44 0.50 -0.07 4 0.54 0.60 -0.06 5 0.00 1.00 0.00 6 0.00 1.81 0.00 7 0.00 0.69 0.00 8 0.00 0.51 0.00 9 0.00 0.61 0.00 10 1.00 1.00 1.00 11 1.55 1.60 1.00 12 0.58 0.57 1.01 13 0.44 0.45 0.99 14 0.54 0.58 0.98
downvote count: 0

http://stackoverflow.com/comment/80511740
has text: FWIW, here are some lists I've found, which you may find useful in testing your code. These are lists of the given length of minimum highest denominator (with no repeated fractions): 6 [2, 3, 15, 18, 35, 63], 7 [2, 3, 15, 28, 35, 44, 77], 8 [2, 4, 6, 20, 58, 130, 174, 377]. I'm pretty sure 6 & 7 are correct, but I wouldn't be surprised if there's a better solution to 8.
comment on: http://stackoverflow.com/q/46781697
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46895885
has comment: http://stackoverflow.com/comment/80738782
has comment: http://stackoverflow.com/comment/80738780
has answer: http://stackoverflow.com/a/46895933
has answer: http://stackoverflow.com/a/46895945
favorite count: 0
has answer: http://stackoverflow.com/a/46895923
score: 0
possible better answer: http://stackoverflow.com/a/46895933
tagged with: python
has title: Python: How to replace beginning and ending brackets without using .replace([ or ])
answer count: 4
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/46896212
upvote count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/46895945
has body: My output is supposed to be incased in brackets like so: [[ken alex boz you] [ken alex you boz] [ken you boz alex] [alex you ken boz] ] I need to delete the very first [ as well as the very last ]. Is there a way without replacing all of the brackets?
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80739074

http://stackoverflow.com/q/46871139
has comment: http://stackoverflow.com/comment/80690424
has comment: http://stackoverflow.com/comment/80689728
type: UnansweredQuestion
tagged with: python
has title: Python clean up a daemon process
has comment: http://stackoverflow.com/comment/80807119
score: 3
answer count: 0
downvote count: 0
has body: Using python 3.6. What is considered best practice regarding clean up of daemon like process or applications? I'm am aware of context managers, I don't believe they can help in this scenario. Considering this code: from time import sleep import asyncio class RequiresResource(object): def __init__(self): self.file = open('test.txt', 'w') async def run_forever(self, msg, s=5): """Lets assume this function needs self.file""" while True: await asyncio.sleep(s) print(msg) def must_be_called(self): print('I was called') self.file.close() resource = RequiresResource() loop = asyncio.get_event_loop() try: loop.run_until_complete(asyncio.gather(resource.run_forever('Foo', 2), resource.run_forever('Bar',3))) finally: resource.must_be_called() resource.must_be_called() never gets called How would you handle this?
has comment: http://stackoverflow.com/comment/80689538
has comment: http://stackoverflow.com/comment/80689785
type: Question
has comment: http://stackoverflow.com/comment/80801311
tagged with: resource-cleanup
upvote count: 3
favorite count: 0
tagged with: daemon

http://stackoverflow.com/comment/80661258
has text: Should it be `Biquíni`?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46856809
type: Comment

http://stackoverflow.com/q/46865046
type: AnsweredQuestion
score: 1
has title: tkinter, How can you drag across buttons?
type: Question
has body: So I have a simple program where when you click a button from a grid it will be filled a colour. I wish to be able to drag across over the buttons and they get filled, unlike at the moment where you have to click every single button. Can this be done? Here's my code that probably isn't the best: from tkinter import * root=Tk() grid= Frame(root) grid.pack() img0=PhotoImage(file="0.png") img1=PhotoImage(file="1.png") img2=PhotoImage(file="2.png") fill = 1 class button: def __init__(self, x, y): self.type=0 self.but=Button(grid,command=self.change, image=img0, borderwidth=0) self.but.grid(row=y, column=x) def change(self): if self.type==fill: self.but.config(image=img0) self.type=0 else: self.but.config(image=eval("img"+str(fill))) self.type=fill def create(x,y): grid_buttons = [] for Y in range(y): grid_buttons.append([]) for X in range(x): grid_buttons[Y].append(button(X, Y)) create(15,15) root.mainloop()
has comment: http://stackoverflow.com/comment/80677807
accepted answer: http://stackoverflow.com/a/46867793
has comment: http://stackoverflow.com/comment/80680119
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46867793

http://stackoverflow.com/q/46893266
type: UnansweredQuestion
score: 1
has title: %lprun-like module profiling using kernprof
type: Question
upvote count: 1
downvote count: 0
favorite count: 0
has body: I would like to profile certain modules using kernprof without inserting @profile decorators. Inside IPython shell %lprun has awesome feature -m module which allows to profile all lines in a specified module. But if I need to run some script from the command I use kernprof. The latter unfortunately doesn't seem to have this functionality allowing to profile only using the decorator. How can I bring this module-profiling functionality to command line kernprof invocation?
tagged with: line-profiler
tagged with: profiling
tagged with: python
answer count: 0

http://stackoverflow.com/q/46782193
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/46792743
has answer: http://stackoverflow.com/a/46818081
type: UnansweredQuestion
has body: I am very much new to Python and Scrapy, but when I tried to iterate nested html elements, it is not producing desired result. Below is the HTML, i am trying to scrap. Page Title TV Samsung Vizio Element Laptop Apple Microsoft Dell Video Game Console Xbox One Xbox 360 PS 5 SSD Samsung Evo Crucial Sandisk The output I am trying to generate from the above html is a list of: Product Category -> Brand -> Id E.g. TV Samsung 1001 Vizio 1002 Element 1003 Laptop Apple 1004 Microsoft 1005 Dell 1006 Video Game Console Xbox Onen 1007 Xbox 360 1008 PS4 1009 ProductCategories.py def parse(self, response): l = ItemLoader(item=ProductSpiderItem(), response=response) titles = response.xpath('//*[@class="fsdDeptTitle"]') for title in titles: Product_Category= title.xpath('text()').extract() l.add_value('Product_Category', Product_Category) for brnd in title.xpath('//*[@class="fsdDeptCol"]/a[@class="class_a"]'): Brand = brnd.xpath('text()').extract() l.add_value('Brand', Brand) return l.load_item() At this moment it is printing all the product categories from "Outer For Loop" once and the "Inner For Loop" is printing all the brands irrespective of the product categories and the "Inner For Loop" prints all the brands whenever the "Outer For Loop" runs. I would really appreciate any help to resolve the issue. Thanks a lot.
tagged with: python
has title: Scrapy: Trying to iterate nested items but not producing desired output
tagged with: scrapy
type: Question

http://stackoverflow.com/q/46793868
has answer: http://stackoverflow.com/a/46822638
type: Question
linked to: http://stackoverflow.com/q/46699226
has answer: http://stackoverflow.com/a/46799615
tagged with: autodesk-forge
has title: Update File Version with Autodesk API
linked to: http://stackoverflow.com/q/46718771
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/46796595
has body: I am now able to upload a file and create an initial version for the file but am unable to update the version. Using the code in Step 6 of this tutorial does not work even after replacing versions:autodesk.core:File with versions:autodesk.bim360:File. From the error message, Request contains 0 includes instead of 1, it seems I need part of the included block from the example in Step 5 but I am not sure what it should look like; given the outer relationships blocks do not match in format between Steps 5 and 6, I am assuming the inner content varies as well. def create_version_for_file(self, project_name, file_name, folder_id, object_id, storage_id): project_id = self.get_project_id_by_name(project_name) existing_object_id = self.get_version_id_for_file_in_folder(project_name, folder_id, file_name) url = '{}data/v1/projects/{}/items'.format(self.DOMAIN, project_id) logger.info('Starting version create at %s for file_name %s, folder %s, object %s', url, file_name, folder_id, object_id) if existing_object_id: logger.info('Creating version for existing object') data = self._get_version_data_for_existing_file(file_name, object_id, storage_id) else: logger.info('Creating version for new object') data = self._get_version_json_for_new_file(file_name, folder_id, object_id) response = self.session.post(url, json=data, headers={ 'content-type': 'application/vnd.api+json', 'accept': 'application/vnd.api+json' }) if response.status_code != status.HTTP_201_CREATED: logger.warn('Version create for %s failed with status %s: %s', file_name, response.status_code, response.content) return None return json.loads(response.content) def _get_version_json_for_new_file(self, file_name, folder_id, object_id): return { "jsonapi": {"version": "1.0"}, "data": { "type": "items", "attributes": { "displayName": file_name, "extension": { "type": "items:autodesk.bim360:File", "version": "1.0" } }, "relationships": { "tip": { "data": { "type": "versions", "id": "1" } }, "parent": { "data": { "type": "…
accepted answer: http://stackoverflow.com/a/46822638
tagged with: python
possible better answer: http://stackoverflow.com/a/46796595
type: AnsweredQuestion

http://stackoverflow.com/q/46894569
has answer: http://stackoverflow.com/a/49095011
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46894847
tagged with: python
has body: I've used a selector in my python script to fetch the text from some html elements given below. I tried with .text to get the Shop here cheap string from the elements but it doesn't work at all. However, when I try with .text_content() it works as it should. My question is: What's wrong with .text method? Why couldn't it parse the text from the elements? Html elements: $6.35 $6.70 Shop here cheap What i tried with: from lxml import html tree = html.fromstring(element) for data in tree.cssselect(".Price__container"): print(data.text) #It doesn't work at all Btw, I don't wish to go on with .text_content() that is why I'm expecting any answer to scrape the text using .text instead. Thanks in advance.
type: AnsweredQuestion
tagged with: web-scraping
upvote count: 1
linked to: http://stackoverflow.com/q/3517461
type: Question
has answer: http://stackoverflow.com/a/46894847
answer count: 2
tagged with: css-selectors
has title: Scraper giving blank output
downvote count: 0
possible better answer: http://stackoverflow.com/a/49095011
score: 1

http://stackoverflow.com/a/46895658
accepted answer of: http://stackoverflow.com/q/46878848
score: 3
answers question: http://stackoverflow.com/q/46878848
upvote count: 3
has body: Pika is not thread safe. You should avoid sharing the connection object across Flask's contexts. Writing your own Flask plugin wouldn't take that much boilerplate though. It would be very similar to the documentation example plugin. Otherwise, you could do a quick search with flask pika on a search engine and you'll find some existing plugins for this purpose. I have not tried them and they don't seem really popular, but maybe you should give them a go? I don't see why it wouldn't be possible. Flask knows how to deal with this. However, I reckon it would severly degrade performances. Moreover, you might hit some corner-cases if the plugins you use are not perfectly written. Just like you would declare any lock for threading. Nothing much. You put it at the module level (not in Flask's context) so that it is global, that's it. That being said, I think you shouldn't proceed this way. You should rather run the update-job in a different process from the Web Server (using Flask CLI or whatever if you need to re-use some functions). It will be better performance-wise, it's easier to reason about, it's more loosely coupled. Also, you should avoid running into locking headaches as long as possible. Believe me, it's a real source of problems. It's a nightmare to test properly, to debug, to maintain and quite risky when it comes to real-production use-cases. And if you really, really need a lock, don't hold it for one minute, it's way too long. I don't know your exact requirements, but there surely is a solution that is OK and that does not involve such complexity.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/46785814
has body: By default, DRF won't update routes. You should override update method of your serializer, like this: class BillSerializer(ModelSerializer): routes = RouteSerializer(many=True, read_only=True) class Meta: model = Bill fields =('id','created_on','created_by','total_bill_amount','routes') def update(self, instance, validated_data) instance = super().update(instance, validated_data) routes = validated_data.get('routes') if routes: for route_info in routes: Route.objects.filter(id=route_info['id']).update(**route_info) return instance Hope it helps!
has comment: http://stackoverflow.com/comment/80520797
has comment: http://stackoverflow.com/comment/80552298
answers question: http://stackoverflow.com/q/46783667
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80520403
type: Answer
has comment: http://stackoverflow.com/comment/80520309
has comment: http://stackoverflow.com/comment/80520717
has comment: http://stackoverflow.com/comment/80520910
upvote count: 1
has comment: http://stackoverflow.com/comment/80520760
has comment: http://stackoverflow.com/comment/80520860
has comment: http://stackoverflow.com/comment/80520470
has comment: http://stackoverflow.com/comment/80520255
has comment: http://stackoverflow.com/comment/80520844

http://stackoverflow.com/a/46898549
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46897332
type: Answer
upvote count: 2
has body: I agree with Taras' suggestion that Sentry is a great thing to install. Unfortunately, if the issue isn't generating exceptions (or INFO or WARN messages) then it won't catch the issue on its own. I'd suggest that (if you haven't already done so) implementing sentry logging to your views: https://raven.readthedocs.io/en/stable/integrations/django.html Once you've added Sentry to your production app, you can add code like the following into your views: def my_view(request): if some_condition: foo = 12 else: foo = 15 logger.info('Line 45 of the Login view', exc_info=True, extra={ 'request': request, 'myvar': foo, # A variable you're interested in }) Then, if you visit the page on production, it will generate a log message that you can view in sentry. Side Note Once you've determined what your particular error is here, it might be worth examining what's behind you not being able to reproduce the issue locally. This inevitably happens to everyone, but it's a good thing to minimize. Some techniques for doing so include: Using django-environ to have your settings.py files look similar/identical Restoring your local databases from one of your production database backups Limiting code that detects and behaves differently in prod/dev environments to just the settings.py file. Using docker to keep your local/prod instances nearly-identical.
score: 2
answers question: http://stackoverflow.com/q/46897332
type: AcceptedAnswer

http://stackoverflow.com/comment/80576431
type: Comment
has text: Thanks for this completely forgot about integer division.
comment on: http://stackoverflow.com/a/46813360
score: 0
type: AnswerComment

http://stackoverflow.com/comment/117922254
has text: Indeed, you are really calculating the linear kernel function, due to the fact that the magnitude of a TF-IDF Vector is always 1.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46764347

http://stackoverflow.com/comment/80540266
type: Comment
has text: Hmm.. although this cannot be done in some embedded environments, turning off optimizations may help on your Windows and Linux platforms. This sounds like it could be compiler specific.
comment on: http://stackoverflow.com/q/46796126
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80611916
comment on: http://stackoverflow.com/q/46832129
score: 0
has text: @Wondercricket : don't use the identity operator for equality test.
type: Comment
type: QuestionComment

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/46896048

http://stackoverflow.com/q/46795665
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/46795818
tagged with: python
has body: I have a list that essentially goes as such: Dalc = [1,2,1,1,1,1,1,1,1,1,1,1,5,1,1,3,1,2,1,1,1,1,2.......] It currently contains 395 elements, and I'm trying to extend it such that I keep the same percentage of 1's, 2's, 3's, 4's and 5's. Min = 1, Max = 5, and I initially did the following to try and extend the list past 10000 elements: from random import randint .... Dalc_add = [] dalc_max = max(Dalc) dalc_min = min(Dalc) i = 0 while i &lt; 10000: Dalc_add.append(randint(dalc_min, dalc_max)) i = i + 1 Dalc.append(Dalc_add) What this gave was a list with the initial bias present for the first 395 iterations, but then after that the rest of the list looked like: [1,5,3,2,3,1,4,2,4,5,2,5,3,2,1,3,4,2,1,3,3,4,1........] A lot more 3, 4, &amp; 5 present, and it completely messes up any statistical analysis I can perform. How do I extend the list as above, while also preserving the weights and biases present (with respect to frequency of occurrence) for the list values?
has comment: http://stackoverflow.com/comment/80538191
has comment: http://stackoverflow.com/comment/80538071
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/46795813
has title: Extend a list with numbers that match initial bias
accepted answer: http://stackoverflow.com/a/46795813
possible better answer: http://stackoverflow.com/a/46795818
type: Question
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/80538083

http://stackoverflow.com/comment/80578046
comment on: http://stackoverflow.com/a/46814897
has text: So I have to use Django forms.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/80615730
score: 0
comment on: http://stackoverflow.com/a/46833958
type: Comment
type: AnswerComment
has text: I wont have duplicate paths, but this is certainly handy for other code issues. This method is also slower than the normal lambda expression. as a side note: add `datetime.fromtimestamp()` around `os.path.getmtime`. Or else the values will be incorrect

http://stackoverflow.com/q/46851802
type: Question
has body: I have a web scraper that saves data to a sqlite database locally on my machine. At the beginning of the script, I have it load the database, conn = sqlite3.connect('named_database.db') alldata = pd.read_sql_query("SELECT * FROM table_in_named_database", conn) which throws the following error, Traceback (most recent call last): File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 1404, in execute cur.execute(*args) sqlite3.OperationalError: no such table: table_in_named_database During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./path_to/this_script.py", line 127, in &lt;module&gt; main() File "./path_to/this_script.py", line 113, in main alldata = pd.read_sql_query('SELECT * FROM table_in_named_database', conn) File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 332, in read_sql_query parse_dates=parse_dates, chunksize=chunksize) File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 1439, in read_query cursor = self.execute(*args) File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 1416, in execute raise_with_traceback(ex) File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/compat/__init__.py", line 344, in raise_with_traceback raise exc.with_traceback(traceback) File "/Users/emporerblk/miniconda3/lib/python3.6/site-packages/pandas/io/sql.py", line 1404, in execute cur.execute(*args) pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT * FROM table_in_named_database': no such table: table_in_named_database I know that the data exists because when I access it via the command line, it works. &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; conn = sqlite3.connect("./path_to/named_database.db") &gt;&gt;&gt; conn &lt;sqlite3.Connection object at 0x112efab90&gt; &gt;&gt;&gt; df = pd.read_sql_query("SELECT * FROM table_in_named_d…
has comment: http://stackoverflow.com/comment/80663753
favorite count: 0
has title: Error when reading SQL table with Pandas
tagged with: pandas
tagged with: sqlite
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 1

http://stackoverflow.com/comment/80486680
comment on: http://stackoverflow.com/q/46770482
type: Comment
type: QuestionComment
score: 0
has text: Can you share the value for `data`

http://stackoverflow.com/comment/80861900
has text: If you mean the python sdk, and the rest API, they are actually the same thing. The sdk communicates over the API.
score: 0
comment on: http://stackoverflow.com/q/46801008
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80687727
type: QuestionComment
has text: I dont see `-g` option, nor do i see init. Can you please be more accurate in asking the question?
comment on: http://stackoverflow.com/q/46870207
score: 0
type: Comment

http://stackoverflow.com/q/46784609
answer count: 1
has body: I would like to open a new browser by clicking Button from python tkinker GUI and new directory need to be saved and display on GUI. I am able to open current directory with command below; import os subprocess.Popen('explorer "C:\temp"') cur_path = os.path.dirname(__file__) my question is how to save the active browser dir and display on GUI after Step A/B above?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46791346
tagged with: python
has title: Python tkinter : browse directory and save to new directory
type: AnsweredQuestion
score: 2
upvote count: 3
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46791346

http://stackoverflow.com/q/46854408
answer count: 0
has comment: http://stackoverflow.com/comment/80657044
has body: Please, I want to repeat in R a data crossing I did in Python 3 - Pandas. The most appropriate way would be with the use of dplyr? I have two CSVs. One is about donations for politicians: each line is a donation and each line has the name of the donor company and the federal registration number of that company (CPF_CNPJ_doador - unique for each company in the country) CPF_CNPJ_doador Nome_doador Valor 73668675000187 CWVGRAFICA EDITORA E BAZAR EIRELI LTDA ME 1000,00 83647909000163 CARBONIFERA CRICIUMA S/A 1750,00 10731057000114 HAROLDO AZEVEDO CONSTRUÇÕES LTDA 100,00 ... The other CSV has companies that have environmental irregularities. You have several data, including the company name and the federal registration number of that company (CPF_CNPJ - unique for each company in the country). But a company may appear more than once in this CSV - it may have multiple affiliates with irregularities for example Nome_Razao_Social CPF_CNPJ Carajas Madeiras Industria e Comercio Ltda - Me 02579504000214 Carbo Gás Ltda 03828695000435 Carbomil Química S/A 07645062000108 Carbomil Química S/A 07645062000108 I made a pandas merge (Python 3) of these two CSVs: ibama_doadores_orig= pd.merge(eleitos_d_doadores, ibama.drop_duplicates('CPF_CNPJ_limpo'), left_on='CPF_CNPJ_doador_originario', right_on='CPF_CNPJ_limpo', how = 'left') And then I removed the nulls ibama_doadores_orig = ibama_doadores_orig[pd.notnull(ibama_doadores_orig['CPF_CNPJ_limpo'])] Both can be duplicated in CSVs (a politician can receive donations from the same company on different dates, for example, and a company number repeated in the second csv). But I want to get all the lines of donations, even if they are from lines with duplicate companies. But from the second CSV I just want to get the first appearance In Python this worked (I checked the Excel PivotTable). Please, in the R language, does anyone know how to do it? Data example First lines of the ibama file: index Nome_Razao_Social CPF_CNPJ CPF_CNPJ_limpo UF_E…
type: Question
has comment: http://stackoverflow.com/comment/80657482
has comment: http://stackoverflow.com/comment/80656873
tagged with: http://stackoverflow.com/tag/r
score: 0
has comment: http://stackoverflow.com/comment/80656683
linked to: http://stackoverflow.com/q/5963269
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: How to avoid repeated fields in R with dplyr?

http://stackoverflow.com/q/46857466
tagged with: css
has answer: http://stackoverflow.com/a/46889664
score: 1
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/80867422
tagged with: webdriver
type: Question
has comment: http://stackoverflow.com/comment/80780821
has answer: http://stackoverflow.com/a/46857493
answer count: 3
downvote count: 0
has body: I'm trying to figure out how to select this element. It's the last iteration of the class on the webpage. The id will change every week. The source is below: Disney Mainline Oct 15, 2017 Oct 03, 2017 06:00 PM 15 Oct 05, 2017 03:30 PM 80 Disney Mainline Oct 22, 2017 Oct 10, 2017 10:21 AM 15 Oct 12, 2017 03:30 PM 80 Disney Mainline Oct 29, 2017 Oct 17, 2017 06:00 PM 15 Oct 19, 2017 03:30 PM 80 I'm wanting to select the last iteration of the class "cls_arw arw_blue" so that it will take me to its designated link. But I haven't been able to figure it out. I've tried: driver.find_element_by_class_name("cls_arw arw_blue") driver.find_element_by_id("ctl00_cphMain_gdvSchdRel_ctl04_lnkSchTyp") driver.find_element_by_css_selector("a.cls_arw arw_blue") Note: I realize that, if successful, my attempts would only have found the first element under those conditions, but it hasn't even been able to find the element based off of what I've tried. When I do figure out how to find the element, I would also need help finding the last iteration of it on the page.
favorite count: 0
has title: Python - How can I select this element?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47116905

http://stackoverflow.com/a/46902023
downvote count: 0
has body: I would use concat: In [11]: res = pd.concat([df1, df2, df3, df4], keys=[1, 2, 3, 4], axis=1) In [12]: res Out[12]: 1 2 3 4 AAPL MSFT TSLA GE AAPL MSFT TSLA GE AAPL MSFT TSLA GE AAPL MSFT TSLA GE 2013-01-01 0.144764 1.292692 -1.303908 -0.843892 -1.104683 -1.178507 0.898648 -0.626209 0.492292 0.147169 1.814729 0.562406 -0.121656 0.865116 0.430813 -0.326225 2013-01-02 -0.163063 0.019601 -2.565271 0.708233 0.317464 -2.574969 -0.080129 -1.176806 0.045253 0.684745 -1.062797 -0.483389 -0.579194 0.401920 -0.393240 0.113734 2013-01-03 0.213592 -0.732072 -0.942323 0.191418 -0.962551 -0.027296 0.665155 2.775983 -0.627107 -0.015927 0.939107 0.239057 0.548166 -1.753082 -0.007525 1.771812 2013-01-04 1.067464 -0.331888 0.638843 -1.197937 0.925848 2.273798 0.646925 -2.910974 0.531653 -0.748255 0.262995 0.077923 -0.867982 1.174089 0.183573 0.263749 2013-01-05 0.873720 -0.816305 0.270330 -1.543169 0.116701 -1.392711 1.519368 -0.601046 -0.154348 -0.345653 -0.785385 -0.095604 1.351421 0.192520 0.802445 2.107376 2013-01-06 -0.781975 1.007111 -2.555165 -1.866207 1.480997 0.212057 1.053570 -0.798790 -0.785660 -0.853178 -2.274432 0.481971 -1.555876 -0.928069 -0.408319 0.270534 then you can pull out APPL using xs: In [13]: res.xs("AAPL", level=1, axis=1) Out[13]: 1 2 3 4 2013-01-01 0.144764 -1.104683 0.492292 -0.121656 2013-01-02 -0.163063 0.317464 0.045253 -0.579194 2013-01-03 0.213592 -0.962551 -0.627107 0.548166 2013-01-04 1.067464 0.925848 0.531653 -0.867982 2013-01-05 0.873720 0.116701 -0.154348 1.351421 2013-01-06 -0.781975 1.480997 -0.785660 -1.555876 Perhaps a nicer thing is to get a dict of the groups: In [21]: d = dict(iter(res.groupby(level=1, axis=1))) In [22]: d["AAPL"] Out[22]: 1 2 3 4 AAPL AAPL AAPL AAPL 2013-01-01 0.144764 -1.104683 0.492292 -0.121656 2013-01-02 -0.163063 0.317464 0.045253 -0.579194 2013-01-03 0.213592 -0.962551 -0.627107 0.548166 2013-01-04 1.067464 0.925848 0.531653 -0.867982 2013-01-05 0.873720 0.116701 -0.154348 1.351421 2013-01-06 -0.781975 1.480997 -0…
accepted answer of: http://stackoverflow.com/q/46901961
type: Answer
answers question: http://stackoverflow.com/q/46901961
has comment: http://stackoverflow.com/comment/80750992
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/80613642
has text: Please make sure that you give a brief explanation of what you are trying to do in the beginning. The snippet can be pasted afterwards. Somebody might downvote your question because of this. For your answer now, I am trying to find something similar and I will answer when I arrive home :)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46832964
type: Comment

http://stackoverflow.com/comment/80745712
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46889184
type: Comment
has text: Thank you for your comment. I'm sorry insufficient my answer.

http://stackoverflow.com/a/46819720
type: Answer
has comment: http://stackoverflow.com/comment/80587388
answers question: http://stackoverflow.com/q/46819003
score: 1
has body: I have no explanation for your observation (not much of a matlab-user; but i can confirm that octave is doing it like you said), but following scipy's example-usage, you can achieve this result using: import numpy as np import scipy.sparse as sp data = np.tile(np.array([-8037.5, 50., -12.5]), (3,1)) x = sp.spdiags(data, np.arange(3), 1, 51) print(x) Output: (0, 0) -8037.5 (0, 1) 50.0 (0, 2) -12.5 The tile-step builds: [[-8037.5 50. -12.5] [-8037.5 50. -12.5] [-8037.5 50. -12.5]] and of course everything is 0-indexing based.
has comment: http://stackoverflow.com/comment/80587240
has comment: http://stackoverflow.com/comment/80590358
upvote count: 1
has comment: http://stackoverflow.com/comment/80590337
has comment: http://stackoverflow.com/comment/80590527
downvote count: 0

http://stackoverflow.com/q/46828093
has comment: http://stackoverflow.com/comment/80603737
tagged with: python
has title: How to get property names from super class in sub class python
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/80603712
has comment: http://stackoverflow.com/comment/80603795
has answer: http://stackoverflow.com/a/46828404
has body: I have a class like below class Paginator(object): @cached_property def count(self): some_implementation class CachingPaginator(Paginator): def _get_count(self): if self._count is None: try: key = "admin:{0}:count".format(hash(self.object_list.query.__str__())) self._count = cache.get(key, -1) if self._count == -1: self._count = self.count # Here, I want to get count property in the super-class, this is giving me -1 which is wrong cache.set(key, self._count, 3600) except: self._count = len(self.object_list) count = property(_get_count) As indicated in the comment above, self._count = &lt;expression&gt; should get the count property in super-class. If it is method we can call it like this super(CachingPaginator,self).count() AFAIK. I have referred many questions in SO, but none of it helped me. Can anyone help me in this.
has comment: http://stackoverflow.com/comment/80603629
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80603760
answer count: 1
tagged with: inheritance
has comment: http://stackoverflow.com/comment/80603821
has comment: http://stackoverflow.com/comment/80603828
score: 0
has comment: http://stackoverflow.com/comment/80603765

http://stackoverflow.com/q/46838636
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
answer count: 2
upvote count: 1
has title: How to make sure I only print once?
has comment: http://stackoverflow.com/comment/80625145
possible better answer: http://stackoverflow.com/a/46838696
tagged with: printing
accepted answer: http://stackoverflow.com/a/46838679
has answer: http://stackoverflow.com/a/46838696
favorite count: 0
has body: I am a beginner to python, I am trying to create a program that check's the password variability. The code is finished but when I execute it, it prints the same message multiple times. But I only want it to print once. def controleer_paswoord(wachtwoord): import re for item in wachtwoord: kleine_letter = re.search( "[a-z]",wachtwoord) hoofd_letter = re.search( "[A-Z]",wachtwoord) cijfer = re.search ("[0-9]",wachtwoord) karakter = re.search ("[$#@]",wachtwoord) lengte = (len(wachtwoord)&lt;6 or len(wachtwoord)&gt;12) if kleine_letter == None: print("{0} -&gt; Geldig paswoord? False".format(wachtwoord)) elif hoofd_letter == None: print("{0} -&gt; Geldig paswoord? False".format(wachtwoord)) elif cijfer == None: print("{0} -&gt; Geldig paswoord? False".format(wachtwoord)) elif karakter == None: print("{0} -&gt; Geldig paswoord? False".format(wachtwoord)) elif lengte == None: print("{0} -&gt; Geldig paswoord? False".format(wachtwoord)) else: print("{0} -&gt; Geldig paswoord? True".format(wachtwoord)) # wachtwoord = (input("Geef hier uw gewenste wachtwoord in:" )) wachtwoord = "2w3E" controleer_paswoord(wachtwoord) what I get: #2w3E -&gt; Geldig paswoord? False #2w3E -&gt; Geldig paswoord? False #2w3E -&gt; Geldig paswoord? False #2w3E -&gt; Geldig paswoord? False what I want: #2w3E -&gt; Geldig paswoord? False
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46838679

http://stackoverflow.com/q/46801202
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80549471
tagged with: python
has comment: http://stackoverflow.com/comment/80549223
answer count: 0
has body: I'm using Python to generate a list of students for "Peer Assessment". The idea is to assign each student in a cohort a fixed number of peers for assessment. Rules: each student can't assess themselves each student needs to assess N students therefore, each student will be assessed N times I have a failed attempt and then came up with a simple solution: from collections import defaultdict from random import shuffle from pprint import pprint student_raw = ''' Adam Bob Jordan Tom Edward Alex David Alistar JoshA Yin Keanu JoshB Liam Jesse Mike Aaron Nick Daniel ''' num = 3 # number of assessees per assessor student_list = [s for s in student_raw.splitlines() if s != ''] shuffle(student_list) assessors = student_list assignment = defaultdict(list) print(assessors) for i, assessor in enumerate(assessors): if (i+1+num) &lt; len(assessors): assignment[assessor] = assessors[i+1: i+1+num] else: assignment[assessor] = assessors[i+1: len(assessors)] + assessors[0: (i+1+num)%len(assessors)] pprint(assignment) I wonder if there is a better algorithm for this? Result: ['Daniel', 'Adam', 'Nick', 'Jordan', 'Alistar', 'Bob', 'Aaron', 'Alex', 'Edward', 'Jesse', 'David', 'Keanu', 'Mike', 'Tom', 'JoshB', 'Liam', 'Yin', 'JoshA'] defaultdict(&lt;class 'list'&gt;, {'Aaron': ['Alex', 'Edward', 'Jesse'], 'Adam': ['Nick', 'Jordan', 'Alistar'], 'Alex': ['Edward', 'Jesse', 'David'], 'Alistar': ['Bob', 'Aaron', 'Alex'], 'Bob': ['Aaron', 'Alex', 'Edward'], 'Daniel': ['Adam', 'Nick', 'Jordan'], 'David': ['Keanu', 'Mike', 'Tom'], 'Edward': ['Jesse', 'David', 'Keanu'], 'Jesse': ['David', 'Keanu', 'Mike'], 'Jordan': ['Alistar', 'Bob', 'Aaron'], 'JoshA': ['Daniel', 'Adam', 'Nick'], 'JoshB': ['Liam', 'Yin', 'JoshA'], 'Keanu': ['Mike', 'Tom', 'JoshB'], 'Liam': ['Yin', 'JoshA', 'Daniel'], 'Mike': ['Tom', 'JoshB', 'Liam'], 'Nick': ['Jordan', 'Alistar', 'Bob'], 'Tom': ['JoshB', 'Liam', 'Yin'], 'Yin': ['JoshA', 'Daniel', 'Adam']})
has title: algorithm to find people to review/assess in a group
type: Question
has comment: http://stackoverflow.com/comment/80549485
tagged with: algorithm

http://stackoverflow.com/q/46896386
downvote count: 0
tagged with: scikit-learn
tagged with: dimensionality-reduction
favorite count: 0
type: UnansweredQuestion
has body: I have this features which I am trying to reduce based on Variance Threshold: x2.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 120 entries, 0 to 119 Columns: 6083 entries, ADULT.EDUCATION to 1kmrecreacion intelectual / 1kmgeo dtypes: float64(6083) memory usage: 5.6 MB I need to retain the features names, so I have obtained this function from another Stackoverflow question: def VarianceThreshold_selector(data): columns = data.columns selector = VarianceThreshold(.5) selector.fit_transform(data) labels = [columns[x] for x in selector.get_support(indices=True) if x] return pd.DataFrame(selector.fit_transform(data), columns=labels) I apply it: VarianceThreshold_selector(x2) I am getting this error: Shape of passed values is (4105, 120), indices imply (4104, 120) How can I solve it?
tagged with: shapes
has answer: http://stackoverflow.com/a/51837587
tagged with: python
has title: Variance Threshold shape of passed error
score: 1
type: Question
answer count: 2
tagged with: feature-selection
has comment: http://stackoverflow.com/comment/80743957
has answer: http://stackoverflow.com/a/67598100
upvote count: 1

http://stackoverflow.com/comment/80612759
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46832024
has text: I don't know if your videos is suitable for this questions.. Because for my question there is a `for loop` before the `threading`. But there's no `for loop` in that video. I just want the `threading` stops before the functions are finished so it can start processing the next round of the `for loop`.
score: 0

http://stackoverflow.com/comment/80734848
comment on: http://stackoverflow.com/q/46893770
score: 0
type: Comment
type: QuestionComment
has text: What s the output that you are seeing?

http://stackoverflow.com/comment/80677531
comment on: http://stackoverflow.com/q/46864957
type: Comment
type: QuestionComment
has text: See my answer. If you want to use the datetime module, you need to set the relative dates correctly.
score: 0

system-calls
type: Tag
tag name: system-calls
tags question: http://stackoverflow.com/q/46780385

http://stackoverflow.com/q/46819731
type: AnsweredQuestion
tagged with: classification
downvote count: 3
has comment: http://stackoverflow.com/comment/80587048
accepted answer: http://stackoverflow.com/a/46883407
has body: From what I've read, it appears that a split of around 80% training 20% va validation data is close to optimal. As the size of the testing dataset increases, the variance of the validation results should go down at the cost of less effective training (lower validation accuracy). Therefore, I am confused as to the following results which seemed to show optimal accuracy and low variance with a TEST_SIZE=0.5 (each trial ran multiple times and one trial was selected to represent the different testing sizes). TEST_SIZE=0.1, this should work effectively due to large training size but have a larger variance (5 trials varied between 16% and 50% accuracy). Epoch 0, Loss 0.021541, Targets [ 1. 0. 0.], Outputs [ 0.979 0.011 0.01 ], Inputs [ 0.086 0.052 0.08 0.062 0.101 0.093 0.107 0.058 0.108 0.08 0.084 0.115 0.104] Epoch 100, Loss 0.001154, Targets [ 0. 0. 1.], Outputs [ 0. 0.001 0.999], Inputs [ 0.083 0.099 0.084 0.079 0.085 0.061 0.02 0.103 0.038 0.083 0.078 0.053 0.067] Epoch 200, Loss 0.000015, Targets [ 0. 0. 1.], Outputs [ 0. 0. 1.], Inputs [ 0.076 0.092 0.087 0.107 0.077 0.063 0.02 0.13 0.054 0.106 0.054 0.051 0.086] Target Class 0, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 1, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 2, Predicted Class 2 Target Class 1, Predicted Class 0 Target Class 0, Predicted Class 0 Target Class 2, Predicted Class 2 50.0% overall accuracy for validation set. TEST_SIZE=0.5, this should work okay (accuracy between the other two cases) - 5 trials varied between 92 and 97% accuracy for some reason. Epoch 0, Loss 0.547218, Targets [ 1. 0. 0.], Outputs [ 0.579 0.087 0.334],…
type: Question
has comment: http://stackoverflow.com/comment/80587049
tagged with: neural-network
score: -1
has title: Why does a 50-50 train/test split work best for a data-set of 178 observations with this neural network?
has comment: http://stackoverflow.com/comment/80588742
has comment: http://stackoverflow.com/comment/80587993
tagged with: validation
answer count: 1
tagged with: training-data
has answer: http://stackoverflow.com/a/46883407
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/80445881
type: Comment
has text: By `cat` you mean col_name? With regards to the second point - I can't believe that I did that haha
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46749751

http://stackoverflow.com/comment/86363327
comment on: http://stackoverflow.com/q/46811709
type: Comment
type: QuestionComment
score: 2
has text: One thing that I would consider if I had the data on disk in numpy-friendly format is doing a [`mmap`](https://docs.python.org/2/library/mmap.html) of that file(s) and wrapping them to a numpy array. Doing an `mmap` of the same file in several processes (setting `MAP_SHARED | PROT_READ`) should result in the data being stored in RAM at most once.

http://stackoverflow.com/comment/80541927
type: Comment
comment on: http://stackoverflow.com/a/46794057
type: AnswerComment
has text: wow nice one - thanks...was so close yet so far...appreciate it!
score: 0

http://stackoverflow.com/q/46880388
answer count: 2
downvote count: 1
has body: I have scoured all of google's available links to address this issue, yet it still remains unsolved for me... I get the following error when trying to import graph_tool in python3. I have both python 2.7 and 3.6 and anaconda installed. I install packages using either pip, conda, or brew. I have MacOS Sierra 10.12.3. $ python3 Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12) [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from graph_tool.all import * Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/numpy/core/__init__.py", line 16, in &lt;module&gt; from . import multiarray ImportError: cannot import name 'multiarray' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/site-packages/graph_tool/__init__.py", line 104, in &lt;module&gt; import numpy File "/usr/local/lib/python3.6/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/usr/local/lib/python3.6/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/usr/local/lib/python3.6/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/usr/local/lib/python3.6/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/usr/local/lib/python3.6/site-packages/numpy/core/__init__.py", line 26, in &lt;module&gt; raise ImportError(msg) ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try `git clean -xdf` (removes all files not under version control). Otherwise reinstall numpy. Original error was: cannot import name 'multiarray' Some info on my dire…
has answer: http://stackoverflow.com/a/46880535
favorite count: 0
tagged with: importerror
accepted answer: http://stackoverflow.com/a/46888017
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46888017
has title: python ImportError: cannot import name 'multiarray'
score: 1
possible better answer: http://stackoverflow.com/a/46880535
type: Question
linked to: http://stackoverflow.com/q/46900020
tagged with: graph-tool
upvote count: 2
tagged with: numpy

http://stackoverflow.com/q/46864882
favorite count: 0
has answer: http://stackoverflow.com/a/46864922
tagged with: python
score: -5
tagged with: instance
has body: I'm trying extract class names via dir() and create their instance on the fly via a variable name in a for loop. How can I make python interpret 'item' as a variable name and not the 'non-existing' class name. &gt;&gt;&gt; class cls1(): ... def __init__(self): ... self.speak = 'say cls1' ... def replay(self): ... print self.speak ... &gt;&gt;&gt; for item in dir(): ... if item[:2] != '__': ... print 'item = ', item ... x = item() ... x.reply() ... item = cls1 Traceback (most recent call last): File "&lt;stdin&gt;", line 4, in &lt;module&gt; TypeError: 'str' object is not callable
type: Question
type: AnsweredQuestion
downvote count: 5
accepted answer: http://stackoverflow.com/a/46864922
upvote count: 0
answer count: 1
has title: creating an instance in a for loop

http://stackoverflow.com/q/46860193
favorite count: 0
has title: Error "unable to find vcvarsall.bat" despite newest visual studio version
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86707479
tagged with: kernel
tagged with: visual-studio
has comment: http://stackoverflow.com/comment/80703758
tagged with: compiler-errors
answer count: 0
tagged with: cython
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/85460693
has comment: http://stackoverflow.com/comment/80670131
has body: I'm working in Jupyter Notebook. When I want to compile a .pyx in cython, it throws an error similar to this: %run -i setup.py build_ext --inplace unable to find vcvarsall.bat The setup.py file looks like this: from distutils.core import setup from Cython.Build import cythonize setup( ext_modules=cythonize("hh_vers_vector.pyx"), ) This only happens, however, on my computer at work. At the one at home, it works just fine. It is probably an issue with Visual Studio as explained here. The thing is, I installed the very same version of Visual Studio 2017 Community on both computers. The latest Anaconda 3 version is installed on both computers. Both use Python 3.6.2 and IPython 6.1.0. So how can that be? Both run with Windows 10. I'll also show you my .pyx file. If you need more information I will edit my post. from math import exp import numpy as np import time def hhModel(*params, Iext, float dt, int Vref): ## Unwrap params argument: these variables are going to be optimized cdef float ENa = params[0] cdef float EK = params[1] cdef float EL = params[2] cdef float GNa = params[3] cdef float GK = params[4] cdef float GL = params[5] ## Input paramters # I : a list containing external current steps, your stimulus vector [nA] # dt : a crazy time parameter [ms] # Vref : reference potential [mV] def alphaM(float v, float vr): return 0.1 * (v-vr-25) / ( 1 - exp(-(v-vr-25)/10) ) def betaM(float v, float vr): return 4 * exp(-(v-vr)/18) def alphaH(float v, float vr): return 0.07 * exp(-(v-vr)/20) def betaH(float v, float vr): return 1 / ( 1 + exp( -(v-vr-30)/10 ) ) def alphaN(float v, float vr): return 0.01 * (v-vr-10) / ( 1 - exp(-(v-vr-10)/10) ) def betaN(float v, float vr): return 0.125 * exp(-(v-vr)/80) ## steady-state values and time constants of m,h,n def m_infty(float v, float vr): return alphaM(v,vr) / ( alphaM(v,vr) + betaM(v,vr) ) def h_infty(float v, float vr): return alphaH(v,vr) / ( alphaH(v,vr) + betaH(v,vr) ) def n_infty(float v, float vr): return alphaN(v,vr) / ( …
downvote count: 0

http://stackoverflow.com/a/46864529
has comment: http://stackoverflow.com/comment/80676497
has comment: http://stackoverflow.com/comment/80676519
has comment: http://stackoverflow.com/comment/80676829
has comment: http://stackoverflow.com/comment/80676946
score: 0
has body: I was wondering if it is correct to think that this is equivalent to the init(self) function in Python? No. Just by looking at the structure of the statement you can understand. Indeed, self is a reference to the instance. Therefore, the instance must be constructed before __init__ is called. See this for more information (__new__ is actually what you're looking for) Same question for a C++ destructor method vs. Python _exit__(self) No. __exit__ only exit the Runtime context related to the object. In this case, what you are really looking for is __del__. See this, which clearly state: Called when the instance is about to be destroyed. This is also called a destructor.
has comment: http://stackoverflow.com/comment/80677368
has comment: http://stackoverflow.com/comment/80677221
type: Answer
answers question: http://stackoverflow.com/q/46864368

http://stackoverflow.com/comment/80626771
score: 3
comment on: http://stackoverflow.com/q/46839394
has text: It would appear that where you write to the csv you are writing `P` which is actually referencing the function `P()`, not the input which you assign to the variable `P` earlier. Using proper variable and function names would avoid this issue.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46860101
downvote count: 0
upvote count: 2
has body: You can group them and select the number you want for each value: data = df.loc[df['label'].isin([1,6])].groupby('label').head(500)
type: Answer
answers question: http://stackoverflow.com/q/46860038
score: 2

http://stackoverflow.com/comment/80620190
type: QuestionComment
has text: @DamianLattenero I think because `AAAAABAA` has one `B` while the latter has two.
comment on: http://stackoverflow.com/q/46835119
score: 0
type: Comment

http://stackoverflow.com/comment/80486153
score: 0
has text: By download I mean, when i give the input file in ffmpeg I should download the file from hdfs and give to ffmpeg, I'm trying to see if i can pipe the actual binary data to it. what do you think I should do? is there another tool?
comment on: http://stackoverflow.com/q/46769464
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80449924
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46750954
has text: Thanks Bruce, I just took a snapshot to provide some sample lines. There are many lines, and about 1000 files. I am trying the java xml approach you suggested. New to java, but I'll have a look. and If I can do it in python all the better. Thanks again.
score: 0

http://stackoverflow.com/comment/80482373
has text: Why is your accepted solution better than using a dict with dynamicallly generated keys? `alldat['Week{}'.format(i)]` and now there's no abomination in your code. You probably will need `eval`/`globals` _once_ if you want to change to a sane data model. But then bury this knowledge and use a dict/list.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46767597

http://stackoverflow.com/comment/80674572
comment on: http://stackoverflow.com/a/46863473
has text: @piRSquared Does `gt(0)` not already result in a bool mask? Also, welcome back :)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80571411
type: QuestionComment
score: 0
has text: Please post your desired output.
comment on: http://stackoverflow.com/q/46812096
type: Comment

http://stackoverflow.com/q/46822979
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80627820
has title: Uniformly random sampling
has answer: http://stackoverflow.com/a/46823252
has comment: http://stackoverflow.com/comment/80596314
type: Question
has answer: http://stackoverflow.com/a/46823319
has comment: http://stackoverflow.com/comment/80594653
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/80594298
tagged with: random
has comment: http://stackoverflow.com/comment/80607631
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/46836351
has body: My problem is as follows, I have 4 playing cards face down in front of me. There is a King, Queen, Jack, and Ace. I pick a card, look at it, then put it back face down in front of me. I'm trying to simulate picking 3 cards 1000 times (you can pick the same card multiple times) i.e. one sample of 3 can be Jack, Jack, and King. I've tried to do that here: import random cards=["King", "Queen", "Jack", "Ace"] for i in range(1000): print([random.sample(cards, 3)]) All this does is print out 1000 iterations of picking 3 cards, but it never picks the same card twice, which it should. What I wanna do is count how many times I pick 3 unique cards and then calculate the probability of doing so.Then I want to calculate the average number of different cards I pick each trial. I know it will help to add values to a list, but I'm not sure how to go about it. Apologize for formatting, I'm inexperienced.
has comment: http://stackoverflow.com/comment/80593297

http://stackoverflow.com/q/46862408
type: Question
has answer: http://stackoverflow.com/a/46862429
upvote count: 18
has answer: http://stackoverflow.com/a/46862762
has title: Python: Find count of the elements of one list in another list
linked to: http://stackoverflow.com/q/1964934
favorite count: 0
type: UnansweredQuestion
downvote count: 2
score: 16
has body: Let's say I have two lists list1 and list2 as: list1 = [ 3, 4, 7 ] list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ] I want to find the count of the elements of list1 which are present in list2. Expected output is 4 because 3 and 4 from list1 are appearing twice in list2. Hence, total count is as 4.
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46862440
has answer: http://stackoverflow.com/a/46862478

http://stackoverflow.com/a/46811042
has comment: http://stackoverflow.com/comment/80570519
score: 3
has comment: http://stackoverflow.com/comment/80571389
answers question: http://stackoverflow.com/q/46810875
has comment: http://stackoverflow.com/comment/80572270
downvote count: 0
type: Answer
has body: You can open all the files using a single context manager with contextlib.ExitStack (in Python 3) and then write to the output file after applying zip on the iterable of files: import csv from contextlib import ExitStack outfile = "CalculatedOutput/Opera.csv" with ExitStack() as stack, open(outfile, "w+") as to_file: # open all files fs = [stack.enter_context(open(fname)) for fname in files] fs = map(csv.reader, fs) # write all rows from all files csv.writer(to_file).writerows(zip(*fs)) Update: If the file contains characters that cannot be decoded to UTF-8 (the default encoding for open), you can use intermediate surrogate characters when reading, which are replaced with their original form at write time: with ExitStack() as stack, open(outfile, "w+", errors='surrogateescape') as to_file : fs = [stack.enter_context(open(fname, errors='surrogateescape')) for fname in files] ...
upvote count: 3

http://stackoverflow.com/a/46779731
has body: I'm going to assume you want to convert your last column into one hot concodings and then concat it to your original array. You can initialise an array of zeros, and then set the appropriate indices to 1. Finally concat the OHE array to your original. MCVE: print(arr) array([[ -9.95, 15.27, 9.08, 1. ], [ -6.81, 11.87, 8.38, 2. ], [ -3.02, 11.08, -8.5 , 1. ], [ -5.73, -2.29, -2.09, 2. ], [ -7.01, -0.9 , 12.91, 2. ], [-11.64, -10.3 , 2.09, 2. ], [ 17.85, 13.7 , 2.14, 0. ], [ 6.34, -9.49, -8.05, 2. ], [ 18.62, -9.43, -1.02, 1. ], [ -2.15, -23.65, -13.03, 1. ]]) c = arr[:, -1].astype(int) ohe = np.zeros((c.shape[0], c.max() + 1)) ohe[np.arange(c.shape[0]), c] = 1 arr = np.hstack((arr[:, :-1], ohe)) print(arr) array([[ -9.95, 15.27, 9.08, 0. , 1. , 0. ], [ -6.81, 11.87, 8.38, 0. , 0. , 1. ], [ -3.02, 11.08, -8.5 , 0. , 1. , 0. ], [ -5.73, -2.29, -2.09, 0. , 0. , 1. ], [ -7.01, -0.9 , 12.91, 0. , 0. , 1. ], [-11.64, -10.3 , 2.09, 0. , 0. , 1. ], [ 17.85, 13.7 , 2.14, 1. , 0. , 0. ], [ 6.34, -9.49, -8.05, 0. , 0. , 1. ], [ 18.62, -9.43, -1.02, 0. , 1. , 0. ], [ -2.15, -23.65, -13.03, 0. , 1. , 0. ]])
type: Answer
answers question: http://stackoverflow.com/q/46779666
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46779666
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80505866

http://stackoverflow.com/q/46847900
type: Question
has title: How to send message to HttpResponseRedirect in Django
answer count: 1
tagged with: django-rest-framework
score: 0
has body: I have added a middleware to a session-out user with my logic. I am trying to redirect to login page with a message. I am using HttpResponseRedirect(reverse('user_login')) for redirecting to my custom login page. So, how to pass values to a page?
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46847933

http://stackoverflow.com/q/46749124
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
has title: Handling Nested API Payload as JSON
score: 2
has answer: http://stackoverflow.com/a/78538980
type: UnansweredQuestion
favorite count: 0
has body: { "token_type": "bearer", "stripe_publishable_key": "{PUBLISHABLE_KEY}", "scope": "read_write", "livemode": false, "stripe_user_id": "{ACCOUNT_ID}", "refresh_token": "{REFRESH_TOKEN}", "access_token": "{ACCESS_TOKEN}", } I am working with a third party API using python requests and can grab stripe_user_id from the above JSON response using this: stripe_payload = json.loads(resp.text) stripe_user_id = stripe_payload['stripe_user_id'] How would I grab the api_token below when the JSON is returned as below with the extra "data" inserted in the JSON response? I tried this: timekit_api_token = timekit_payload['data':'api_token'] but got an error: unhashable type: 'slice' { "data": { "id": "d187d6e0-d6cb-409a-ae60-45a8fd0ec879", "first_name": "Emmet", "last_name": "Brown", "name": "Emmet Brown", "email": "doc.brown@timekit.io", "image": "http://www.link-to-img.com/image.png", "activated": false, "timezone": "America/Los_Angeles", "last_sync": null, "api_token": "nvHfRSlhvsnlg4rS7Wt28Ty47qdgegwSu3YK7hPW" } }
type: Question
has comment: http://stackoverflow.com/comment/80444803
tagged with: python
answer count: 1
upvote count: 3

http://stackoverflow.com/comment/80516646
type: Comment
type: QuestionComment
has text: I think you may need to do more research about network communication. The code showing in your question is exactly tcp connection but is a short connection. It will be closed after every requests and be established again before every requests. So it is very costly to repetitively send information. But if you establish a long connection, you just establish connection once and transform data during a long time and finally close the connection. It won't waste time on connection establishment.
comment on: http://stackoverflow.com/q/46784976
score: 0

http://stackoverflow.com/comment/80551181
type: Comment
has text: Just to be clear you don't have a linked list, you have a list of links ;)
comment on: http://stackoverflow.com/a/46782415
type: AnswerComment
score: 0

http://stackoverflow.com/a/46841492
type: Answer
answers question: http://stackoverflow.com/q/46841300
has body: Another choice is regex if you have more complicated input. For the case above, I recommend splitting lines using - and set the maxsplit parameter. final_list = ['UNIQUE-ID - ASN\n', 'UNIQUE-ID - D-GLT\n', 'UNIQUE-ID - 4-AMINO-BUTYRATE\n', 'UNIQUE-ID - CPD-8569\n', 'UNIQUE-ID - CPD-17095\n', 'UNIQUE-ID - CPD-17880\n', 'UNIQUE-ID - GLY\n', 'UNIQUE-ID - CPD-18298\n', 'UNIQUE-ID - D-SERINE\n', 'UNIQUE-ID - ACETYLCHOLINE\n', 'UNIQUE-ID - DOPAMINE\n', 'UNIQUE-ID - SEROTONIN\n', 'UNIQUE-ID - HISTAMINE\n', 'UNIQUE-ID - PHENYLETHYLAMINE\n', 'UNIQUE-ID - TYRAMINE\n', 'UNIQUE-ID - CPD-58\n', 'UNIQUE-ID - 1-4-HYDROXYPHENYL-2-METHYLAMINOETHAN\n', 'UNIQUE-ID - TRYPTAMINE\n'] just_compound_id = [] for line in final_list: line = line.rstrip() split_id = line.split('-', 2)[2].strip() just_compound_id.append(split_id) print(just_compound_id)
score: 0

http://stackoverflow.com/comment/80591781
comment on: http://stackoverflow.com/a/46803941
score: 0
type: AnswerComment
has text: Here's a full tutorial on file dialogs. https://pythonspot.com/en/pyqt5-file-dialog/ Please try searching for this material instead.
type: Comment

http://stackoverflow.com/q/46792087
has title: flask unit test "failed to establish a new connection"
favorite count: 0
has comment: http://stackoverflow.com/comment/80671638
has comment: http://stackoverflow.com/comment/80542900
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80605590
tagged with: python
tagged with: flask-testing
has comment: http://stackoverflow.com/comment/80534035
tagged with: python-unittest
tagged with: flask-restful
answer count: 1
has comment: http://stackoverflow.com/comment/80533412
has answer: http://stackoverflow.com/a/46829150
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80535391
tagged with: flask
has comment: http://stackoverflow.com/comment/80547123
has comment: http://stackoverflow.com/comment/80547214
has comment: http://stackoverflow.com/comment/80533993
has body: I am writting unit tests for a flask app. This app expose REST endpoints and uses the flask_restful lib. Basically, one of my endpoints will do requests to other endpoints and do some processing. While executing the tests through pytest, it returns this error (NOTE: this works when basically testing with curl) : requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=5000): Max retries exceeded with url: /ctrlm/H_INFOEXPLH:05u3v/output/ (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x0486D090&gt;: Failed to establish a new connection: [WinError 10061] Here is the test code : class RestTests(unittest.TestCase): """ Test the rest module. """ ############################ #### setup and teardown #### ############################ def setUp(self): """ Executed prior to each test """ app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config['THREADED'] = True self.client = app.test_client() # incident id: self.incident = "INC1863137" # ctrl-m job id : self.jobid_no_output = "server:0ceit" self.jobid_no_job = "server:0ceity" # job format that will surely fail! def tearDown(self): """ executed after each testexecuted after each test """ pass ############### #### tests #### ############### def test_ctrl_output(self): """ UAT 3 : ctrl-M job output is found. """ response = self.client.post('/servnow/incident/{}'.format(self.incident), data=json.dumps({'data': "This is just a json test"}), headers={'Content-Type': 'application/json'} ) #print("DEBUGGGG!!!!!!!!!!!!!!!!!!! ===============&gt; {}".format(response)) self.assertIsNotNone(response) Well, maybe the flask instance initiated with setUp() is not able to be threaded... On the app code, this is this code which create the issue : url = "http://127.0.0.1:5000{}".format( flask.url_for('joboutput', jobid=jobid)) resp = requests.get(url).json() Well, I just would like to execute a query to an url from flask... Probably, I'm d…
score: 2
has comment: http://stackoverflow.com/comment/80580860
downvote count: 0

http://stackoverflow.com/q/46759258
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/46759283
accepted answer: http://stackoverflow.com/a/46759283
type: AnsweredQuestion
score: -5
has body: I am stored the list of elements in the list and I would like to create a if statement so I can compare a string with the list to see if the element is not matched. Here is what I use: self.EPG_Channel = 'Channel 5' self.channel_str = ['BBC One, BBC Two, ITV, Channel 4, Channel 5'] I want to create something is like: if not self.EPG_Channel == self.channel_str: print "You are not in the last element in the list" else: print "You are in the list element in the list so let do nothing..." I want to know how do you create a if statement to check the elements in the list with a string to see if the element is not in the last element in the list?
has title: Check if the element is last in the list
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46759278
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/46759278
favorite count: 0
upvote count: 0

http://stackoverflow.com/comment/80590552
type: AnswerComment
comment on: http://stackoverflow.com/a/46821546
score: 0
type: Comment
has text: Thanks. Can you please take a look at why matrix `A`, as described under the edit, is not giving correct output as expected?

http://stackoverflow.com/comment/80572257
comment on: http://stackoverflow.com/q/46811800
has text: @Adrio, do you mean a bash script that installs the dependancies in the remote machine? I do not want to pip install anything on the remote machine. The remote machine may not even have access to pypi repository if it is behind a firewall.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80680292
comment on: http://stackoverflow.com/q/46866327
has text: Correct, and 4 is inside 3, and 3 is inside 1.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80668068
type: Comment
has text: I've been playing around with it and it seems particularly bad for the pseudo-inverse which is the one I cared about most...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46859873

http://stackoverflow.com/comment/80534576
type: Comment
comment on: http://stackoverflow.com/a/46792116
score: 0
type: AnswerComment
has text: Just one question. How did you identified that its encoding as 'cp1252'? Is there any method available for this?

http://stackoverflow.com/comment/80608665
has text: @SergeSoloshchenko I posted the regex based answer. Well, you may really do it the way you did, just using a `isalpha()` method.
score: 0
comment on: http://stackoverflow.com/q/46830435
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80573967
has text: You never reset i after looping once, which I'd think would be necessary. Surprised this doesn't throw an OOB exception. And what's `da`? Do you mean `row`?
comment on: http://stackoverflow.com/q/46813432
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46808615
accepted answer: http://stackoverflow.com/a/46810021
type: AnsweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/80564628
type: Question
has answer: http://stackoverflow.com/a/46810021
has comment: http://stackoverflow.com/comment/80565692
answer count: 3
downvote count: 0
score: 1
has body: Suppose a multiple depth dict {'definition': 'dirname', 'get': ['getatime', 'getctime', 'getmtime', 'getsize'], 'operation': ['join', {'split':['split', 'splitdrive', 'splitext']}, {'expand': ['expanduser', 'expandvars']}, ], } I tried to extract its items with a definded function. lst = [] def count_d(dt): global lst # global is unnecessary here if isinstance(dt, dict): for value in dt.values(): if isinstance(value, str): lst.append(value) else: count_d(value) elif isinstance(dt,list): for ele in dt: if isinstance(ele, str): lst.append(ele) else: count_d(ele) return lst The over_complicated recursive function solved the problem. Out[121]: ['dirname', 'getatime', 'getctime', 'getmtime', 'getsize', 'join', 'split', 'splitdrive', 'splitext', 'expanduser', 'expandvars'] What I am expecting is: lst = [] def count_d(dt): global lst for ele in dt: if isinstance(ele,str): lst.append(ele) or more abstract in one line without declaring variable and using global.
possible better answer: http://stackoverflow.com/a/46808732
favorite count: 0
has comment: http://stackoverflow.com/comment/80564800
has answer: http://stackoverflow.com/a/46808732
has title: Draw elements from a multiple depth dictionary
has answer: http://stackoverflow.com/a/46809133
tagged with: python

http://stackoverflow.com/comment/80749636
has text: @sati that doesn't sound like a good idea: now you have a bunch of modules in your working directory, and you'll get name clashes. Python should be able to pick up the modules from its site-packages directory if properly installed.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46901305
type: Comment

http://stackoverflow.com/comment/80581872
type: Comment
has text: @MatteoRagni It's a question hard to work with. Especially until one recognizes that ```np_array.cov()``` does not exist.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46817222

http://stackoverflow.com/q/46859242
favorite count: 0
has answer: http://stackoverflow.com/a/46860583
upvote count: 2
has body: I'm trying to scrape data from an HTML file. it looks like this: from bs4 import BeautifulSoup as bs import urllib redditPage1 = "http://redditlist.com/sfw" r=urllib.urlopen(redditPage1).read() soup = bs(r) Now I want to get the reddit moderators (or subredditors, as they are called) in a list by order of the number of their subscribers. For that I need to only look at the data that comes after the this line of code: Subscribers Everything before this line is irrelevant and all entries about the subredditors after this line look like this: 1 i funny 18,197,786 What should I do to be able to extract the subredditor names that come after this line and not before?
tagged with: web-scraping
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/46860583
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46859363
has title: How to scrape data in HTML file from a certain line onwards
type: Question
accepted answer: http://stackoverflow.com/a/46859363
has answer: http://stackoverflow.com/a/46859596
tagged with: beautifulsoup
answer count: 3
tagged with: http://stackoverflow.com/tag/html
score: 1

http://stackoverflow.com/q/46807597
tagged with: neural-network
tagged with: face-detection
answer count: 1
has title: face landmark detection with helen database
score: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46941369
downvote count: 1
tagged with: tensorflow
type: Question
has body: I'm going to use CNNs for face landmark detection.(python and tensorflow) The problem is images in Helen database have different scales. I think I cannot just resize or crop images because the data is the positions of images.((x,y) coordinates) however, I found a lot of papers(CNNs) tested their model with Helen dataset. Does anyone have idea how to deal with helen dataset? I really appreciate it.

http://stackoverflow.com/q/46817423
has comment: http://stackoverflow.com/comment/80582233
tagged with: python
has answer: http://stackoverflow.com/a/46817555
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46817555
has body: I'm making a noughts and crosses game in python, and I've forgotten how to have a variable within printed code. I know I can make my code more efficent by making the O and X parts merged but with the noughts and crosses board using variables to function. What I have currently done: for i in range (1,2): player = int(input("Select from either `O` [1] or `X` [2]: ")) while player &lt;0 or player &gt;2: print("You must only enter 1 for noughts, or 2 for crosses.") time.sleep (0.5) user = int(input("Select from either `O` [1] or `X` [2]: ")) else: if player==1: user="O" time.sleep (0.25) print("Player 1 has selected to be `O`.") #user has chosen to be noughts time.sleep (1) print(" ") time.sleep (0.5) print(" You can choose a square by entering in the co-ordinates of it. ") time.sleep (1.5) print(" EG: If you selected (2,1) and you were `O`, the grid would look like: ") time.sleep (1.5) print(" (x&gt;) [1] {2} [3]") print(" ┌-----------┐") print(" {1} | | O | |") print(" |---+---+---|") print(" [2] | | | |") print(" |---+---+---|") print(" [3] | | | |") print(" (y^) └-----------┘") print(" ") else: user="X" time.sleep (0.25) print("Player 1 has selected to be `X`.") #user has chosen to be crosses time.sleep (1) print(" ") time.sleep (0.5) print(" You can choose a square by entering in the co-ordinates of it. ") time.sleep (1.5) print(" EG: If you selected (2,1) and you were `X`, the grid would look like: ") time.sleep (1.5) print(" (x&gt;) [1] {2} [3]") print(" ┌-----------┐") print(" {1} | | X | |") print(" |---+---+---|") print(" [2] | | | |") print(" |---+---+---|") print(" [3] | | | |") print(" (y^) └-----------┘") print(" ") time.sleep(1.5) print("Tutorial over, time to play!") time.sleep(0.5) x_axis=float(input("Please enter the x-axis: ")) y_axis=float(input("Please enter the y-axis: ")) I think it works something like this, not correct, I know, please help! user=x print(" [3] | | {} | |".format{user}
has title: How do you have a variable inside of printed text, which was set earlier?
score: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

sorting
tags question: http://stackoverflow.com/q/46815504
tags question: http://stackoverflow.com/q/46835757
tags question: http://stackoverflow.com/q/46886865
tags question: http://stackoverflow.com/q/46892476
tags question: http://stackoverflow.com/q/46752489
tags question: http://stackoverflow.com/q/46825760
tags question: http://stackoverflow.com/q/46863568
tags question: http://stackoverflow.com/q/46890127
tags question: http://stackoverflow.com/q/46809337
type: Tag
tags question: http://stackoverflow.com/q/46800055
tags question: http://stackoverflow.com/q/46869502
tags question: http://stackoverflow.com/q/46789055
tags question: http://stackoverflow.com/q/46844233
tags question: http://stackoverflow.com/q/46787230
tag name: sorting
tags question: http://stackoverflow.com/q/46901669
tags question: http://stackoverflow.com/q/46770748
tags question: http://stackoverflow.com/q/46812446
tags question: http://stackoverflow.com/q/46773028
tags question: http://stackoverflow.com/q/46750670
tags question: http://stackoverflow.com/q/46885888
tags question: http://stackoverflow.com/q/46843740
tags question: http://stackoverflow.com/q/46808236
tags question: http://stackoverflow.com/q/46835119

http://stackoverflow.com/a/46776575
answers question: http://stackoverflow.com/q/46772953
score: 2
upvote count: 2
has body: Please refer to the example below for details. Example main.py from kivy.app import App from kivy.uix.button import Button from kivy.uix.spinner import Spinner class MyWidget(Spinner): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) self.create_spinner() def create_spinner(self): self.text = "Home" self.values = ("Home", "Work", "Other", "Custom") self.size_hint = (None, None) self.size = (100, 44) self.pos_hint = {"center_x": 0.5, "center_y": 0.5} self.bind(text=self.graphTypeSelected) def graphTypeSelected(self, spinner, text): print("Hola") btnPrueba = Button(text="Prueba") spinner.parent.add_widget(btnPrueba) # functionsLUT = {"Accelerometer": self.temperatureGraph, # "Temperature": self.temperatureGraph} # functionsLUT[text]() # # def temperatureGraph(self): # print("temperatureGraph called") class TestApp(App): title = "Kivy Spinner Demo" def build(self): return MyWidget() if __name__ == "__main__": TestApp().run() Output
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46772953
type: Answer

apache-zookeeper
tags question: http://stackoverflow.com/q/46774759
tag name: apache-zookeeper
type: Tag

http://stackoverflow.com/comment/80654164
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46853192
type: Comment
has text: @NickA - can you explain?

http://stackoverflow.com/comment/80611754
type: Comment
type: QuestionComment
score: 1
has text: or even `not password.islower()`
comment on: http://stackoverflow.com/q/46832129

http://stackoverflow.com/comment/80648418
has text: A good reason indeed, I didn't explain in detail but apparently the poster appreciates an easier explanation. Maybe now the poster has a better understanding of his issue thanks to my answer and now he will be more prepared for details like your answer.
type: Comment
comment on: http://stackoverflow.com/a/46846721
type: AnswerComment
score: 0

http://stackoverflow.com/a/46766354
type: Answer
answers question: http://stackoverflow.com/q/46766113
has comment: http://stackoverflow.com/comment/80479161
score: 0
has body: import re print([re.sub(r'[\n\r\t]', '', c) for c in list]) I think you may use regex

http://stackoverflow.com/comment/80530871
comment on: http://stackoverflow.com/q/46792186
type: QuestionComment
has text: `print x` means output `x` and then a new-line. `print x,` means output `x` and then a space.
score: 0
type: Comment

http://stackoverflow.com/a/46794353
has comment: http://stackoverflow.com/comment/80535426
upvote count: 1
downvote count: 0
has body: Sklearn uses prebuilt networks, so no. I also don't think it's possible in Keras, as it has prebuilt layers. It sure can be implemented in Tensorflow though. Note that in TF you can explicitly define layers. For example in this snippet you'd need to add normalization in line 25, namely you can divide output rows tf.nn.sigmoid(tf.matmul(X, w_1)) by appropriate norms of input rows (you can get them using tf.nn.l2_normalize with dim=1)
has comment: http://stackoverflow.com/comment/80536652
type: Answer
score: 1
answers question: http://stackoverflow.com/q/46793190
has comment: http://stackoverflow.com/comment/80536254

http://stackoverflow.com/comment/80681414
type: Comment
type: QuestionComment
has text: Could you please tell me the way? Because when you choose a custom range in Mozilla, corresponding csv file is not filled with those values
comment on: http://stackoverflow.com/q/46852584
score: 0

http://stackoverflow.com/comment/80467259
type: AnswerComment
comment on: http://stackoverflow.com/a/46760294
type: Comment
has text: The state column values have spaces as i extracted them from a json file and saved in dataframe. So wherever spaces are there, the logic shared by you does not work, If there are no spaces, it works perfectly. Could you please advise how can i remove spaces. Tried using strip function while storing values in State as df['Location'] = list(map(lambda t:t['user']['location'].strip(), data)) but get error that 'NoneType' object has no attribute 'strip'
score: 0

http://stackoverflow.com/q/46870889
linked to: http://stackoverflow.com/q/17138088
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80701483
has comment: http://stackoverflow.com/comment/80694175
has comment: http://stackoverflow.com/comment/80701527
has comment: http://stackoverflow.com/comment/80699290
type: Question
has comment: http://stackoverflow.com/comment/80700529
score: 0
tagged with: encoding
duplicate of: http://stackoverflow.com/q/17138088
has body: When trying to generate a xml using python code I get this error: ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters. Please help in completing my code. I basically have two questions. First code : Open python IDLE # -*- coding: cp1252 -*- def generatexmlfile(): from lxml import etree as ET page = ET.Element('Module') ET.tostring(page, xml_declaration=True) doc = ET.ElementTree(page) #headElt = ET.SubElement(page, 'head') headElt = ET.SubElement(page, 'TestCaseName', NAME="118_Function Sinitiation ", TCID="118", AUTOMATIONID="118_01") title = ET.SubElement(headElt, 'PAYMENT_value') input_string='Suspended|€ 2,000.00' cleaned_string = ''.join(c for c in input_string if valid_xml_char_ordinal(c)) title.text = cleaned_string outFile = open('D:\\python\\CreateXML\\homemade.xml', 'w') doc.write(outFile,xml_declaration=True,encoding='utf-8',method="xml") def valid_xml_char_ordinal(c): codepoint = ord(c) # conditions ordered by presumed frequency return ( 0x20 &lt;= codepoint &lt;= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 &lt;= codepoint &lt;= 0xFFFD or 0x10000 &lt;= codepoint &lt;= 0x10FFFF ) generatexmlfile() The questions are: The IDLE does not allow me to save unless # -*- coding: cp1252 -*- is added. what is # -*- coding: cp1252 -*- ? The € character in the code causes the problem. Please let me know how to handle it and complete the xml generation
tagged with: unicode
has comment: http://stackoverflow.com/comment/80700481
tagged with: lxml
has title: Python-LXML : ValueError: All strings must be XML compatible
tagged with: python

http://stackoverflow.com/comment/80675415
type: AnswerComment
type: Comment
has text: As I explained, the iteration is being performed by `ProcessPoolExecutor.map()`. This is basically equivalent to: `for item in list_to_process: calculation(item)`, except that `calculation` may be called in a difference process for each item.
comment on: http://stackoverflow.com/a/46863986
score: 0

http://stackoverflow.com/q/46800307
has comment: http://stackoverflow.com/comment/80547558
favorite count: 0
tagged with: parsing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80547542
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80550724
upvote count: 1
has title: Slow file parsing when using .split()
has comment: http://stackoverflow.com/comment/80552864
has body: with open(file, 'r') as h: f = h.readlines() for line in f: a = line.split()[-7] if a in dict: dict[a] += line else: dict[a] = line I found a lot of questions on here about parsing files but none about the speed of the parse. Most people were looking for "how to parse file" and "how to collect x from file" and the answers were usually something like my example above. Im looking for any way to speed this up. Parsing a 30MB files with 276,000 lines will take ~50 minutes with the above process. If I take the split out of the process then it finishes in less than 1 second. Knowing that im always looking for the same index on every line, is it possible to do this any faster?
type: Question
has comment: http://stackoverflow.com/comment/80576673
downvote count: 0
has comment: http://stackoverflow.com/comment/80575058
has comment: http://stackoverflow.com/comment/80547540
has comment: http://stackoverflow.com/comment/80552880
has comment: http://stackoverflow.com/comment/80548494
has comment: http://stackoverflow.com/comment/80569428
tagged with: python
score: 1

http://stackoverflow.com/q/46875814
favorite count: 0
tagged with: oracle-database
linked to: http://stackoverflow.com/q/10382838
tagged with: python
possible better answer: http://stackoverflow.com/a/46875964
has answer: http://stackoverflow.com/a/46880637
upvote count: 1
tagged with: django
has body: New to using Django over here. I am trying to create a DJango form that will save data to the database. To do this, I am using CreateView When calling the URL that is to "do the work", I have it set up as follows (so, a parameter is being passed in as well) url(r'^owner/contacts/add/(?P<tenantid>[0-9]+)/$', views.MstrstoreheadcontactCreateView.as_view(), name='owner-contact-add'), Problem: When trying to save data to the DB, I get an error that seems to be due to some fields not being set properly the exact error message I am getting is: The above exception (ORA-02291: integrity constraint (ORAAPPS.SYS_C009216) violated - parent key not found) was the direct cause This is how the Model is defined: class Mstrstoreheadcontact(models.Model): tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True) contactid = models.BigIntegerField(primary_key=True) genderid = models.BigIntegerField(blank=True, null=True) firstname = models.CharField(max_length=20, blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) officephoneno = models.CharField(max_length=20, blank=True, null=True) cellphoneno = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrStoreHeadContact' it was created using the inspectdb option (used to auto-generate classes for tables that already exist in a database) This is how the CreateView is being defined in views.py class MstrstoreheadcontactCreateView( CreateView ): model = Mstrstoreheadcontact fields = [ 'firstname', 'lastname', 'officephoneno', 'cellphoneno'] def form_valid(self, form): self.kwargs['tenantid'] = 10 # returning rendered page super(MstrstoreheadcontactCreateView, self).form_valid(form) return render(self.request, self.template_name, self.get_context_data(form=form)) def get_context_data(self, **kwargs): ctx = super(MstrstoreheadcontactCreateView, self).get_context_data(**kwargs) ctx['tenantid'] = self.kwargs['t…
has title: DJango CreateView not setting attributes before data is saved to the DB
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/46875964
type: Question
linked to: http://stackoverflow.com/q/16079299
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/46880637

http://stackoverflow.com/comment/80466888
comment on: http://stackoverflow.com/q/46760771
has text: While originality is nice, remember, this is a kid friendly website ;-(
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/80509390
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46763985
type: Comment
has text: Thanks @DomJack. I'll definitely check it out. I've found it very counter-intuitive to debug Tensorflow code sometimes.

http://stackoverflow.com/q/46755423
tagged with: web
favorite count: 0
has body: I got a a Database with a few columns. I want to add to my search the option to search not only one column like Project. I want to search a few more columns too.. so the search will look for Project or ServerName or IP and search all of the columns or a few of them. I tried (Project__icontains=query, ServerName__icontains=query) but it said wrong syntax. index.html: def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Project__icontains=query) else: posts = serverlist.objects.all() # else: models.py: from django.db import models class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30)
tagged with: python
accepted answer: http://stackoverflow.com/a/46755468
type: AnsweredQuestion
tagged with: mysql
tagged with: django
upvote count: 1
type: Question
score: 1
tagged with: database
has title: Searching a few columns in Django
has answer: http://stackoverflow.com/a/46755468
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47007176
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46899905
type: Answer
answers question: http://stackoverflow.com/q/46899905
downvote count: 0
score: 1
has body: As I discovered, HTTP cookies are not separated by ports on the same host. So I had project A (the OAuth2 client) running on localhost:8000 and project B (the OAuth2 server) running on localhost:8001. Django's sessionid Cookie was getting overridden during the auth process, which caused this error. The solution is to run the OAuth2 server on a different host (I just made an entry in /private/etc/hosts on macOS that looks like: 127.0.0.1 id.localhost and updated SOCIAL_AUTH_CUSTOM_BACKEND_URL to http://id.localhost:8001.

tuples
tags question: http://stackoverflow.com/q/46798652
tags question: http://stackoverflow.com/q/46820094
tags question: http://stackoverflow.com/q/46878559
tags question: http://stackoverflow.com/q/46870075
tags question: http://stackoverflow.com/q/46842412
tags question: http://stackoverflow.com/q/46779821
tags question: http://stackoverflow.com/q/46891727
tags question: http://stackoverflow.com/q/46764778
tags question: http://stackoverflow.com/q/46829577
tags question: http://stackoverflow.com/q/46770709
tags question: http://stackoverflow.com/q/46903261
tags question: http://stackoverflow.com/q/46876034
tag name: tuples
tags question: http://stackoverflow.com/q/46809120
tags question: http://stackoverflow.com/q/46786664
tags question: http://stackoverflow.com/q/46869112
tags question: http://stackoverflow.com/q/46774105
tags question: http://stackoverflow.com/q/46880434
tags question: http://stackoverflow.com/q/46867481
tags question: http://stackoverflow.com/q/46749181
type: Tag
tags question: http://stackoverflow.com/q/46777086
tags question: http://stackoverflow.com/q/46765997

http://stackoverflow.com/comment/80459071
type: QuestionComment
comment on: http://stackoverflow.com/q/46756719
score: 0
type: Comment
has text: @wwii, I'm sorry I do not think the official doc discusses anything about store sparse list. Please detail if you think there's any.

http://stackoverflow.com/comment/80646640
score: 0
has text: The Python boolean or operator is `or`, not `||`.
comment on: http://stackoverflow.com/q/46849668
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46829432
has comment: http://stackoverflow.com/comment/80606440
upvote count: 1
downvote count: 0
has body: From the experience of previous similar questions, you should try to convert your JSON (well, actually, your Python list of dicts) in product_list to a string representation of that same JSON before posting: import requests import json payload = { "access_token": "123abc", "product_total": 2, "product_list": json.dumps([ { "product_id": 111, ... }, { "product_id": 222, ... }]) } r = requests.post(url, data=payload, verify=False) r.text
type: Answer
answers question: http://stackoverflow.com/q/46800101
has comment: http://stackoverflow.com/comment/80606716
has comment: http://stackoverflow.com/comment/80606360
score: 1

http://stackoverflow.com/comment/80466939
comment on: http://stackoverflow.com/q/46760626
score: 0
has text: Cheers I know what min and max are so I’ll read up on the other things thank you
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46860908
has comment: http://stackoverflow.com/comment/80669300
favorite count: 0
has title: Concatenate two strings with a common substring?
type: Question
has comment: http://stackoverflow.com/comment/80669410
possible better answer: http://stackoverflow.com/a/46861071
has answer: http://stackoverflow.com/a/46861094
tagged with: python
has answer: http://stackoverflow.com/a/46861205
score: 4
has answer: http://stackoverflow.com/a/46861106
has answer: http://stackoverflow.com/a/46862123
has comment: http://stackoverflow.com/comment/80669356
has comment: http://stackoverflow.com/comment/80669445
linked to: http://stackoverflow.com/q/7794208
has body: Say I have strings, string1 = 'Hello how are you' string2 = 'are you doing now?' The result should be something like Hello how are you doing now? I was thinking different ways using re and string search. (Longest common substring problem) But is there any simple way (or library) that does this in python? To make things clear i'll add one more set of test strings! string1 = 'This is a nice ACADEMY' string2 = 'DEMY you know!' the result would be!, 'This is a nice ACADEMY you know!'
answer count: 5
has comment: http://stackoverflow.com/comment/102091206
accepted answer: http://stackoverflow.com/a/46861106
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80669385
downvote count: 0
has answer: http://stackoverflow.com/a/46861071
tagged with: string

http://stackoverflow.com/q/46860234
tagged with: indexing
tagged with: list
has answer: http://stackoverflow.com/a/46871268
tagged with: loops
has title: Loop through list to find element and add total of price based on that element?
type: Question
has comment: http://stackoverflow.com/comment/80668095
answer count: 2
has comment: http://stackoverflow.com/comment/80668199
has comment: http://stackoverflow.com/comment/80668234
score: 0
has comment: http://stackoverflow.com/comment/80668324
has comment: http://stackoverflow.com/comment/80668172
type: UnansweredQuestion
tagged with: python
has body: I want to be able to loop through a list to find matches of elements within the list that is written to file and add the total of prices given for the element in the list. Here is what I have so far - just don't know how to find matches of elements and add. - E.g. your expense name lists might contain multiple entries called "junk food" and for each there will be a corresponding priceList entry for its cost. def expensesManager(): filePath=pickAFile() file=open(filePath,"w") numExpenses=requestInteger("How many weekly expenses do you currently have?") expensePriceList=[None]*numExpenses expenseNameList=[None]*numExpenses index=0 total=0 while(index&lt;numExpenses): expenseNameList[index]=requestString("Name of Expense "+str(index+1)) expensePriceList[index]=requestNumber("Price of "+ str(expenseNameList[index].capitalize())+" per week") lineList=(expenseNameList[index].capitalize()+" "+str(expensePriceList[index])+"\n") total=expensePriceList[index] print "Your total expenditure on "+str(expenseNameList[index]).capitalize()+ " per month is $"+str((total)*4) file.writelines(lineList) index=index+1 file.close()
has answer: http://stackoverflow.com/a/46860646

http://stackoverflow.com/comment/81069365
score: 0
type: Comment
type: QuestionComment
has text: Another follow up question. I've been suggested multiple times to just change the interval to say, `[-5,5]`. However, now my question is, why doesn't the opposite issue arise and then instead of `1.0+eps = 1.0` that we get `1.0+big_number = NaN`? if `big_number = number^30`? Like why do numerical issue seem to be more sensitive when raising to the power of 30 a number with magnitude less than 1?
comment on: http://stackoverflow.com/q/46859839

http://stackoverflow.com/q/46880929
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46880973
has answer: http://stackoverflow.com/a/46880983
has answer: http://stackoverflow.com/a/46880951
has body: I am a new coder, sorry if my question is bad or I am not following proper etiquette! I am designing a basic program that rolls dice. It is supposed to roll dice until the total points of either the computer or the user equals 100. However, even though my point totaler is working, the loop won't end. Anyone know why this is? Thank you! def main(): GAME_END_POINTS = 100 COMPUTER_HOLD = 10 is_user_turn = True user_pt = 0 computer_pt = 0 welcome() while computer_pt &lt; GAME_END_POINTS or user_pt &lt; GAME_END_POINTS: print_current_player(is_user_turn) if is_user_turn is True: user_pt = user_pt + take_turn(is_user_turn, COMPUTER_HOLD) elif is_user_turn is False: computer_pt = computer_pt + take_turn(is_user_turn, COMPUTER_HOLD) report_points(user_pt, computer_pt) is_user_turn = get_next_player(is_user_turn)
type: Question
has answer: http://stackoverflow.com/a/46880973
has title: My "while loop" not working as expected
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80709196
favorite count: 0
has comment: http://stackoverflow.com/comment/80709294
has comment: http://stackoverflow.com/comment/80709218
tagged with: python
accepted answer: http://stackoverflow.com/a/46880951

http://stackoverflow.com/q/46761927
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/46762125
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/46761963
has body: If I have a csv data that gives two row values of: years grades 2001 98 2001 75 2008 100 2003 57 2008 50 I have more values but I will try to explain what I am trying to get here. I want to get the average for each year. For instance, for 2001, the answer would be (98+75)/(# of counts 2001, which is 2 in this case). def construct_values(filing): """ Parameters ---------- Returns ------- years: array of integers average_grades: array of floats """ years, average_grades = [], [] grades = [] with open('grades.csv', 'r') as filing: next(filing) for row in file_path: year, grade = (s.strip() for s in row.split(',')) years.append(year) grades.append(grade) return years, average_grades What I did was just to get two arrays of years and grades. I don't know how to get average arrays and then print out like: 2001, 88.5555 for instance if 88.555 is average. Instead of being them as dictionaries, what I want to have are two arrays that will just return together.
linked to: http://stackoverflow.com/q/35866205
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: How to get an average from a row then make a list out of it
type: Question
duplicate of: http://stackoverflow.com/q/35866205

http://stackoverflow.com/q/46755168
tagged with: tensor
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: Tensorflow : Update Certain Tensor Indices On a Condition
tagged with: tensorflow
type: Question
has body: I am using Tensorflow and I want to apply the condition below to my tensor: if(value &gt; 0): value = log(value) else: value = -log(-value) Currently, I am doing the following. minone = tf.constant(-1, dtype=tf.float32) condition = tf.less(X, minone) idx = tf.where(condition) portion = tf.gather_nd(X, idx) log = -tf.log(-portion) X = tf.scatter_nd_update(X, idx, log) However, this only works when X is of type tf.Variable and not of a normal Tensor type. How would I achieve a working condition for a variable of Tensor type?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46755278

http://stackoverflow.com/comment/80747109
type: Comment
type: QuestionComment
has text: Can you...move all the monkeypatching into methods that can themselves be monkeypatched during the unit testing? What exactly is the desired behavior here? Presumably you *do* want to unit test your per-customer customizations, in which case you *would* want a monkeypatch operation to persist across all the unit tests? Or not?
score: 0
comment on: http://stackoverflow.com/q/46899708

http://stackoverflow.com/a/56108687
upvote count: 2
answers question: http://stackoverflow.com/q/46902367
has body: this problem arises when we use vectors in place of scalars for example in a for loop the range should be a scalar, in case you have given a vector in that place you get error. So to avoid the problem use the length of the vector you have used
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/46786660
has answer: http://stackoverflow.com/a/46786793
type: Question
score: 0
has title: In PyParsing, remove all quotes from the parsed result
answer count: 1
favorite count: 0
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: pyparsing
has body: I'd like to parse a string which is a comma-separated list of double-quoted strings. At first (after from pyparsing import *) I tried this: In [36]: expression = delimitedList(dblQuotedString, delim=",") In [37]: expression.parseString('"foo","bar"') Out[37]: (['"foo"', '"bar"'], {}) This generates the expected matches, but doesn't remove the quotes. So I tried adding an addParseAction(removeQuotes): In [34]: expression = delimitedList(dblQuotedString, delim=",").addParseAction(r ...: emoveQuotes) In [35]: expression.parseString('"foo","bar"') Out[35]: (['foo'], {}) This removes the quotes on 'foo', but now the 'bar' result is missing. How can I make the expression such that the result is (['foo', 'bar'], {})?

multithreading
tags question: http://stackoverflow.com/q/46827674
tags question: http://stackoverflow.com/q/46773577
tags question: http://stackoverflow.com/q/46772252
tags question: http://stackoverflow.com/q/46870707
tags question: http://stackoverflow.com/q/46772858
tags question: http://stackoverflow.com/q/46865429
type: Tag
tags question: http://stackoverflow.com/q/46751725
tags question: http://stackoverflow.com/q/46851963
tags question: http://stackoverflow.com/q/46779121
tags question: http://stackoverflow.com/q/46784355
tags question: http://stackoverflow.com/q/46832024
tags question: http://stackoverflow.com/q/46901633
tags question: http://stackoverflow.com/q/46789093
tags question: http://stackoverflow.com/q/46831801
tags question: http://stackoverflow.com/q/46899021
tags question: http://stackoverflow.com/q/46774295
tags question: http://stackoverflow.com/q/46840764
tags question: http://stackoverflow.com/q/46773650
tags question: http://stackoverflow.com/q/46879926
tags question: http://stackoverflow.com/q/46778712
tags question: http://stackoverflow.com/q/46788776
tags question: http://stackoverflow.com/q/46860663
tags question: http://stackoverflow.com/q/46850706
tags question: http://stackoverflow.com/q/46854555
tags question: http://stackoverflow.com/q/46846475
tags question: http://stackoverflow.com/q/46780981
tags question: http://stackoverflow.com/q/46842346
tags question: http://stackoverflow.com/q/46751804
tags question: http://stackoverflow.com/q/46842479
tags question: http://stackoverflow.com/q/46754524
tags question: http://stackoverflow.com/q/46841364
tags question: http://stackoverflow.com/q/46802272
tags question: http://stackoverflow.com/q/46846870
tag name: multithreading
tags question: http://stackoverflow.com/q/46852269
tags question: http://stackoverflow.com/q/46775912
tags question: http://stackoverflow.com/q/46878848

http://stackoverflow.com/q/46793110
upvote count: 4
has body: I want to apply a voting classifier to several pipeline classifiers and tune the parameters in a grid search. Following minimal example gives me an error. Do I have to do this differently? from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import VotingClassifier p1 = Pipeline('clf1', RandomForestClassifier()) p2 = Pipeline('clf2', AdaBoostClassifier()) p3 = Pipeline('clf3', VotingClassifier(estimators=(p1, p2))) p3.get_params() Error: TypeError: cannot convert dictionary update sequence element #0 to a sequence
answer count: 1
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/46793305
favorite count: 0
has title: Using VotingClassifier in Sklearn Pipeline
tagged with: python
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/46793305
type: AnsweredQuestion
score: 4

http://stackoverflow.com/comment/80675046
has text: Not `piR-esque` he cares too much about speed. It will take toooo much time if df exceeds 1000 rows.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46863741
type: Comment

http://stackoverflow.com/comment/80621354
score: 1
has text: Looking more closely at the filename that fails, I see there's a `?` in it. I thought maybe that was an indication of an improperly encoded character, but now I realize that it's really a literal question mark. That makes it an invalid filename. See https://stackoverflow.com/questions/1033424/how-to-remove-bad-path-characters-in-python
type: QuestionComment
comment on: http://stackoverflow.com/q/46834036
type: Comment

http://stackoverflow.com/comment/80628810
type: Comment
has text: Then wouldn't casting the `PyObject` to `Key` and assigning the external structure pointer to `inner` member work? (e.g. `((Key*)keyInstancePyObject)->inner = externalInnerStructPointer`) work? Is it required to use that external pointer (or you can create another one and populate its member with values from the external one)? I'm afraid I'm still missing something, or it could be an _XY_ problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/46839642
score: 0

http://stackoverflow.com/comment/80576604
type: AnswerComment
score: 0
type: Comment
has text: thats exactly what I did. Thanks jezrael!
comment on: http://stackoverflow.com/a/46807741

http://stackoverflow.com/comment/80687020
score: 0
has text: Is it the string "zero" or the number 0?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46869884

http://stackoverflow.com/comment/80542392
type: QuestionComment
has text: It means you need to configure your server so that it knows how to run Python scripts.
comment on: http://stackoverflow.com/q/46797693
type: Comment
score: 0

http://stackoverflow.com/comment/80623055
comment on: http://stackoverflow.com/a/46819814
type: AnswerComment
score: 0
type: Comment
has text: I have marked another response as the answer, because while this response is correct, it does not address the root issue, and doesn't instruct one on how to fix it. Thanks for your time though!

http://stackoverflow.com/a/54189508
score: 5
has body: The str.get_dummies function does not accept prefix parameter, but you can rename the column names of the returned dummy DataFrame: data['col'].str.get_dummies(sep=',').rename(lambda x: 'col_' + x, axis='columns')
upvote count: 5
answers question: http://stackoverflow.com/q/46867201
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80567150
comment on: http://stackoverflow.com/a/46809479
score: 0
type: AnswerComment
has text: Happens to the best ;). Glad I could help.
type: Comment

http://stackoverflow.com/comment/80668201
type: Comment
has text: also, is this a language dependent issue? would it still occur in Matlab for example?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46859873

http://stackoverflow.com/a/46756271
has comment: http://stackoverflow.com/comment/80457864
upvote count: 1
answers question: http://stackoverflow.com/q/46756214
accepted answer of: http://stackoverflow.com/q/46756214
has comment: http://stackoverflow.com/comment/80458038
type: AcceptedAnswer
downvote count: 0
has body: You can use re.findall() and format the user input into the pattern: import re word = ... with open("months.txt") as f: count = sum(len(re.findall(r'\b{}\b'.format(word), line)) for line in f) \b marks a word boundary in the regular expression: &gt;&gt;&gt; word = 'Apple' &gt;&gt;&gt; len(re.findall(r'\b{}\b'.format(word), "Apple. or Apple? or +Apple- Applepie")) 3
type: Answer
score: 1

http://stackoverflow.com/comment/80754276
comment on: http://stackoverflow.com/a/46903739
score: 0
type: AnswerComment
has text: You must be missing something. I've tried this code with all of the items as boolean, and it worked. Wait, I updated it to match class instance
type: Comment

http://stackoverflow.com/q/46828437
upvote count: 1
has answer: http://stackoverflow.com/a/47715516
type: Question
has body: When debugging manipulations of large np-arrays with PyCharm I have encountered the problem that there is no quick way to check the shape of the array as hoovering the mouse over a variable shows only the first and last three elements: Is there a way to show 500 x 1000 x 4 x 45 instead? Pressing ctrl+F1 and scrolling to the shape property becomes a bit tiresome after a while ...
score: 1
answer count: 1
downvote count: 0
has title: Python: PyCharm show "shape" by "mouse over"
tagged with: python
favorite count: 0
tagged with: pycharm
type: UnansweredQuestion

http://stackoverflow.com/q/46802777
favorite count: 0
has title: Where is the best place to run a Python script in AWS?
upvote count: 3
has comment: http://stackoverflow.com/comment/80574285
answer count: 3
has comment: http://stackoverflow.com/comment/80552734
has answer: http://stackoverflow.com/a/46803933
tagged with: amazon-elastic-beanstalk
has answer: http://stackoverflow.com/a/46802922
has body: I am fairly new using AWS and I need to run a batch process (daily ) and store the data in a MySQL database. It would take approximately 30 minutes for extraction and transformation. As a side note, I need to run pandas. I was reading that lambda functions are limited to 5 minutes. http://docs.aws.amazon.com/lambda/latest/dg/limits.html I was thinking of using an EC2 micro instance with Ubuntu or an Elastic Beanstalk instance. And Amazon RDS for a MySQL DB. Am I on the right path? Where is the best place to run my python code in AWS?
tagged with: python
has answer: http://stackoverflow.com/a/46814173
accepted answer: http://stackoverflow.com/a/46814173
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: mysql
type: Question
possible better answer: http://stackoverflow.com/a/46802922
tagged with: amazon-ec2
tagged with: amazon-web-services

http://stackoverflow.com/q/46788266
tagged with: http://stackoverflow.com/tag/r
has title: Run python from R via system command
has comment: http://stackoverflow.com/comment/80523148
has body: I want to execute python code from R via the system2 function, which invokes a command line. Here is an example: mcar = R6::R6Class( public = list( initialize = function() { system2("python -c", "import gym; env = gym.make('MountainCar-v0')") }, reset = function() { system2("python -c", "env.reset()") } getActionSpace = function() { system2("python -c", "env.action_space") } ) ) a = mcar$new() a$reset() a$getActionSpace() a = mcar$new() should create the gym environment and then it should be possible to call a$reset() or a$getActionSpace(). Because I do not know in advance in which order reset and getActionSpace will be called, I cannot just write a python script and call this, e.g. import gym env = gym.make('MountainCar-v0') env.reset() env.action_space But system2("python -c", "import gym; env = gym.make('MountainCar-v0')") returns an error: running command '"python -c" import gym; env = gym.make('MountainCar-v0')' had status 127
favorite count: 0
tagged with: command-line
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80522853
downvote count: 1
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/80522773
answer count: 1
has answer: http://stackoverflow.com/a/46788794

http://stackoverflow.com/comment/80655975
has text: IOError: [Errno 2] No such file or directory: 'H:\\XMLConverter\\XML_TXT\\MVM.txt'
comment on: http://stackoverflow.com/a/46853628
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46899946
favorite count: 0
has comment: http://stackoverflow.com/comment/80747086
accepted answer: http://stackoverflow.com/a/46899983
answer count: 4
has title: Access class variables from another class
tagged with: python-3.x
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46899981
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/46900002
has answer: http://stackoverflow.com/a/46899988
type: Question
has answer: http://stackoverflow.com/a/46899983
possible better answer: http://stackoverflow.com/a/46899988
has body: I have a simple class A that gets the name from users. class A: def __init__(self, name = ''): self.name = name Then I want to create a class B that prints out this name. I tried: class B: def print_name(printing_name = A.name): print(printing_name) Then I call these methods: m1 = A("x") B.print_name(m1) This returns the error Traceback (most recent call last): File "so.py", line 5, in &lt;module&gt; class B: File "so.py", line 7, in B def print_name(printing_name = A.name): AttributeError: class A has no attribute 'name' I know that I did not assign a class variable in the class A, and thus the name attribute goes with specific instances, not the entire class. However, the name attribute has to connect with every specific instance because it changes from the case to case. Then how should I get this name in class B?
downvote count: 0

http://stackoverflow.com/q/46886767
favorite count: 0
has body: How can I calculate the pitch of a micro bit accelerometer as a full range, i.e. from -Pi to Pi radians (the same as -180 to 180 degrees)? Here is my existing micro python code: while True: x = accelerometer.get_x()/1024 y = accelerometer.get_y()/1024 z = accelerometer.get_z()/1024 roll = math.pi-(math.atan2(x, z)%(math.pi*2)) pitch = math.atan2(-y, math.sqrt(x*x + z*z)) print('{roll:'+str(roll)+',pitch:'+str(pitch)+'}') The behaviour I see is: (Correct for me) Rolling the micro bit goes from 0 up to Pi to the right (until upside down) and from 0 down to -Pi rolling to the left (until upside down). At upside down, the radians will flip between Pi and -Pi. (incorrect for me) Pitching the micro bit forwards goes from 0 to Pi/2 (at 90 degrees) and then back down to 0 (upside down), pitching the micro bit backwards similarly goes from 0 down to -Pi/2 (at 90 degrees) then back up to 0 (when upside down). I am looking for the pitch to go forwards from 0 to Pi (when upside down) and backwards from 0 to -Pi (when upside down). Thank you in advance Andy
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80728182
has comment: http://stackoverflow.com/comment/80727431
score: 3
answer count: 0
upvote count: 3
tagged with: pitch
type: Question
tagged with: accelerometer
tagged with: bbc-microbit
has comment: http://stackoverflow.com/comment/80727878
downvote count: 0
has title: micro:bit how to calculate pitch in range -Pi to Pi

http://stackoverflow.com/q/46807403
tagged with: svm
has answer: http://stackoverflow.com/a/46808198
tagged with: numpy
linked to: http://stackoverflow.com/q/46910328
answer count: 3
has answer: http://stackoverflow.com/a/46809413
downvote count: 0
possible better answer: http://stackoverflow.com/a/46808198
favorite count: 0
tagged with: python
has body: I need to deploy an SVM in a C++ build target system. Therefore I want to train an SVM using dlib with python/numpy, serialize it and evaluate in the target system. The python documentation for dlib is rather obscure to me, so can anyone help me with this minimal example? import dlib # My data in numpy feature_column_1 = np.array([-1, -2, -3, 1, 2, 3]) feature_column_2 = np.array([1, 2, 3, -1, -2, -3]) labels = np.array([True, True, True, False, False, False]) # Features feature_vectors = dlib.vectors() for feature_column in [feature_column_1, feature_column_2]: feature_vectors.append(dlib.vector(feature_column.tolist())) # Labels labels_array = dlib.array(labels.tolist()) # Train svm = dlib.svm_c_trainer_linear() svm.train(feature_vectors, labels_array) # Test y_probibilities = svm.predict(labels_array_new) I get following error for the training: ---&gt; 18 svm.train(vectors, array) ValueError: Invalid inputs
accepted answer: http://stackoverflow.com/a/46809413
tagged with: dlib
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/46808316
tagged with: machine-learning
has title: Minimal Example for dlib SVM using Python/Numpy
type: Question
score: 3

http://stackoverflow.com/q/46861252
has answer: http://stackoverflow.com/a/46862884
score: 10
has title: Django DRF - What's the use of serializers?
has comment: http://stackoverflow.com/comment/80670298
type: Question
has comment: http://stackoverflow.com/comment/80671414
has answer: http://stackoverflow.com/a/47852943
has comment: http://stackoverflow.com/comment/80670489
has body: I've been using Django for over 3 years now, but have never felt the need to use DRF. However, seeing the growing popularity of DRF, I thought of giving it a try. Serializing is the concept I find it most difficult. Consider for eg:- I want to save user details. Following is the user related models. class Users(models.Model): GENDER_CHOICES = ( ('M', 'MALE'), ('F', 'FEMALE'), ('O', 'OTHERS'), ) first_name = models.CharField(max_length=255, blank=True, null=True) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=1, blank=True, null=True) class UserAddress(models.Model): ADDRESS_TYPE_CHOICES = ( ('P', 'Permanent'), ('Cu', 'Current'), ('Co', 'Correspondence') ) line1 = models.CharField(max_length=255) line2 = models.CharField(max_length=255, blank=True, null=True) pincode = models.IntegerField() address_type = models.CharField(choices=ADDRESS_TYPE_CHOICES, max_length=255) user_id = models.ForeignKey(Users, related_name='uaddress') class UserPhone(models.Model): phone = models.CharField(max_length=10) user_id = models.ForeignKey(Users, related_name='uphone') class UserPastProfession(models.Model): profession = models.CharField(max_length=10) # BusinessMan, software Engineer, Artist etc. user_id = models.ForeignKey(Users, related_name='uprofession') I'm getting all the user details bundled in one POST endpoint. { 'first_name': 'first_name', 'middle_name': 'middle_name', 'last_name': 'last_name', 'gender': 'gender', 'address': [{ 'line1': 'line1', 'line2': 'line2', 'address_type': 'address_type', }], 'phone': ['phone1', 'phone2'], 'profession': ['BusinessMan', 'Software Engineer', 'Artist'] } Without using DRF, I would have made a Users object first, linking it with UserAddress, UserPhone and UserPastProfession object. How the same could be done using DRF? I mean validating, serializing, and then saving the details. How seria…
downvote count: 0
has answer: http://stackoverflow.com/a/51679617
has comment: http://stackoverflow.com/comment/80670574
tagged with: django-rest-framework
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/80670230
upvote count: 10
has comment: http://stackoverflow.com/comment/80670059
tagged with: python
has comment: http://stackoverflow.com/comment/80670115
has comment: http://stackoverflow.com/comment/80669893
has comment: http://stackoverflow.com/comment/80671476
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80670025
tagged with: django
has comment: http://stackoverflow.com/comment/80669977

http://stackoverflow.com/comment/80447489
score: 0
type: AnswerComment
has text: Because `'i'` is not an integer. As you said, "there are no strings, no division by zero".
comment on: http://stackoverflow.com/a/46750565
type: Comment

http://stackoverflow.com/a/46860646
answers question: http://stackoverflow.com/q/46860234
has comment: http://stackoverflow.com/comment/80689749
has comment: http://stackoverflow.com/comment/80685247
score: 0
has body: Here is a code that will combine the two lists into a default dictionary. Then loop through and fetch the sum of each element price. You can implement this into your personal code. expenseNameList = ['bills', 'car', 'Uni', 'bills'] expensePriceLIst = [300, 150, 470, 150] #Created defultdict from collections import defaultdict diction = defaultdict(set) for c, i in zip(expenseNameList, expensePriceLIst): diction[c].add(i) for x in diction: print ("Your total expenditure on",x, "per month is $"+str(sum(diction.get(x)))+".")
type: Answer

http://stackoverflow.com/comment/80655749
type: QuestionComment
type: Comment
has text: `destination_file.writelines(line)` => `destination_file.write(line)`
score: 0
comment on: http://stackoverflow.com/q/46854187

http://stackoverflow.com/comment/90861976
has text: try to show toy examle: source data and what should happen. Like https://stackoverflow.com/questions/48066662/np-concatenate-a-nd-tensor-array-with-a-1d-array
score: 0
comment on: http://stackoverflow.com/q/46894349
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46836962
tagged with: built-in
downvote count: 3
answer count: 1
favorite count: 0
has body: I went through python 2x and 3x docs. It only mentions the following - The Python interpreter has a number of functions and types built into it that are always available. How and where are these built-in methods free floating?
has title: How can I find Python Built-in functions?
tagged with: python
upvote count: 4
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80621523
has comment: http://stackoverflow.com/comment/80621953
has answer: http://stackoverflow.com/a/46837497
accepted answer: http://stackoverflow.com/a/46837497
has comment: http://stackoverflow.com/comment/80621548
type: Question
has comment: http://stackoverflow.com/comment/80621554
has comment: http://stackoverflow.com/comment/80621525

http://stackoverflow.com/q/46751760
tagged with: gitpython
upvote count: 2
has title: Emulating 'git rebase -i' with reword in GitPython
has comment: http://stackoverflow.com/comment/80449803
favorite count: 0
tagged with: python
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80450001
has body: I'm working on a Python script to reword commit messages before sending out a code review, so that all the commits follow a particular format mandated by our team (e.g. "[UserStoryID] [TaskID] Some description of my commit") For instance, if I had 3 commits: a1b2c3 Add documentation d4e5f6 Implement unit tests c7b8a9 Add feature X I want to rebase/rename to: f9e8d7 US123 - TA456 - Add documentation c6b5a4 US123 - TA456 - Implement unit tests e3c2a1 US123 - TA456 - Add feature X With git rebase -i, this is easily doable using the reword option. But how can I replicate this functionality in GitPython? I'm thinking of something along these lines, although it is not valid GitPython: commits = list(repo.iter_commits(max_count=3)) # Reset to the parent commit of the first one we want renamed repo.head.reference = repo.commit('HEAD~4') repo.head.reset(index=True, working_tree=True) # Replay each commit, modifying the message first for commit in commits[::-1]: renamed_commit = commit.clone() renamed_commit.message = 'US123 - TA456 - ' + commit.message repo.apply(renamed_commit)
tagged with: git
type: Question

http://stackoverflow.com/comment/99068972
comment on: http://stackoverflow.com/a/46773161
type: Comment
has text: so you left `sess.run(train_step)` outside of the loop. So that means that weight update will occur after calculating the gradients of the last batch, is that correct? If we put it inside the loop, it will happen after each epoch right?
score: 3
type: AnswerComment

http://stackoverflow.com/comment/80505732
comment on: http://stackoverflow.com/q/46779690
score: 0
type: QuestionComment
has text: @SergAnuke I am attempting to replicate this research: https://web.stanford.edu/class/ee368/Project_Spring_1415/Reports/Cheshire_Halasz_Perin.pdf. I want to isolate the court by detecting the straight lines that outline it so that I can eventually use homography to find coordinates of players on the court.
type: Comment

http://stackoverflow.com/a/76068255
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46854496
has body: Didn't see my solution here so will post it. Worked for my corrupted images, but good to check your usecase. from cv2 import error import cv2 image= cv2.imread('your image') try: cv2.imshow('image', image) except error: print("error occured, now you can do some processing")

http://stackoverflow.com/comment/80712063
score: 0
has text: Why do You have 2 definitions of `Question` class?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46882342

http://stackoverflow.com/a/48490714
upvote count: 2
score: 2
has body: You ought to call the only command form directory my_app: nuitka --standalone --recurse-all --output-dir=deploy-nui a.py You'll get your application into folder my_app/deploy-nui/a.dist Of course before use nuitka you ought to install nuitka: pip install nuitka or pip3 install nuitka
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46767801

http://stackoverflow.com/comment/83717935
type: Comment
comment on: http://stackoverflow.com/q/46779745
has text: Did you ever figure this out? I'm having the same problem. AccessControlException on my python library directory
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80574303
type: QuestionComment
type: Comment
score: 0
has text: As well as speeding things up, it also saves RAM, since the module only gets loaded if it's needed. And that can be important on systems that need to run micropython. But @bendl makes a very good point: if the function is called multiple times then having the `import` in the function is less efficient, since the interpreter has to check on every function call if the module is loaded. Of course, this check is much faster than actually loading the module from storage, but still...
comment on: http://stackoverflow.com/q/46813425

http://stackoverflow.com/a/46814091
answers question: http://stackoverflow.com/q/46813982
type: Answer
has body: You can try this: s = 'he is hdajs asdas da he is not asd as da s i am a da daas you am a' s1 = s.split() new_data = list(set([(s.count(' '.join(b)), b) for b in [(s1[i], s1[i+1]) for i in range(len(s1)-1)]])) Output: [(2, ('am', 'a')), (1, ('da', 'daas')), (1, ('not', 'asd')), (1, ('s', 'i')), (1, ('da', 'he')), (1, ('you', 'am')), (2, ('he', 'is')), (1, ('is', 'not')), (1, ('asdas', 'da')), (1, ('asd', 'as')), (1, ('hdajs', 'asdas')), (1, ('a', 'da')), (1, ('daas', 'you')), (2, ('as', 'da')), (1, ('da', 's')), (1, ('is', 'hdajs')), (1, ('i', 'am'))]
downvote count: 1
score: -1
upvote count: 0

windows-server-2008-r2
tag name: windows-server-2008-r2
tags question: http://stackoverflow.com/q/46761979
type: Tag

http://stackoverflow.com/comment/80613967
type: Comment
type: AnswerComment
has text: Yes, replace with the name for your key pair name. This is the name displayed in the EC2 console.
comment on: http://stackoverflow.com/a/46781541
score: 0

http://stackoverflow.com/comment/80510833
type: AnswerComment
comment on: http://stackoverflow.com/a/46755287
score: 0
has text: Thanks, @dseuss, but when I do that, and I hit the exception, the tracer puts me at the lowest frame of the stack but thinks the next one up is the top of the script (which is from __future__ import print_function). (I'm no longer using the simple script in my example.) It's a much longer script, but the line that actually triggered the exception doesn't seem available in the stack the way it is when I use import ipdb;ipdb.set_trace(). Am I missing something?
type: Comment

http://stackoverflow.com/comment/80749905
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46901401
has text: So, I've discovered that using enumerate will help me obtain the indices of the list, but it's still a little hard to wrap my head around slicing the lists at the points I need to...any guidance would be really helpful.

http://stackoverflow.com/q/46752629
has answer: http://stackoverflow.com/a/46752773
linked to: http://stackoverflow.com/q/4028904
tagged with: startup
type: Question
has comment: http://stackoverflow.com/comment/80451087
has body: I have a script which downloads a file and saves to the Pictures directory. all is working well and I set that script to run on start up. but Since then I am getting key-error i.e HOME key. line where I getting error: filepath=os.environ['HOME']+'//Pictures' but it works fine when I run that script normally. why is this happening?
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/80451163
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/4028904
type: UnansweredQuestion
has title: python: Getting error while accesing os.environ['HOME'] in Ubuntu at start up
tagged with: python
has comment: http://stackoverflow.com/comment/80451059

http://stackoverflow.com/a/46983838
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46869323
has body: you can install modbus module using pip3 command. It has a client that will do your job.

http://stackoverflow.com/comment/80736914
comment on: http://stackoverflow.com/a/46894759
score: 1
type: AnswerComment
has text: @Luke: did you actually tested your query before you posted. Beause `ON DUPLCATE KEY UPDATE vulncount` seems illegal syntax. Third attempt.
type: Comment

http://stackoverflow.com/a/46761731
has body: In Python, you can have an else clause attached to your for loop. For example &gt;&gt;&gt; for i in range(10): ... if i == 5: break # this causes the else statement to be skipped ... else: ... print 'not found' ... Note 5 was found so the else statement is not executed &gt;&gt;&gt; for i in range(10): ... if i == 15: break ... else: ... print 'not found' ... not found See the documentation on for statements A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.
has comment: http://stackoverflow.com/comment/80471061
answers question: http://stackoverflow.com/q/46761691
accepted answer of: http://stackoverflow.com/q/46761691
has comment: http://stackoverflow.com/comment/80468756
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80468861
has comment: http://stackoverflow.com/comment/80492295
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/q/46901196
has title: Pygame Simple Movement: Enemy mimicking player movement and also retracing steps
has answer: http://stackoverflow.com/a/46943877
accepted answer: http://stackoverflow.com/a/46943877
type: Question
score: 0
answer count: 1
tagged with: python-3.x
tagged with: python
tagged with: pygame
has body: I want to use the movement method of my player class and have the enemy copy player movements. I want the enemy to basically follow the player until a certain condition is met for example 3 minutes have passed, after which I would like the enemy to retrace all its steps. Below is my movement method in the player's class class PacMan(pygame.sprite.Sprite): def __init__(self, x, y, radius): super().__init__() self.image = pygame.Surface([radius, radius]) self.image.fill([250, 250, 0]) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.queue = [-speed1, 0] self.direction = [-speed1, 0] def change_direction(self, x, y): self.queue = [x, y] def move(self, level): self.rect.x += self.queue[0] self.rect.y += self.queue[1] hitlist = pygame.sprite.spritecollide(self, level.wall_list, False) if hitlist: self.rect.x -= self.queue[0] self.rect.y -= self.queue[1] self.rect.x += self.direction[0] self.rect.y += self.direction[1] seclist = pygame.sprite.spritecollide(self, level.wall_list, False) if seclist: self.rect.x -= self.direction[0] self.rect.y -= self.direction[1] else: self.direction[0] = self.queue[0] self.direction[1] = self.queue[1] if self.rect.x &lt; -pacman_length: self.rect.x = board_dimensions[0] - wall_length self.rect.y = self.rect.y if self.rect.x &gt; board_dimensions[0]: self.rect.x = wall_length Next the enemy class which won't function apart from going to the right 4 pixels at a time class Ghost(pygame.sprite.Sprite): def __init__(self, x, y, color,): super().__init__() self.color = color self.image = pygame.Surface([pacman_length, pacman_length]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.direction = [0, speed1] self.moves = [False, True, True, False] self.edible = False self.wait = False self.waitcount = 0 self.speed = speed1 def move(self, level): status1 = False status2 = True self.rect.move_ip(4, 0) x_change = 0 y_change = 0 for i in startingmovements: print (i) print(i[0]) print (…
type: AnsweredQuestion

http://stackoverflow.com/comment/80499517
comment on: http://stackoverflow.com/q/46772871
type: QuestionComment
type: Comment
score: 0
has text: Edit, I just tried it with html5lib and got the same result.

http://stackoverflow.com/a/46771104
has comment: http://stackoverflow.com/comment/80491237
has body: Exactly, you are right - need set_index and unstack: df1 = (df.set_index(['ID_Patient', 'Name_Patient','month','year','visits'])['var'] .unstack() .reset_index() .rename_axis(None, 1)) print (df1) ID_Patient Name_Patient month year A U Z 0 2755 Jack Apr 2012 3.0 1.0 1.0 1 9753 Sue Feb 2012 NaN NaN 1.0 2 9753 Sue Jan 2012 5.0 8.0 NaN 3 11132 Jim Feb 2012 4.0 NaN 6.0 4 11132 Jim Jan 2012 2.0 5.0 NaN
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80487792
upvote count: 2
has comment: http://stackoverflow.com/comment/80491129
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46771055
answers question: http://stackoverflow.com/q/46771055

http://stackoverflow.com/comment/80689440
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46774528
has text: Yes, this line - `sess.run(tf.global_variables_initializer())` - runs the initializers for all variables. The result boils down to whether these initializers are constant or random.

http://stackoverflow.com/comment/80475997
type: QuestionComment
score: 1
has text: I think you should post some data, along with a better description of what you want.
comment on: http://stackoverflow.com/q/46764572
type: Comment

http://stackoverflow.com/a/46821175
downvote count: 0
has body: Use to_csv with the sep='\t' attribute. df.to_csv('example.txt', sep='\t')
type: Answer
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/85747396
answers question: http://stackoverflow.com/q/46821135

http://stackoverflow.com/q/46774701
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80495309
tagged with: java
tagged with: nav
has comment: http://stackoverflow.com/comment/80495624
type: Question
has body: So the issue i am having is that i am trying to count how many items(there are 8) are in the navigation menu of https://www.softrams.com/ and the logic won't pull through correctly. Either i am using the wrong function or i am not coding it correctly. the code I built for this function is WebElement nav_menu_count = driver.findElement(By.xpath("//ul[contains(@class,'nav navbar-nav')]")); System.out.println(nav_menu_count.getSize()); String nav_count = "710, 51"; if(nav_menu_count.equals(nav_count)) System.out.println("Menu count is correct"); else System.out.println("Menu count is incorrect"); my console output when i run this code is: (710, 51) Menu count is incorrect
answer count: 2
accepted answer: http://stackoverflow.com/a/46775826
has title: write a test to pass/fail the number of items in a Navigation menu using Java and or Python
score: 0
has answer: http://stackoverflow.com/a/46775826
tagged with: python
tagged with: selenium
possible better answer: http://stackoverflow.com/a/46775950
has answer: http://stackoverflow.com/a/46775950

http://stackoverflow.com/comment/80667813
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46860036
has text: sorry mate, but I asked for a solution, not what the error means

http://stackoverflow.com/comment/80559689
comment on: http://stackoverflow.com/q/46804356
has text: I had the same problem. The paramater `killasgroup=true` in the supervisord script solved it for me.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46819094
accepted answer: http://stackoverflow.com/a/46819249
tagged with: file
has comment: http://stackoverflow.com/comment/80585639
has body: I have a series of textfiles. They all end with a float, without a preceding whitespace ...foo123.456. The float has an unbounded number of digits. the files are large so I would like to avoid reading them completely in memory. They have also different sizes. How to avoid readgin the entire file?
has comment: http://stackoverflow.com/comment/80585720
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80585771
has comment: http://stackoverflow.com/comment/80585903
has comment: http://stackoverflow.com/comment/80585902
type: Question
has title: read a number at the end of a file
answer count: 1
has answer: http://stackoverflow.com/a/46819249
linked to: http://stackoverflow.com/q/2301789
score: 0
has comment: http://stackoverflow.com/comment/80585684
tagged with: python
has comment: http://stackoverflow.com/comment/80585606
has comment: http://stackoverflow.com/comment/80585715

http://stackoverflow.com/comment/111622657
comment on: http://stackoverflow.com/a/59575613
has text: worked but with a correction: `export LDFLAGS="-L/usr/local/opt/protobuf/lib"` AND `export CPPFLAGS="-I/usr/local/opt/protobuf/include"`
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46828255
tagged with: python
possible better answer: http://stackoverflow.com/a/46828465
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46828334
upvote count: 3
type: Question
score: 3
tagged with: substring
tagged with: replace
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have this: Title Num 0 VALEUR ÉNERGÉTIQUE 1 PROTÉINES 2 GLUCIDES <class 'pandas.core.frame.DataFrame'> Num Index(['Title'], dtype='object') This is what I want: Title Num 0 VALEUR ÉNERGÉTIQUE 1 PROTÉINES 2 GLUCIDES This is the regex I developed: ()([a-zA-Z]+\s*\w*)() Testing it I see it matches the whole initial string and has groups for the different substrings. In the end, I want group(2) in my dataframe column. (My examples below show the explicit regex but I have also tried these with the re.compile result which doesnt work either to get me to the my final result). This is what I have tried: df['Title'] = df['Title'].replace({'': ''}, inplace=True, regex=True) The result: Title Num 0 None 1 None 2 None Try number 2: df['Title'] = df['Title'].str.replace('', repl = '') Result number 2: Title Num 0 NaN 1 NaN 2 NaN Try number 3: df['Title'] = df[lambda df: df.columns[0]].str.extract('(>[a-zA-Z]+\s*\w*)', expand=False) Result 3: Title Num 0 NaN 1 NaN 2 NaN I really dont see what I am doing wrong and any help getting to my desired result would be appreciated. Thank you!
has answer: http://stackoverflow.com/a/46828465
tagged with: extract
has title: extracting and replacing substring using regex in a pandas dataframe
has answer: http://stackoverflow.com/a/46828334

http://stackoverflow.com/comment/80476023
has text: Hi, thanks a lot about your post. By default task are running on EU and when I execute it as DataflowRunner I have no problem with them. Issue appears just when I execute on DirectRun. Sorry about don't emphasize it on my question.
type: Comment
comment on: http://stackoverflow.com/a/46765048
score: 0
type: AnswerComment

http://stackoverflow.com/q/46860827
has answer: http://stackoverflow.com/a/46861025
type: UnansweredQuestion
tagged with: python
has title: numpy.ndarray' object has no attribute labels_
has body: I am working on Kmeans clustering algorithm. When I try to access the cluster labels it is showing: numpy.ndarray object has no attribute labels_ My code is as follows: movies=np.array(movies) kmeans=KMeans(n_clusters=19).fit_predict(movies) print(kmeans.labels_)
type: Question
tagged with: numpy
tagged with: k-means
has comment: http://stackoverflow.com/comment/80669149
score: 0
answer count: 1

http://stackoverflow.com/comment/106260623
type: Comment
comment on: http://stackoverflow.com/a/49328226
score: 0
type: AnswerComment
has text: Not working. I downloaded the latest .whl from the above mentioned link and installed it. When I did import cv2 it was still not able to find it. So added this line in the code to point to the installed location. Then I was able to import cv2 successfully but then when I tried to use imread parameter I got the error "AttributeError: module 'cv2' has no attribute 'imread'". Any idea where I am doing wrong ?

http://stackoverflow.com/comment/80515850
score: 0
comment on: http://stackoverflow.com/a/46783395
type: AnswerComment
has text: I'm using your second solution part 2, as it is a Series (first one spits out an error for me)
type: Comment

http://stackoverflow.com/comment/80465934
comment on: http://stackoverflow.com/a/46760016
type: Comment
has text: my apologies, sample data given above data wasn't the same but i changed it.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80594657
comment on: http://stackoverflow.com/a/46775533
score: 0
type: AnswerComment
has text: Another thing that strikes me, is you don't actually call __init__, and can you use self.master outside the __init__ function.
type: Comment

http://stackoverflow.com/q/46821106
tagged with: list-comprehension
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46821127
upvote count: 1
tagged with: enumeration
tagged with: python
has body: Is there a way to enumerate in list comprehension where the enumeration only increments when the if statement is True? For example, the code below enumerates whether the if statement is True or False and I would like to have a continuous index. my_list = [0,1,2] [i for i, w in enumerate(my_list) if w != 1] I also tried the following, but you can't use pass inside a list comprehension like below. [i if w != 1 else pass for i, w in enumerate(my_list)]
favorite count: 0
has title: Python Enumeration Using List Comprehension and If Statement
downvote count: 0
has comment: http://stackoverflow.com/comment/80589875
possible better answer: http://stackoverflow.com/a/46821134
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46821134
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/46821127
score: 1
has comment: http://stackoverflow.com/comment/80589701

http://stackoverflow.com/a/46897982
answers question: http://stackoverflow.com/q/46897854
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46897854
score: 5
type: AcceptedAnswer
has body: Python variable names and Python keyword argument names (which is what you actually need her) cannot contain $. You may be able to use the **kwargs syntax though: client.pet.get_pets(**{"$limit": 10})
type: Answer
upvote count: 5

http://stackoverflow.com/a/46870227
has comment: http://stackoverflow.com/comment/80739038
upvote count: 3
has comment: http://stackoverflow.com/comment/80828851
has comment: http://stackoverflow.com/comment/80697480
has body: This post solves for one-to-one mapping case between array and dictionary keys. The idea would be similar to proposed in @Andy Hayden's smart solution, but we will create a bigger array that incorporates Python's negative indexing thereby giving us the efficiency of simply indexing without any offsetting needed for incoming input arrays, which should be the noticeable improvement here. To get the indexer, which would be a one-time usage as the dictionary stays the same, use this - def getval_array(d): v = np.array(list(d.values())) k = np.array(list(d.keys())) maxv = k.max() minv = k.min() n = maxv - minv + 1 val = np.empty(n,dtype=v.dtype) val[k] = v return val val_arr = getval_array(d) To get the final replacements, simply index. So, for an input array a, do - out = val_arr[a] Sample run - In [8]: a = np.array([[ 3, 0, 2, -1], ...: [ 1, 255, 1, -16], ...: [ 0, 3, 2, 2]]) ...: ...: d = {0: 1, 1: 2, 2: 3, 3: 4, -1: 0, 255: 0, -16:5} ...: In [9]: val_arr = getval_array(d) # one-time operation In [10]: val_arr[a] Out[10]: array([[4, 1, 3, 0], [2, 0, 2, 5], [1, 4, 3, 3]]) Runtime test on tiled sample data - In [141]: a = np.array([[ 3, 0, 2, -1], ...: [ 1, 255, 1, -16], ...: [ 0, 3, 2, 2]]) ...: ...: d = {0: 1, 1: 2, 2: 3, 3: 4, -1: 10, 255: 89, -16:5} ...: In [142]: a = np.random.choice(a.ravel(), 1024*2048).reshape(1024,2048) # @Andy Hayden's soln In [143]: indexer = np.array([d.get(i, -1) for i in range(a.min(), a.max() + 1)]) In [144]: %timeit indexer[(a - a.min())] 100 loops, best of 3: 8.34 ms per loop # Proposed in this post In [145]: val_arr = getval_array(d) In [146]: %timeit val_arr[a] 100 loops, best of 3: 2.69 ms per loop
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46868855
has comment: http://stackoverflow.com/comment/80697518
score: 3

http://stackoverflow.com/comment/80596599
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46824087
has text: @MartijnPieters it's English, so 1252 should work? I tried with codec: ascii & cp037. Also pandas didn't deliver any error when reading the file.

http://stackoverflow.com/comment/80678198
comment on: http://stackoverflow.com/a/46865407
score: 2
has text: or use a lambda : `recordButton.clicked.connect(lambda:self.mainWindow.setCurrentIndex(1))`
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46875395
tagged with: return
possible better answer: http://stackoverflow.com/a/46875474
tagged with: python
has answer: http://stackoverflow.com/a/46875474
has comment: http://stackoverflow.com/comment/80697746
has answer: http://stackoverflow.com/a/46875420
has title: Print a returned file from a function
score: 0
answer count: 3
has body: I just want to print a file that is returned from a separate function: def open_file(): while True: try: filename = input("Input a file name: ") file=open(filename,'r') return file except FileNotFoundError: print("Error: Enter a valid file.") continue else: break open_file() for line in file: print(line) It's prompting for the file, and gives the error and re-promts when an invalid file is entered, but when a valid file is entered, it says that "file" is not defined. It's defined in the open_file function though, and is the returned value... So why doesn't it print?
tagged with: function
has answer: http://stackoverflow.com/a/46875486
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46875486

http://stackoverflow.com/q/46787536
tagged with: python
tagged with: readline
type: AnsweredQuestion
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/80521533
has comment: http://stackoverflow.com/comment/80521480
score: 0
has body: Im a little stuck here. I'm trying to read a data file in Python 3. I want to make a list of lists *The first 36 lines: each line is a list that's appended to the main list f = open("a.data","r") h = [] a = [] for word in range(0,797): g = f.readline() h.append(g.strip()) a.append(h) h = [] But from the 37th line and beyond: I need a loop where this happens: The new line is a white line, pass the next 4 lines should go into a new list 'h' and append to 'h' to 'a' The thing is that readline() acts crazy for everything I tried Any suggestions? Thanks in advance. ps the strings in the 4 lines are divided by a ;
accepted answer: http://stackoverflow.com/a/46789668
answer count: 1
has comment: http://stackoverflow.com/comment/80523705
has title: Python list in lists from datafile with different layouts
has comment: http://stackoverflow.com/comment/80523000
has comment: http://stackoverflow.com/comment/80521604
has answer: http://stackoverflow.com/a/46789668

http://stackoverflow.com/a/46903452
type: Answer
has body: as an alternative, you can take advantage of auth mechanism of requests, you can modify the prepared Request object: def auth_provider(req): global requests_count requests_count += 1 req.headers['X-Seq-Count'] = requests_count print('requests_count:', requests_count) return req requests_count = 0 s = requests.Session() s.auth = auth_provider s.get('https://www.example.com') requests.get('https://www.example.com', auth=auth_provider) output: requests_count: 1 requests_count: 2 however subclassing Session sounds okay to me.
downvote count: 0
answers question: http://stackoverflow.com/q/46878216
accepted answer of: http://stackoverflow.com/q/46878216
score: 3
has comment: http://stackoverflow.com/comment/80762100
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80866734
upvote count: 3

http://stackoverflow.com/comment/80771725
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46896757
type: Comment
has text: sir about the up-vote i tried that but the site respond is i have reputation less than 15 so i can NOT up vote any thing, but i promise you that i will up-vote your answer as soon as i pass the reputation thing.

http://stackoverflow.com/q/46879270
has comment: http://stackoverflow.com/comment/80705838
type: Question
tagged with: python-imaging-library
score: 1
upvote count: 2
answer count: 1
downvote count: 1
has body: I have a problem. So, I have this image, and I want put all of the numbers onto one line: But I only got this: As you can see, if it is 1, 0, 7 - all is fine, but with 4 and 3... My code: def reshape_img(self): width, height = self.img.size new_img_list = [] for x in range(width): white_y = 0 start_nr = False for y in range(height): red, green, blue = self.img.getpixel((x, y)) # Current color if red != 255: start_nr = True new_y = y - white_y + 5 new_img_list.append((x, new_y, (red, green, blue))) elif red == 255 and not start_nr: white_y += 1 return new_img_list def new_image(image_list): background = (255, 255, 255, 255) img = Image.new('RGB', (545, 20), background) pixels = img.load() for d in image_list: pixels[d[0], d[1]] = d[2] img.save('img2.png')
favorite count: 0
has title: Make objects in the image in one line
has answer: http://stackoverflow.com/a/46879517
accepted answer: http://stackoverflow.com/a/46879517
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/46870368
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python-requests
has body: I am new to python and I am trying to learn webscraping. I use Linux mint 18.2 and python version is as given in subject line. I have run pip install requests and subsequent pip install request --upgrade (all ran successfully). However, I am receiving below error while trying to import requests library: import requests Warning (from warnings module): File "/usr/local/lib/python2.7/dist-packages/requests/init.py", line 80 RequestsDependencyWarning) RequestsDependencyWarning: urllib3 (1.13.1) or chardet (2.3.0) doesn't match a supported version! Traceback (most recent call last): File "", line 1, in import requests File "/usr/local/lib/python2.7/dist-packages/requests/init.py", line 90, in from urllib3.exceptions import DependencyWarning ImportError: cannot import name DependencyWarning
score: 1
has title: import request command in python 2.7.12 yeilding requests dependency warning
type: Question
downvote count: 0
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80688589

http://stackoverflow.com/q/46893870
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/80735176
has comment: http://stackoverflow.com/comment/80735330
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80735274
tagged with: methods
has answer: http://stackoverflow.com/a/46894512
type: Question
answer count: 2
has body: I'm implementing a "player" module with the foliowing: a validation function a Player object with username and password attributes a change password method for Player When running the following change_password method, I receive an error: while(old_password!=self.password_str): AttributeError: 'Player' object has no attribute 'password_str' Yet, I am defining password_str as attribute of Player. Any ideas what's happening? class Player(object): def __init__(self, username_str="-", password_str=""): while (not validated(password_str)): self.password_str=input("Password is invalid. Please try again:") self.username=username_str def change_password(self,old_password): MAX_ATTEMPT=3 num_of_fails=0 while(old_password!=self.password_str): num_of_fails+=1 if(num_of_fails&lt;MAX_ATTEMPT): old_password=input("Thej passwword entered is invalid. Please try again. \ (You have "+str(MAX_ATTEMPT-num_of_fails)+" attempts reamining)") else: print("Incorrect password entered too many times. Your account is temporarily locked.") break if(num_of_fails&lt;MAX_ATTEMPT): new_password=input("please enter a new password.") while(not validated(new_password)): new_password=input("New password is invalid. Please try again") self.password_str=new_password print("Password has been successfully changed!")
has title: Error message: object does not contain attribute when object contains attribute
has answer: http://stackoverflow.com/a/46894299
score: 0
accepted answer: http://stackoverflow.com/a/46894512
possible better answer: http://stackoverflow.com/a/46894299
favorite count: 0

http://stackoverflow.com/q/46818539
has comment: http://stackoverflow.com/comment/80585868
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80585582
has comment: http://stackoverflow.com/comment/80585802
has comment: http://stackoverflow.com/comment/80585805
score: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/80594336
has comment: http://stackoverflow.com/comment/80586886
favorite count: 0
has comment: http://stackoverflow.com/comment/80584953
has comment: http://stackoverflow.com/comment/80594373
type: Question
has body: I'm trying to create a function that receives two bits of information and returns two lists of floats based on information that is already present in a file: Let's define the function as follows get_cakes_size_colour(), that should receive two strings as arguments: the name of the file, Cake size pattern. The function should return a list where the first element is a list of cake sizes and the second element a list of weight colors. This was the bit of code that I tried: def get_dimer_distance_energy(file_name, weight_size): one_cake_size = True cake_size = [] cake_colour = [] cake_colours = [] with open(file_name,'r') as file: for line in file: if cake_size in line.split() and one_cake_size: cake_size_1 = line.split()[1] cake_size_A = float(cake_size_1) cake_size_2 = line.split()[2] cake_size_B = float(cake_size_2) cake_size_3 = line.split()[3] cake_size_C = float(cake_size_3) one_cake_size=False elif cake_size in line.split() and not one_cake_size: cake_size_4 = line.split()[1] cake_size_D = float(cake_size_4) cake_size_5 = line.split()[2] cake_size_E = float(cake_size_5) cake_size_6 = line.split()[3] cake_size_F = float(cake_size_6) one_cake_size=True cake_size = cake_size +[average_size((cake_size_A), (cake_size_B), (cake_size_C), (cake_size_D), (cake_size_E), (cake_size_F))] return cake_size if "cake colour" in line: cake_colour += [line.split()[3]] return cake_colour for item in cake_colour: cake_colours.append(float(item)) return cake_colours I should point out that I had already defined a function for average_size earlier which ran perfect and was as follows: def average_size(x1, y1, z1, x2, y2, z2): size = ( (x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2 )**0.5 return size There were two problems I found when running this code: Firstly, I found that the return function does not return lists and was wondering if there were any amends to this. I tried looking for the solution to this on the site and could not find any that worked. Secondly, I found that when running th…
tagged with: python
has comment: http://stackoverflow.com/comment/80585713
has comment: http://stackoverflow.com/comment/80584599
has comment: http://stackoverflow.com/comment/80594326
has comment: http://stackoverflow.com/comment/80585813
tagged with: list
has title: creating a new list from another list but streamlining
upvote count: 3
has comment: http://stackoverflow.com/comment/80585849
tagged with: file
has comment: http://stackoverflow.com/comment/80586184
has comment: http://stackoverflow.com/comment/80586359
has comment: http://stackoverflow.com/comment/80585403
has comment: http://stackoverflow.com/comment/80585193

http://stackoverflow.com/comment/80611584
has text: FYI, it returns a tuple `(a,b)`, not a list `[a,b]` (technically)
type: AnswerComment
comment on: http://stackoverflow.com/a/46831960
type: Comment
score: 2

http://stackoverflow.com/comment/80521780
comment on: http://stackoverflow.com/q/46787806
type: Comment
type: QuestionComment
score: 1
has text: Please show the CSV output you want to achieve.

http://stackoverflow.com/comment/80590309
comment on: http://stackoverflow.com/a/46820441
score: 0
type: AnswerComment
has text: Thank you all so much, that definitely makes more sense. Is there anyway to track how many “lives” I’ve used?
type: Comment

http://stackoverflow.com/q/46844378
favorite count: 0
has answer: http://stackoverflow.com/a/46844685
has comment: http://stackoverflow.com/comment/80636492
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80636460
linked to: http://stackoverflow.com/q/5598181
type: Question
accepted answer: http://stackoverflow.com/a/46844685
linked to: http://stackoverflow.com/q/3249524
has title: Print on the same spot in IPython console
has comment: http://stackoverflow.com/comment/80636482
score: 4
tagged with: ipython
upvote count: 4
tagged with: printing
has comment: http://stackoverflow.com/comment/80636567
has body: This has been asked before (for instance a, b, etc.), but I cannot make it work in IPython console. I simply want to print some text over and over on the same line, not as continuous text, but replacing the previous one. This is my code: import time try: while True: s = "I want this always on the same line. " print(s, end="\r", flush=True) time.sleep(0.5) except KeyboardInterrupt: pass And here is what I get in IPython console: I am using Anaconda distribution on PC and Spyder, with Python 3. The code works in Anaconda terminal, but I need to print out some image as well so I need IPython. I also tried using end="" or adding a comma after the print() statement (even if this is for Python 2), but to no avail.
downvote count: 0
answer count: 1
tagged with: console

http://stackoverflow.com/q/46761654
has comment: http://stackoverflow.com/comment/80468808
has answer: http://stackoverflow.com/a/46761780
favorite count: 0
has title: Function defined correctly?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80468691
type: Question
has comment: http://stackoverflow.com/comment/80468757
tagged with: probability-distribution
has comment: http://stackoverflow.com/comment/80468587
tagged with: function
has body: I have a pdf defined as P(r, t). I am trying to define the pdf in python, but am new to the program and am unsure if I correctly defined it. Here is the pdf I am trying to define.1 from scipy.special import gamma as G def A(gamma, d): return np.power(G((d + 2) / gamma) / (G(d / gamma)), (gamma / 2)) def B(gamma, d): return np.log(gamma * np.power(G((d + 2) / gamma), (d / 2)) / np.power(G(1 / gamma), ((d + 2) / 2))) def dispersion(gamma, d, t, D): return np.power((D * t), (2 / gamma)) * g(gamma, d) def pdf(gamma, d, r, t, D): return (1 / np.power(dispersion(gamma, d, t, D), (d / 2))) * np.exp((-A(gamma, d) * np.power((r / np.sqrt(g(gamma, d))), gamma)) + B(gamma, d)) I am trying to plot the pdf, but I keep getting an error, so I want to confirm what I have above is correct before I try to move on. Any help would be appreciated! Also, I use G for the gamma function, and gamma to denote the gamma variable. Where the error is coming from: I created a sample 100x1000 and I let gamma=2 and d=1 for simplicity def pdf(gamma, d, r, t, D): return (1 / np.power(dispersion(gamma, d, t, D), (d / 2))) * np.exp((-A(gamma, d) * np.power((r / np.sqrt(g(gamma, d))), gamma)) + B(gamma, d)) r = range(100) t = range(1000) gamma = 2 d = 1 D = 2 p = pdf(gamma, d, r, t, D) plt.plot(r, p) plt.show() TypeError: unsupported operand type(s) for *: 'int' and 'range'
downvote count: 5
score: -4
answer count: 1

http://stackoverflow.com/a/46837679
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80657964
has comment: http://stackoverflow.com/comment/80727237
answers question: http://stackoverflow.com/q/46837554
has comment: http://stackoverflow.com/comment/80623607
has comment: http://stackoverflow.com/comment/80653984
has comment: http://stackoverflow.com/comment/80624201
type: Answer
has comment: http://stackoverflow.com/comment/80726246
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80656327
has body: You can sort columns A and B and then use groupby df'A','B' = pd.DataFrame(np.sort(df'A','B'.values, axis=1)) df.groupby(['A', 'B']).C.sum().reset_index() A B C 0 x y 9 1 y z 5 2 z z 6
accepted answer of: http://stackoverflow.com/q/46837554

http://stackoverflow.com/comment/80842754
score: 0
type: Comment
has text: I am able to get the label names but drop down does not works.Could you tell me where am i getting wrong?
comment on: http://stackoverflow.com/a/46866604
type: AnswerComment

http://stackoverflow.com/comment/80468757
type: Comment
type: QuestionComment
score: 2
has text: If you don't show the error and the code that causes the error, then no one will be able to help you.
comment on: http://stackoverflow.com/q/46761654

http://stackoverflow.com/q/46851060
tagged with: tensorboard
favorite count: 0
has answer: http://stackoverflow.com/a/46852037
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/39114832
downvote count: 1
has body: I'm learning TensorFlow by try out the example mnist_softmax.py (this is the orignal file),I add a few modification to it in order to using TensorBoard: tf.global_variables_initializer().run() merged_summary_op = tf.summary.merge_all() summary_writer = tf.summary.FileWriter('mnist_logs', sess.graph) # Train for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) if i%25 == 0: summary_str , _ = sess.run(merged_summary_op) summary_writer.add_summary(summary_str,i) # Test trained model correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) but a got errors when I run this file: File "mnist_softmax.py", line 87, in &lt;module&gt; tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 48, in run _sys.exit(main(_sys.argv[:1] + flags_passthrough)) File "mnist_softmax.py", line 73, in main summary_str , _ = sess.run(merged_summary_op) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 895, in run run_metadata_ptr) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1109, in _run self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 413, in __init__ self._fetch_mapper = _FetchMapper.for_fetch(fetches) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 230, in for_fetch (fetch, type(fetch))) TypeError: Fetch argument None has invalid type &lt;class 'NoneType'&gt; I…
tagged with: tensorflow
type: Question
answer count: 1
has title: Encounter Errors When Using tensorflow.summary
score: 0

http://stackoverflow.com/a/46770439
upvote count: 12
has comment: http://stackoverflow.com/comment/80486838
downvote count: 0
has comment: http://stackoverflow.com/comment/80488503
score: 12
has comment: http://stackoverflow.com/comment/80652000
has comment: http://stackoverflow.com/comment/80556469
has body: This is called multi-task learning, which basically means a model that learns several functions, but shares (some or all) weights. It's fairly common, for example one model for image recognition and detection. What you need to do is to define several loss functions (they are called heads). Here's a very simple example in tensorflow that learns Y1 and Y2 from X (from this post series): # Define the Placeholders X = tf.placeholder("float", [10, 10], name="X") Y1 = tf.placeholder("float", [10, 1], name="Y1") Y2 = tf.placeholder("float", [10, 1], name="Y2") # Define the weights for the layers shared_layer_weights = tf.Variable([10,20], name="share_W") Y1_layer_weights = tf.Variable([20,1], name="share_Y1") Y2_layer_weights = tf.Variable([20,1], name="share_Y2") # Construct the Layers with RELU Activations shared_layer = tf.nn.relu(tf.matmul(X,shared_layer_weights)) Y1_layer = tf.nn.relu(tf.matmul(shared_layer,Y1_layer_weights)) Y2_layer_weights = tf.nn.relu(tf.matmul(shared_layer,Y2_layer_weights)) # Calculate Loss Y1_Loss = tf.nn.l2_loss(Y1,Y1_layer) Y2_Loss = tf.nn.l2_loss(Y2,Y2_layer) If you wish to code in pure scikit, see sklearn.multiclass package, they support multioutput classification and multioutput regression. Here's an example of multioutput regression: &gt;&gt;&gt; from sklearn.datasets import make_regression &gt;&gt;&gt; from sklearn.multioutput import MultiOutputRegressor &gt;&gt;&gt; from sklearn.ensemble import GradientBoostingRegressor &gt;&gt;&gt; X, y = make_regression(n_samples=10, n_targets=3, random_state=1) &gt;&gt;&gt; MultiOutputRegressor(GradientBoostingRegressor(random_state=0)).fit(X, y).predict(X) array([[-154.75474165, -147.03498585, -50.03812219], [ 7.12165031, 5.12914884, -81.46081961], [-187.8948621 , -100.44373091, 13.88978285], [-141.62745778, 95.02891072, -191.48204257], [ 97.03260883, 165.34867495, 139.52003279], [ 123.92529176, 21.25719016, -7.84253 ], [-122.25193977, -85.16443186, -107.12274212], [ -30.170388 , -94.80956739, 12.16…
type: Answer
has comment: http://stackoverflow.com/comment/80489975
has comment: http://stackoverflow.com/comment/80716451
has comment: http://stackoverflow.com/comment/80488020
has comment: http://stackoverflow.com/comment/80489157
has comment: http://stackoverflow.com/comment/80715520
answers question: http://stackoverflow.com/q/46770088

http://stackoverflow.com/a/47043860
accepted answer of: http://stackoverflow.com/q/46794306
has body: import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') data = remote.get_state(api, 'sensor.random_sensor') print(data.last_changed)
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/46794306

http://stackoverflow.com/q/46775668
tagged with: python
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/46776045
has title: Need help in removing duplicate dates and merging values of two rows in Pandas Dataframe (python)
tagged with: dataframe
tagged with: pandas
type: AnsweredQuestion
has body: I am following data in pandas dataframe. Some date vales are repeating(2010-07-31,2010-10-31). How to remove repeated dates and merge the values between two rows. Take A % B values from 1st row and C &amp; D values from 2nd row. Date A B C D 1 2010-06-30 0:00:00 47.1 29.34 0.036 100.8 2 2010-07-31 0:00:00 47.1 29.34 3 2010-07-31 0:00:00 -4.644 100.2 4 2010-08-31 0:00:00 47.1 29.34 -1.481 100.4 5 2010-09-30 0:00:00 29.3 14.15 3.865 101.6 6 2010-10-31 0:00:00 29.3 14.15 7 2010-10-31 0:00:00 0.517 102.6 Expected Output: Date A B C D 1 2010-06-30 0:00:00 47.1 29.34 0.036 100.8 2 2010-07-31 0:00:00 47.1 29.34 -4.644 100.2 4 2010-08-31 0:00:00 47.1 29.34 -1.481 100.4 5 2010-09-30 0:00:00 29.3 14.15 3.865 101.6 6 2010-10-31 0:00:00 29.3 14.15 0.517 102.6 Thanks!
possible better answer: http://stackoverflow.com/a/46776257
has answer: http://stackoverflow.com/a/46776257
type: Question
has answer: http://stackoverflow.com/a/46776045

http://stackoverflow.com/comment/80702959
has text: @kens - I've added ghostscript path in $PATH variable: export PATH=$PATH:/usr/local/Cellar/ghostscript/9.22/bin/ But not working yet. And I tried to call "gs" in the console, and it works. I think it means system recognized ghostscript path.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46875908

http://stackoverflow.com/a/46791929
downvote count: 0
type: Answer
has body: Your code works fine if you just use map or a list comprehension. map(parseRPN, dat) I wouldn't worry about figuring out numpy's apply until you actually need to improve the performance.
has comment: http://stackoverflow.com/comment/80533577
upvote count: 1
has comment: http://stackoverflow.com/comment/80530915
score: 1
answers question: http://stackoverflow.com/q/46791372

http://stackoverflow.com/q/46860038
has comment: http://stackoverflow.com/comment/80667788
has answer: http://stackoverflow.com/a/46860101
has title: How to get specific number of rows based on column values in dataframe
favorite count: 0
duplicate of: http://stackoverflow.com/q/20069009
tagged with: pandas
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: dataframe
tagged with: rows
has answer: http://stackoverflow.com/a/46860097
has comment: http://stackoverflow.com/comment/80667795
type: Question
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/20069009
has body: Suppose I have a MNIST dataset in this way. df = pd.read_csv('data/train.csv') data = df.loc[df['label'].isin([1,6])] I am trying to select only those rows whose column ['label'] == 1 or 6. But, I am want to get only 500 rows from each column ['label'] How do I do it?

http://stackoverflow.com/comment/80741728
score: 1
type: QuestionComment
type: Comment
has text: You don't have separate global and local lists. There's only one list here. See https://nedbatchelder.com/text/names.html
comment on: http://stackoverflow.com/q/46897270

http://stackoverflow.com/a/46815781
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46815504
score: 1
has comment: http://stackoverflow.com/comment/80580426
upvote count: 1
has body: Assuming you have the whole database of 1M records in memory, the best solution would be: sorted(my_list, key=lambda rec: int(rec[1][-4:] + rec[1][3:5] + rec[1][:2]), reverse=True) It is very close to your second solution, except that you do not modify the list at all, but just extract the key of each record on demand. And the key will have the form 20170811 of the integer type for the original '11/08/2017' string. And it does not create the datetime objects, as parsing can be too expensive, when you need it only for sorting. And it compares even faster than the datetime objects and than the strings. Because the integer comparison is the fastest possible. And it consumes least memory during sorting, because the integers are the most compact way of storing the keys (relative to the strings &amp; datetimes). It can be even more optimized (for no real benefit, but for fun) by storing the number of days since some base date (compare: 20170811 (20'170'811) vs 736551 (736'551) days since 01.01.0001 or 17389 (17'389) since 01.01.1970). And the computational cost is not so much bigger, compared to the datetime parsing. sorted(my_list, key=lambda rec: int(rec[1][-4:])*32*12 + int(rec[1][3:5])*32 + int(rec[1][:2]), reverse=True) Here, we assume that every month is always 32 days, and every year is always 32*12=384 days. Because we do not care about the actual number of days, but only about their relative position on the numeric axis. This covers the cases with 28-29-30-31 days easily. PS: However, if you really have a database of 1M records, I would advise you to sort it in the database server with proper SQL — faster and more optimized. But this is another big topic which depends on how the database is organized.
has comment: http://stackoverflow.com/comment/80581944

http://stackoverflow.com/a/46830198
score: 3
accepted answer of: http://stackoverflow.com/q/46829276
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/46829276
has body: As commented by @Raphael, you can combine value1 and value2 columns into a single struct type column firstly, and then collect_list: import pyspark.sql.functions as F (df.withColumn('values', F.struct(df.value1, df.value2)) .groupBy('id') .agg(F.collect_list('values').alias('values'))).show() +---+--------------------+ | id| values| +---+--------------------+ | 1|[[A,red], [B,red]...| | 2|[[A,blue], [B,blu...| +---+--------------------+

http://stackoverflow.com/comment/80664285
type: Comment
has text: Whatever works best. Usually `select` is aesier/cleaner but `find_all` has more options.
score: 2
comment on: http://stackoverflow.com/q/46836818
type: QuestionComment

http://stackoverflow.com/q/46791194
has answer: http://stackoverflow.com/a/46791516
tagged with: terminal
score: 0
has comment: http://stackoverflow.com/comment/80529995
has comment: http://stackoverflow.com/comment/80532172
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/80531375
has comment: http://stackoverflow.com/comment/80529355
has answer: http://stackoverflow.com/a/46793260
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80531240
has title: I want to send a python's script output to a SSH shell
type: Question
answer count: 2
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/80532184
has comment: http://stackoverflow.com/comment/80529920
has body: Hello everyone I am making a car in Raspberry Pi-3. and I am sending some shh commands. my problem id that I do not want to send shh commands directly , although I want to send an output of a python console output how do i do so?
has comment: http://stackoverflow.com/comment/80528826

http://stackoverflow.com/comment/80650444
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46851356
has text: Thank you @jsbueno
score: 0

http://stackoverflow.com/a/46894502
upvote count: 1
score: 1
has body: You can create a dummy serializer for it. CustomerEventsSerializer(serializers.ModelSerializer): def to_representation:(self,obj): rep= super(CustomerEventsSerializer,self).to_representation(obj) rep['events']= [ customer.event for customer in CustomerEvents.objects.filter(account_number=obj.account_number)] return rep class Meta: model = CustomerEvents fields = ('account_number',)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46892217
has comment: http://stackoverflow.com/comment/99421522
type: Answer
accepted answer of: http://stackoverflow.com/q/46892217

http://stackoverflow.com/comment/133237729
has text: @dank8 Question was asked about 5 years ago, I have no logs now. There were no problems with XSLT 1, but with XSLT 2 only. In that project I used Saxon and it worked well.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46785786

http://stackoverflow.com/q/46793942
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/46794375
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46794058
type: Question
has title: how do I use .isalpha() to detect a maths operator
answer count: 2
has comment: http://stackoverflow.com/comment/80534802
has comment: http://stackoverflow.com/comment/80534938
has body: I'm trying to detect what math operator has been used and then assigning that operator to a variable. This is my code: start = "3x - 2 = 11" op = "+" for m in start: if m.isalpha(): if m == "-": op = m if m == "+": op = m if m == "*": op = m if m == "/": op = m print(op) However this prints "+", despite there being a "-" in the string start. Does anybody know why it is not printing out "-"? (btw this is python 3)
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/80699211
comment on: http://stackoverflow.com/q/46876060
score: 0
type: Comment
type: QuestionComment
has text: yes, so you need to count tuples. But that being said, it is against SO policies to answer zero-effort questions.

http://stackoverflow.com/comment/80649030
type: Comment
has text: It works. Thanks. Any idea why request.files('*') didn't work?
score: 0
comment on: http://stackoverflow.com/a/46844895
type: AnswerComment

http://stackoverflow.com/comment/80618932
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46822871
type: AnswerComment
has text: Ok thanks! What does the last line do? (I'm pretty new to `Django` as well)

http://stackoverflow.com/comment/80564929
comment on: http://stackoverflow.com/q/46800479
type: Comment
score: 0
has text: Please read https://stackoverflow.com/help/self-answer
type: QuestionComment

http://stackoverflow.com/comment/80773235
comment on: http://stackoverflow.com/a/46884334
has text: Thanks! This seems to make sense, but for some reason, it's still only returning the last item, even in the scrapy shell. Any idea why that might be? Thanks again
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/46785786
tagged with: xslt-2.0
has comment: http://stackoverflow.com/comment/80518546
has comment: http://stackoverflow.com/comment/133237729
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: lxml
has body: I use XSLT 2.0 file for converting ISOSTS XML document into HTML. My code: from lxml.etree import parse, XSLT xslt = parse('/path/to/isosts2html_standalone.xsl') # fixme: it works, but standard xsl fails! # xslt = XML('''\ # &lt;xsl:stylesheet version="1.0" # xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; # &lt;xsl:template match="/"&gt; # &lt;foo&gt;&lt;xsl:value-of select="/a/b/text()" /&gt;&lt;/foo&gt; # &lt;/xsl:template&gt; # &lt;/xsl:stylesheet&gt;''') self._transformer = XSLT(xslt) # &lt;- FAILS !!! dom = parse(file) new_dom = self._transformer(dom) return tostring(new_dom, pretty_print=True) I have next error: File "src/lxml/xslt.pxi", line 406, in lxml.etree.XSLT.init (src/lxml/etree.c:185192) lxml.etree.XSLTParseError: Start of literal Or next error using isosts2html.xsl from archive: File "src/lxml/xslt.pxi", line 406, in lxml.etree.XSLT.init (src/lxml/etree.c:185192) lxml.etree.XSLTParseError: Invalid expression Does lxml support XSLT 2.0 and how to solve problem?
has comment: http://stackoverflow.com/comment/80518928
has comment: http://stackoverflow.com/comment/133225294
score: 1
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/133234815
has title: How to convert XML into HTML using XSLT 2 transformation from Python3?
type: Question
upvote count: 1
tagged with: python
tagged with: xslt
linked to: http://stackoverflow.com/q/6644695

http://stackoverflow.com/a/46855554
answers question: http://stackoverflow.com/q/46855273
score: 0
type: Answer
has body: For a given input like this: l = pd.DataFrame([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]) you can do something like this: for i,v in l.iterrows(): for j in range(len(v)): l[i][j] = math.sqrt(l[i][j]*l[j][i]) better way of doing it in pandas would be: for i in l.columns.values: for j in l.index: l.loc[i, j] = math.sqrt(l.loc[i, j]*l.loc[j, i]) OUTPUT : &gt;&gt;&gt; l 0 1 2 3 0 1.000000 1.414214 1.732051 2.000000 1 1.189207 2.000000 2.449490 2.828427 2 1.316074 2.213364 3.000000 3.464102 3 1.414214 2.378414 3.223710 4.000000

http://stackoverflow.com/a/46750863
score: 7
has comment: http://stackoverflow.com/comment/137425735
has body: So, searching around and looking some codes on github, I found out that I need to mock from the view even if the function belongs to the use_cases module. So my code now is: tests.py from unittest.mock import patch, Mock @patch('core.views.add_owner_to_place') @patch('core.forms.PlaceForm.is_valid') @patch('core.forms.PlaceForm.save') def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place): self.client.post(reverse('place_create'), data={}) self.assertTrue(mocked_save.called) I know that this works, but now I need to search why it works. I'll explain it when I figure it out.
type: Answer
accepted answer of: http://stackoverflow.com/q/46750706
has comment: http://stackoverflow.com/comment/138546275
answers question: http://stackoverflow.com/q/46750706
upvote count: 7
has comment: http://stackoverflow.com/comment/80448757
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46793821
has comment: http://stackoverflow.com/comment/80534522
tagged with: python
type: AnsweredQuestion
has title: python tictactoe board add numbers to side
possible better answer: http://stackoverflow.com/a/46794270
has comment: http://stackoverflow.com/comment/80534797
has answer: http://stackoverflow.com/a/46794270
type: Question
has answer: http://stackoverflow.com/a/46794323
has body: ok so here is what i'm working on for fun and practice! i am making a game board for tic tac toe or checkers and i want it to be numbered on the side but i just cant figure out some good code for it. i have use as less code as i can hopefully someone can help me with this little challenge to figure this out. Python 2.7.8 is being used Num = 1 def P1(): print(" ---" * game) def P2(): if game &gt;= 2: Num+ 1 print(str(Num) + "| " * (game + 1)) game = int(raw_input("Game board size: ")) for i in range(game): P1() P2() P1() what i am hoping to get out of this is as shown below. 1 2 3 --- --- --- 1| | | | --- --- --- --- --- --- 2| | | | --- --- --- --- --- --- 3| | | | --- --- --- My result from my code is as followed: Game board size: 3 --- --- --- 1| | | | --- --- --- --- --- --- 1| | | | --- --- --- --- --- --- 1| | | | --- --- ---
has answer: http://stackoverflow.com/a/46794069
accepted answer: http://stackoverflow.com/a/46794069
score: 0
has comment: http://stackoverflow.com/comment/80534446
has comment: http://stackoverflow.com/comment/80534529
answer count: 3
has comment: http://stackoverflow.com/comment/80534564
has comment: http://stackoverflow.com/comment/80537153
has comment: http://stackoverflow.com/comment/80534471

http://stackoverflow.com/q/46871086
answer count: 0
type: UnansweredQuestion
tagged with: django
type: Question
has title: year date month in django template
has comment: http://stackoverflow.com/comment/80689659
has comment: http://stackoverflow.com/comment/80690137
has comment: http://stackoverflow.com/comment/80689656
has comment: http://stackoverflow.com/comment/80696446
score: 0
has comment: http://stackoverflow.com/comment/80689699
tagged with: python
has body: I have a home page http://127.0.0.1:8000/home/ which presents a list of blogposts which are a snippet of each blogpost and each snippet links to the full blogpost page which has url for example http://127.0.0.1:8000/home/blog/2017/10/14/. the template for the full blogpost url with year month and day is working correctly however I get a NoReverseMatch on the homepage : Reverse for 'view_blogpost_with_pk' with keyword arguments '{'year': 2017, 'month': 10, 'day': 1}' not found. 1 pattern(s) tried: ['home/blog/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$'] I dont know why its using 2017/10/01 instead of the correct year month day. I think im missing something from the view Here is my template for the home page: {% for p in allposts %} {{p.title}} {{p.author.username}} {{p.date}} {{p.comment_set.count}} comments read more {%endfor%} URL For homepage: url(r'^$', HomeView.as_view(), name = 'home'), Home View: class HomeView(TemplateView): template_name = 'home/home.html' def get(self,request): all_posts = BlogPost.objects.all().order_by('-date') args = {'allposts' : all_posts} return render(request, self.template_name, args) URL for each blogpost: url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', BlogPostView.as_view(),name = 'view_blogpost_with_pk') View for each blogpost: class BlogPostView(TemplateView): template_name = 'home/blog.html' def get(self,request,year,month,day): blogpost = BlogPost.objects.get(date__year=year, date__month=month, date__day=day) form = BlogPostForm() comments = Comment.objects.filter(comment_body_id=blogpost).order_by('-date') c = comments.count() args = {'bpost': blogpost,'form':form,'comments':comments,'c':c} return render(request,self.template_name, args) Been scratching my head for a couple days now did not manage to find a solution yet any help much appreciated.

http://stackoverflow.com/comment/80537573
type: Comment
comment on: http://stackoverflow.com/a/46792924
type: AnswerComment
has text: you Are right , I must to knew the software like microsoft online borders and then to add a number to x and y , thanks for help it work
score: 0

http://stackoverflow.com/q/46874544
has comment: http://stackoverflow.com/comment/80696057
score: 0
linked to: http://stackoverflow.com/q/4764932
has answer: http://stackoverflow.com/a/46884563
tagged with: python
answer count: 1
tagged with: exif
has title: preserve exif data while resizing images in python
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/80702676
has comment: http://stackoverflow.com/comment/80696686
type: UnansweredQuestion
type: Question
has body: I am resizing an image using PIL but the EXIF info is not getting preserved. I was going through answers in stack overflow but all are very old answers and dont seem to be working now. All are using pyexiv2 but I cant find it on google. Can someone suggest some method /to do the above in python 2.7? def imageresize(srcfile, destfile, newwid): img = Image.open(srcfile) print img s = img.size ratio = (float(newwid)/s[0]) newhght = int(ratio*s[1]) img.resize((newwid, newhght),Image.ANTIALIAS) img.save(destfile)
has comment: http://stackoverflow.com/comment/80697465

http://stackoverflow.com/a/46775010
score: 0
has comment: http://stackoverflow.com/comment/80498233
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46774105
has comment: http://stackoverflow.com/comment/80499737
has comment: http://stackoverflow.com/comment/80499716
type: Answer
has comment: http://stackoverflow.com/comment/80500258
has comment: http://stackoverflow.com/comment/80498944
has comment: http://stackoverflow.com/comment/80497662
has comment: http://stackoverflow.com/comment/80498648
accepted answer of: http://stackoverflow.com/q/46774105
has comment: http://stackoverflow.com/comment/80499877
has comment: http://stackoverflow.com/comment/80499598
has comment: http://stackoverflow.com/comment/80497432
has comment: http://stackoverflow.com/comment/80500013
has body: Here's a way to deal with your issue using a defaultdict to avoid having to care about the missing entries : year = (('Fanklin Grand Isle', '5560', 1), ('Windham', '3457', 1)) month = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1)) week = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1)) #I'm using a defaultdict to deal with the missing entries from collections import defaultdict joined_data = defaultdict([0,0,0].copy) for entry in year: #we create the default entry by calling the defaultdict with a key #and immediately grab the newly created list count = joined_data[(entry[0],entry[1])] #we swap *inplace* the value given by the DB query count[0] = entry[2] #rinse and repeat with the rest of the data for entry in month: count = joined_data[(entry[0],entry[1])] count[1] = entry[2] for entry in week: count = joined_data[(entry[0],entry[1])] count[2] = entry[2] #Finally we format the data to the required format result = tuple(key+tuple(value) for key,value in joined_data.items() ) print(result) Output: &gt;&gt;&gt;(('Chittendon', '3367', 0, 1, 1), ('Fanklin Grand Isle', '5560', 1, 1, 1), ('Windham', '3457', 1, 0, 0))

http://stackoverflow.com/a/46837260
answers question: http://stackoverflow.com/q/46837013
has body: You can use filter with like or regex keyword to match patterns in the column names: df = pd.DataFrame({ 'pre_1': [1,2], 'pre_2': [3,4], 'pre_3': [5,6], 'post1': [7,8], 'post2': [9,10], 'post3': [11,12] }) df #post1 post2 post3 pre_1 pre_2 pre_3 #0 7 9 11 1 3 5 #1 8 10 12 2 4 6 To select columns that contain a pattern, use the like keyword: df.filter(like='pre') #pre_1 pre_2 pre_3 #0 1 3 5 #1 2 4 6 Or you can use regular expression, the following will select columns that starts(^) with pre: df.filter(regex='^pre') #pre_1 pre_2 pre_3 #0 1 3 5 #1 2 4 6
score: 0
accepted answer of: http://stackoverflow.com/q/46837013
type: AcceptedAnswer
type: Answer

os.system
tags question: http://stackoverflow.com/q/46773226
tag name: os.system
type: Tag

http://stackoverflow.com/a/46781502
type: Answer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46781420
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46781420
has body: found is just a flag; while it's False (not found is True), you're checking each item against the target value. When you find a match, you set found to True, and bypass the item that matched (continue skips the rest of the body of the loop, returning to the top of the loop immediately, so append isn't called). After that, not found is always False, and since and is a short-circuiting test, if the left hand side is False, then the right hand side isn't even checked. From there on, you just append all remaining items as you go. By using the flag and checking it first, you: Avoid removing more than one copy of value from the newly created list Avoid the work of comparing items once you've found a match (testing not somebool is the cheapest test available in Python beyond testing a compile time constant), speeding up the code a bit

http://stackoverflow.com/q/46865284
tagged with: profiling
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/92796432
score: 8
has body: Taking the example script import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class MySpider(CrawlSpider): name = 'example.com' allowed_domains = ['example.com'] start_urls = ['http://www.example.com'] rules = ( # Extract links matching 'category.php' (but not matching 'subsection.php') # and follow links from them (since no callback means follow=True by default). Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))), # Extract links matching 'item.php' and parse them with the spider's method parse_item Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'), ) def parse_item(self, response): self.logger.info('Hi, this is an item page! %s', response.url) item = scrapy.Item() item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)') item['name'] = response.xpath('//td[@id="item_name"]/text()').extract() item['description'] = response.xpath('//td[@id="item_description"]/text()').extract() return item can anyone please let me know practically how to do profiling of this script ? Thanks
downvote count: 0
type: UnansweredQuestion
tagged with: scrapy
upvote count: 8
has answer: http://stackoverflow.com/a/54309556
type: Question
has title: How to profile a scrapy python script?

http://stackoverflow.com/q/46773626
has title: Parsing XML from a web page
tagged with: http://stackoverflow.com/tag/xml
tagged with: python
accepted answer: http://stackoverflow.com/a/46773738
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80493150
has answer: http://stackoverflow.com/a/46773738
type: Question
score: 0
tagged with: xml-parsing
has body: I want to parse an XML file. It's ok if my file is like "file.xml" I use this commands in Python : from lxml import etree tree = etree.parse("C:/file.xml") However, I have a new target now, the target is a web server. This server generates an XML text with curent values. May be the problem come from the URL because it's not ended by ".xml" ? The URL is like "http://ip/xml_render". But, in python, I have the error : lxml.etree.XMLSyntaxError: Start tag expected, '&lt;' not found, line 1, column 1 Indeed, my web page is not completly like a source code, it looks like this : So, the issue is about the URL or the web page ? Thank you.
answer count: 1

http://stackoverflow.com/a/46834417
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/46774456
answers question: http://stackoverflow.com/q/46774456
has body: It seem that I have to change product_no = models.IntegerField(primary_key=True) to product_no = models.AutoField(primary_key=True) and it's fixed.

http://stackoverflow.com/comment/80574416
has text: Ah! that is a straight fwd way that I have been using for so long. I just went blank now. Thanks MAx :)
comment on: http://stackoverflow.com/a/46813599
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80560548
type: Comment
type: QuestionComment
has text: Edit problem statement
comment on: http://stackoverflow.com/q/46806715
score: 0

http://stackoverflow.com/a/46876685
downvote count: 0
has body: You shuoldn't compare passwords: if myUsers.password == password ..: but rather the hash of the password: if myUsers.password == myPasswordHashFunction(password) ..: how to write myPasswordHashFunction is something you should know in detail, or you're better off using django's authenticate function. If you're not a security expert, then please (please!) don't invent your own way to authenticate and authorize users.
answers question: http://stackoverflow.com/q/46875745
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/80701527
type: QuestionComment
has text: I think you should ask a new question. Make sure to provide a [mcve].
comment on: http://stackoverflow.com/q/46870889
score: 0
type: Comment

http://stackoverflow.com/a/46766064
has comment: http://stackoverflow.com/comment/80477641
upvote count: 1
has body: There are several mistakes: You are making POST request but handling only GET request .html is not needed in routing munro object is not passed to the template I have updated these and now it's good to go: application.py from flask import Flask, render_template, request, url_for app = Flask(__name__) @app.route('/add-munro', methods=['GET','POST']) def addmunro(): if request.method == "POST": #Create an empty list mnList={} #Create a munro dictionary munro = {'name':request.form['mnName'], 'desc':request.form['mnDesc'], 'region':request.form['mnRegion'], 'height':request.form['mnHeight'], 'date':request.form['mnDate'], 'image':request.form['mnImage']} return render_template('add-munro.html', munro=munro) else: return render_template('add-munro.html') if __name__ == '__main__': app.run(debug=True) add-munro.html {% if munro is defined -%} Name: {{ munro.name }} Description: {{ munro.desc }} Region: {{ munro.region }} Height: {{ munro.height }} {%- endif %} Add a Munroe to your list Name Description Region Height Walk date Walk image Output:
has comment: http://stackoverflow.com/comment/80477860
accepted answer of: http://stackoverflow.com/q/46765683
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46765683
type: Answer

http://stackoverflow.com/q/46903065
answer count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
duplicate of: http://stackoverflow.com/q/3768895
has comment: http://stackoverflow.com/comment/80753077
has title: "op.student( , ) is not JSON serializable" in Odoo 10
score: 0
has body: I want to return data from python to javascript. I am calling function get_students_in_a_class in my js file. In which I want all the data which I am returning from python code in Odoo 10 Python code @api.model def get_students_in_a_class(self): _logger = logging.getLogger(__name__) # _logger.info('Class id' + repr(val.x_class_id) ) parents = self.env['parents'].search([('partner_id','=', self.env.user.partner_id.id)]) _logger.info('Parents ' + repr(parents)) sessions = [] classes = [] students = [] for parent in parents: students = self.env['op.student'].search([('parents_ids','=', parent.id)]) _logger.info('Students ' + repr(students)) for student in students: classes = self.env['x_classes'].search([('id','=', student.x_class_id.id)]) _logger.info('Classes ' + repr(classes)) for clas in classes: sessions = self.env['sessions'].search([('class_id','=',clas.id)]) _logger.info('Sessions ' + repr(sessions)) d = dict() d['Classes'] = classes d['Sessions'] = sessions d['Students'] = students _logger.info('Data--&gt;&gt; ' + repr(d)) return d Js code odoo.define('javascript_module.demo', function(require){ "use strict" var model = require('web.Model'); var studentModel = new model('op.student'); var data = studentModel.call('get_students_in_a_class') console.log('data---&gt;&gt;&gt;&gt;&gt;&gt;&gt;', JSON.stringify(data)); }) But it is showing error Server application error {"message":"Odoo Server Error","code":200,"data":{"debug":"Traceback (most r recent call last):\n File \"E:\\Oddo\\Odoo 10.0\\server\\odoo\\http.py\", line 640, in _handle_exception\n File \"E:\\Oddo\\Odoo 10.0\\server\\odoo\\http.py\", line 691, in dispatch\n File \"E:\\Oddo\\Odoo 10.0\\server\\odoo\\http.py\", line 629, in _json_response\n File \"json\\__init__.pyc\", line 244, in dumps\n File \"json\\encoder.pyc\", line 207, in encode\n File \"json\\encoder.pyc\", line 270, in iterencode\n File \"json\\encoder.pyc\", line 184, in default\nTypeError: op.student(113, 115) is not JSON serializable\n",…
linked to: http://stackoverflow.com/q/3768895
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80752894
tagged with: python

http://stackoverflow.com/comment/80573044
score: 0
comment on: http://stackoverflow.com/q/46812811
type: Comment
type: QuestionComment
has text: How about calling functions like "randn"? I think the standard is np.random or so? So, codes written with Pycharm editor and can run there can run in Ipython, but not vice versa?

http://stackoverflow.com/comment/80615794
comment on: http://stackoverflow.com/q/46834065
type: Comment
has text: Where does the `copy_tree` come from?
type: QuestionComment
score: 0

http://stackoverflow.com/a/46862201
has body: You can match node by exact text content as below: //td[text()="Total Assets"]/following-sibling::td/text() or //td[.="Total Assets"]/following-sibling::td/text() in this case both should work in the same way
accepted answer of: http://stackoverflow.com/q/46862177
answers question: http://stackoverflow.com/q/46862177
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/80737911
has text: Thanks guys. Tried both. I have updated my original post.
comment on: http://stackoverflow.com/q/46893921
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80446021
comment on: http://stackoverflow.com/a/46749751
type: Comment
has text: Also, one thing to note, the following warning comes up: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
score: 0
type: AnswerComment

http://stackoverflow.com/q/46777749
has comment: http://stackoverflow.com/comment/80501273
tagged with: python
has comment: http://stackoverflow.com/comment/80501443
has answer: http://stackoverflow.com/a/46777810
score: -1
has body: Given a robust dict with many sub dict's/list's/tuple's shouldn't I be able to use with statement to assign values to new names? I mean: # a dictionary with a complicated structure d = { 'names': ['Mark', 'Matteo', 'John'], 'options': (1, 2), 'sumting': { 'wong': [], 'etc': 'etc', 'habababa': 1 } } # try to access some deeply hidden structure and # pick to assign something to new names with d['sumting'] as temp: new_name1 = temp['wong'] new_name2 = temp['etc'] This yields: &gt;Traceback (most recent call last): &gt; File "&lt;pyshell&gt;", line 1, in &lt;module&gt; &gt;AttributeError: __enter__ Any other (better) way to avoid indexing the data structure (dict) multiple times apart from assigning a temp variable? # consider same `dict` 'd' temp = d['sumting'] new_name1 = temp['wong'] new_name2 = temp['etc'] del temp Using Python 3.6.1
upvote count: 3
has comment: http://stackoverflow.com/comment/80501223
accepted answer: http://stackoverflow.com/a/46777810
answer count: 1
has title: Use 'with' with dict to assign values
downvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80501210
has comment: http://stackoverflow.com/comment/80501240
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/a/46775305
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/80496435
answers question: http://stackoverflow.com/q/46774127
has body: You have 900MB stored in numpy array. tf.Variable(a) is equivalent to tf.Variable(tf.constant(a)). To create this constant, Python client appends 900MB constant to Graph object in Python runtime Session.run triggers TF_ExtendGraph which transfers the graph to TensorFlow C runtime, another 900MB session allocates 900MB for b tf.Variable object in TensorFlow runtime This makes 3600MB of memory allocations. To save memory you could do something like this instead a_holder = tf.placeholder(np.float32) b = tf.Variable(a_holder) sess.run(b.initializer, feed_dict={a_holder: np.arange(100000000)}) TLDR; avoid creating large constants.
accepted answer of: http://stackoverflow.com/q/46774127
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46849612
has body: I have one command that gives all urls of my project. And i want to export this command to xlsx file. Any ideas? In print message should be url command Thanks guys in advance. urls.py (Here command that gives all urls) from django.conf.urls import RegexURLPattern, RegexURLResolver from django.core import urlresolvers from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **kwargs): urls = urlresolvers.get_resolver() all_urls = list() def func_for_sorting(i): if i.name is None: i.name = '' return i.name def show_urls(urls): for url in urls.url_patterns: if isinstance(url, RegexURLResolver): show_urls(url) elif isinstance(url, RegexURLPattern): all_urls.append(url) show_urls(urls) all_urls.sort(key=func_for_sorting, reverse=False) print('Total urls:', len(all_urls)) print('-' * 220) for url in all_urls: print('| {0.regex.pattern:100} | {0.name:50} | {0.lookup_str:70} |'.format(url)) print('-' * 220) export_test.py (Export command) import xlsxwriter # Create a workbook and add a worksheet workbook = xlsxwriter.Workbook('Test2.xlsx') worksheet = workbook.add_worksheet() # Add a bold format bold = workbook.add_format({'bold': True}) # Write header worksheet.write('A1', 'URL', bold) worksheet.write('B1', 'Class', bold) expanses = ( ['TestUrl.com', 'TestClass'], ['TestUrl2.com', 'ExcelClass'], ['TestUrl3.com', 'OrderClass'], ['TestUrl4.com', 'TransferClass'], ) row = 1 col = 0 for item, cost in (expanses): worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) row += 1 workbook.close() I think it should be in print message
has title: Python URL command export to .xlsx file
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80647621
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46852714
tagged with: django
tagged with: python
tagged with: excel
score: 2
upvote count: 2
type: Question

http://stackoverflow.com/comment/80582082
type: Comment
comment on: http://stackoverflow.com/q/46817003
has text: @YaroslavSurzhikov You _could_ do that, but if `test` gets modified, that can lead to [unexpected weirdness](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). OTOH, I agree that mutable default args can be very handy, but when you use them you need to make it clear in the comments that you know what you're doing, or other readers of your code will assume it's a bug. ;)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80707351
type: Comment
comment on: http://stackoverflow.com/a/46873480
type: AnswerComment
has text: @okkhoy glad that I could help
score: 0

http://stackoverflow.com/a/46896886
has comment: http://stackoverflow.com/comment/80741163
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46896648
accepted answer of: http://stackoverflow.com/q/46896648
type: Answer
has body: int() should work correctly if the user only enters integer values - otherwise you have to wrap it with a try and catch block try: num1 = int(input("Type in your first number to add: ")) num2 = int(input("Type in your second number to add: ")) catch Exception as ex: pass //do nothing

http://stackoverflow.com/comment/80470300
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46762509
has text: @ScottBoston Returned with interest :-)
type: Comment

http://stackoverflow.com/comment/80571594
score: 1
has text: I'm not sure what you're trying to do (grab words?), but `.` is a special character in regex (it means any character [except the newline character unless the `s` flag is used] and not when it's used in a set), therefore, you need to escape the `.` with `\.` If you're simply trying to get words, use `[\w-]+`
comment on: http://stackoverflow.com/q/46812096
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80737336
score: 0
type: AnswerComment
has text: Thanks for your help. I added the file before writing transform....using query in hive. Is there any problem in .py script???
comment on: http://stackoverflow.com/a/46892283
type: Comment

http://stackoverflow.com/a/46832265
has comment: http://stackoverflow.com/comment/80612171
score: 0
has comment: http://stackoverflow.com/comment/80612420
has body: Following up on @MrCarnivore... from sys import exit userResponse = raw_input("n or y?") if not (userResponse =="n" or userResponse =="y"): print('Error Message Here') exit(1)
has comment: http://stackoverflow.com/comment/80612962
type: Answer
has comment: http://stackoverflow.com/comment/80612073
answers question: http://stackoverflow.com/q/46832120

http://stackoverflow.com/a/46904556
answers question: http://stackoverflow.com/q/46904428
downvote count: 0
type: Answer
upvote count: 2
score: 2
has body: You use can use dirname on abspath of __file__ to get the full path of the x.xml: os.path.dirname(os.path.abspath(__file__)) &gt;&gt;&gt; import pathlib &gt;&gt;&gt; p = pathlib.PurePath('a/b/c/d/e/f/x.xml') &gt;&gt;&gt; p.parts ('a', 'b', 'c', 'd', 'f', 'x.xml') Then you can extract any part of your path. If you want to get the d folder: import itertools res = '/'.join(itertools.takewhile(lambda x: x != 'd', p.parts))

http://stackoverflow.com/comment/88279479
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50614438
has text: Thanks, Carlos, Good to know. I corrected my answer.
type: AnswerComment

http://stackoverflow.com/q/46846177
possible better answer: http://stackoverflow.com/a/46846724
has comment: http://stackoverflow.com/comment/80639999
has answer: http://stackoverflow.com/a/46846995
has answer: http://stackoverflow.com/a/46846724
has answer: http://stackoverflow.com/a/46846636
answer count: 3
has title: Finding longest perfect match between two strings
downvote count: 0
linked to: http://stackoverflow.com/q/18715688
has comment: http://stackoverflow.com/comment/80640104
favorite count: 0
has body: I am trying to write a script that will perform two functions, when provided with two strings: 1. Find the longest sequence of characters starting from pos[0] that is the same in both strings Seq1 = 'ATCCTTAGC' Seq2 = 'ATCCAGCAATTC' ^^^^ Match from pos[0] to pos[3] Pos: 0:3 Length: 4 Seq: ATCC 2. Find the longest run of characters that exists in both strings Seq1 = 'TAGCTCCTTAGC' # Contains 'TCCTT' Seq2 = 'GCAGCCATCCTTA' # Contains 'TCCTT' ^ No match at pos[0] Pos1: 4:8 Pos2 7:11 Length: 5 Seq: TCCTT To accomplish problem 1, I have the following: #!/usr/bin/python upstream_seq = 'ATACATTGGCCTTGGCTTAGACTTAGATCTAGACCTGAAAATAACCTGCCGAAAAGACCCGCCCGACTGTTAATACTTTACGCGAGGCTCACCTTTTTGTTGTGCTCCC' downstream_seq = 'ATACACGAAAAGCGTTCTTTTTTTGCCACTTTTTTTTTATGTTTCAAAACGGAAAATGTCGCCGTCGTCGGGAGAGTGCCTCCTCTTAGTTTATCAAATAAAGCTTTCG' print("Upstream: %s\nDownstream: %s\n") % (upstream_seq, downstream_seq) mh = 0 pos_count = 0 seq = "" position ="" longest_hom="" for i in range(len(upstream_seq)): pos_count += 1 if upstream_seq[i] == downstream_seq[i]: mh += 1 seq += upstream_seq[i] position = pos_count longest_hom = mh else: mh = 0 break print("Pos: 0:%s\nLength: %s\nSeq: %s\n") % (position , longest_hom, seq) Upstream: ATACATTGGCCTTGGCTTAGACTTAGATCTAGACCTGAAAATAACCTGCCGAAAAGACCCGCCCGACTGTTAATACTTTACGCGAGGCTCACCTTTTTGTTGTGCTCCC Downstream: ATACACGAAAAGCGTTCTTTTTTTGCCACTTTTTTTTTATGTTTCAAAACGGAAAATGTCGCCGTCGTCGGGAGAGTGCCTCCTCTTAGTTTATCAAATAAAGCTTTCG Pos: 0:5 Length: 5 Seq: ATACA I'm having trouble with Problem 2. So far, I've considered an alignment between the two sequences using BioPython's pairwise2. However, in this case, I only want perfect matches (no gaps, no extensions), and I only want to see the longest sequence, not a consensus which is what I appear to get: from Bio import pairwise2 as pw2 global_align = pw2.align.globalms(upstream_seq, downstream_seq, 3, -1, -.5, -.5) print(global_align[0]) ('ATACATT-G----GCC-TTGGCTTA-----G--ACTTAGATCTAG-----ACCTGAA----AATAACCTGCCGAAAA-GACC…
tagged with: bioinformatics
tagged with: python
accepted answer: http://stackoverflow.com/a/46846636
type: AnsweredQuestion
score: 9
type: Question
upvote count: 9

dataframe
tags question: http://stackoverflow.com/q/46803155
tags question: http://stackoverflow.com/q/46834247
tags question: http://stackoverflow.com/q/46866548
tags question: http://stackoverflow.com/q/46825445
tags question: http://stackoverflow.com/q/46891019
tags question: http://stackoverflow.com/q/46801285
tags question: http://stackoverflow.com/q/46880748
tags question: http://stackoverflow.com/q/46905576
tags question: http://stackoverflow.com/q/46810436
tags question: http://stackoverflow.com/q/46870692
tags question: http://stackoverflow.com/q/46764230
tags question: http://stackoverflow.com/q/46788855
tags question: http://stackoverflow.com/q/46827750
tags question: http://stackoverflow.com/q/46819405
tags question: http://stackoverflow.com/q/46763025
tags question: http://stackoverflow.com/q/46864492
tags question: http://stackoverflow.com/q/46780563
tags question: http://stackoverflow.com/q/46879348
tags question: http://stackoverflow.com/q/46840002
tags question: http://stackoverflow.com/q/46761657
tags question: http://stackoverflow.com/q/46764674
tags question: http://stackoverflow.com/q/46796265
tags question: http://stackoverflow.com/q/46837554
tags question: http://stackoverflow.com/q/46834357
tags question: http://stackoverflow.com/q/46868798
tags question: http://stackoverflow.com/q/46832603
tags question: http://stackoverflow.com/q/46820068
tags question: http://stackoverflow.com/q/46859802
tags question: http://stackoverflow.com/q/46760895
tags question: http://stackoverflow.com/q/46784707
tags question: http://stackoverflow.com/q/46890972
tags question: http://stackoverflow.com/q/46761978
tags question: http://stackoverflow.com/q/46819962
tags question: http://stackoverflow.com/q/46788624
tags question: http://stackoverflow.com/q/46762920
tags question: http://stackoverflow.com/q/46821785
tags question: http://stackoverflow.com/q/46850584
tags question: http://stackoverflow.com/q/46754878
tags question: http://stackoverflow.com/q/46880494
tags question: http://stackoverflow.com/q/46834732
tags question: http://stackoverflow.com/q/46882516
tags question: http://stackoverflow.com/q/46832969
tags question: http://stackoverflow.com/q/46819035
tags question: http://stackoverflow.com/q/46842320
tags question: http://stackoverflow.com/q/46852137
tags question: http://stackoverflow.com/q/46798532
tags question: http://stackoverflow.com/q/46842005
tags question: http://stackoverflow.com/q/46823175
tags question: http://stackoverflow.com/q/46876426
tags question: http://stackoverflow.com/q/46781195
tags question: http://stackoverflow.com/q/46867009
tags question: http://stackoverflow.com/q/46758768
tags question: http://stackoverflow.com/q/46797412
tags question: http://stackoverflow.com/q/46777403
tags question: http://stackoverflow.com/q/46780987
tags question: http://stackoverflow.com/q/46865865
tags question: http://stackoverflow.com/q/46835134
tags question: http://stackoverflow.com/q/46900478
tags question: http://stackoverflow.com/q/46818555
tags question: http://stackoverflow.com/q/46781336
tags question: http://stackoverflow.com/q/46802931
tags question: http://stackoverflow.com/q/46771727
tags question: http://stackoverflow.com/q/46858848
tags question: http://stackoverflow.com/q/46844812
tags question: http://stackoverflow.com/q/46841519
tags question: http://stackoverflow.com/q/46884727
tags question: http://stackoverflow.com/q/46855551
tags question: http://stackoverflow.com/q/46797622
tags question: http://stackoverflow.com/q/46770500
tags question: http://stackoverflow.com/q/46760020
tags question: http://stackoverflow.com/q/46853108
tags question: http://stackoverflow.com/q/46847884
tags question: http://stackoverflow.com/q/46831752
tags question: http://stackoverflow.com/q/46901961
tags question: http://stackoverflow.com/q/46802239
tags question: http://stackoverflow.com/q/46833670
tags question: http://stackoverflow.com/q/46775668
tags question: http://stackoverflow.com/q/46777564
tags question: http://stackoverflow.com/q/46830231
tags question: http://stackoverflow.com/q/46876847

http://stackoverflow.com/q/46813478
downvote count: 0
answer count: 1
has title: Fuzzy Matching - returning the best potential value of a test string
has comment: http://stackoverflow.com/comment/80574208
has answer: http://stackoverflow.com/a/46813575
has body: I am trying to use a fuzzy matching to snap a list of responses to a validation set. I am using the following code: for x in rawDatabase.Status: choice = process.extractOne(x, my_list) print('choice ',choice) Where the Status column in the rawDatabase data-frame is the column I am trying to validate. my_list is a list of standardized values for the entries in the Status column to snap to. Using the above code I get the following sample output: choice ('TRANSFER IN FROM GOVERNMENT DEPARTMENT', 100, 39) choice ('TRANSFER OUT TO GOVERNMENT DEPARTMENT', 100, 40) choice ('CURRENT', 100, 1) choice ('LEAVER - RETIRED', 100, 12) choice ('CURRENT', 100, 1) Is there a way I can return the value that best fits the string being tested and update the rawDatabase Status column with the updated value? So for example I would get returned choice = 'TRANSFER IN FROM GOVERNMENT DEPARTMENT' choice = 'TRANSFER OUT TO GOVERNMENT DEPARTMENT' choice = 'CURRENT' choice = 'LEAVER - RETIRED' choice = 'CURRENT'
favorite count: 0
linked to: http://stackoverflow.com/q/6690739
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80574180
upvote count: 1
type: Question
score: 1

http://stackoverflow.com/q/46786211
tagged with: pandas
has title: Counting the Frequency of words in a pandas data frame
downvote count: 0
has answer: http://stackoverflow.com/a/79153563
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/46786277
upvote count: 54
tagged with: python
has answer: http://stackoverflow.com/a/46786404
type: AnsweredQuestion
has body: I have a table like below: URN Firm_Name 0 104472 R.X. Yah &amp; Co 1 104873 Big Building Society 2 109986 St James's Society 3 114058 The Kensington Society Ltd 4 113438 MMV Oil Associates Ltd And I want to count the frequency of all the words within the Firm_Name column, to get an output like below: I have tried the following code: import pandas as pd import nltk data = pd.read_csv("X:\Firm_Data.csv") top_N = 20 word_dist = nltk.FreqDist(data['Firm_Name']) print('All frequencies') print('='*60) rslt=pd.DataFrame(word_dist.most_common(top_N),columns=['Word','Frequency']) print(rslt) print ('='*60) However the following code does not produce a unique word count.
possible better answer: http://stackoverflow.com/a/46786404
type: Question
accepted answer: http://stackoverflow.com/a/46786277
tagged with: nltk
has answer: http://stackoverflow.com/a/61396422
score: 54
has answer: http://stackoverflow.com/a/74811516
linked to: http://stackoverflow.com/q/18936957

http://stackoverflow.com/comment/80567414
comment on: http://stackoverflow.com/q/46809710
has text: they have! i can see that. but what is the problem here? doesnt it work because "countries" are object instead of strings?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/69055117
has body: import pandas as pd df = pd.read_csv('pokemon_data.csv')`enter code here` 'Name', 'Type 1', 'Type 2', 'HP', 'Attack', 'Defense', 'Sp. Atk','Sp. Def', 'Speed', 'Generation', 'Legendary' (My data frame consists of same column names in the same order) df['Total']=df.iloc[:,4:10].sum(axis=1) `'Name', 'Type 1', 'Type 2', 'HP', 'Attack', 'Defense', 'Sp. Atk','Sp. Def', 'Speed', 'Generation', 'Legendary', 'Total'` (adding a new column Total which is the sum of hp, attack, defence, sp.atk, sp.def,speed) cols = list(df.columns.values) df = df[cols[0:4]+[cols[-1]]+cols[4:12]] 'Name', 'Type 1', 'Type 2','Total', 'HP', 'Attack', 'Defense', 'Sp. Atk','Sp. Def', 'Speed', 'Generation', 'Legendary' (Moving the 'Total' columns)
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/122046601
answers question: http://stackoverflow.com/q/46813556

http://stackoverflow.com/a/46776237
has comment: http://stackoverflow.com/comment/80552794
answers question: http://stackoverflow.com/q/46775977
score: 0
upvote count: 1
downvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46775977
has body: there's a lot of transpositions going on here. I fiddled a bit with ast.literal_eval (to evaluate the tuples) and then a few zip calls, maybe there's something simpler: import ast for m,i in enumerate(["(1,2),(3,4)","(6,7),(9,0)"]): # hardcoded the input s.append(m) c.append(zip(*ast.literal_eval(i))) result = [a+b for a,b in zip(*c)] result: [(1, 3, 6, 9), (2, 4, 7, 0)]

http://stackoverflow.com/a/46899713
accepted answer of: http://stackoverflow.com/q/46899376
type: Answer
answers question: http://stackoverflow.com/q/46899376
score: 0
type: AcceptedAnswer
has body: If you want to bring in all of methods and imports for large_import_file to the current file's namespace, you'd just do. from large_import_file import * As silent mentioned in his answer this is covered in Python more on modules

http://stackoverflow.com/comment/80493459
type: Comment
type: QuestionComment
has text: run and toggle are not commands so the quotes don't really matter the whole line is out
score: 0
comment on: http://stackoverflow.com/q/46773836

http://stackoverflow.com/q/46855183
has comment: http://stackoverflow.com/comment/80659926
has comment: http://stackoverflow.com/comment/80657935
type: UnansweredQuestion
has body: I'm trying to combine a bunch of csv files. Each csv file has a different number of columns. This is not a problem, I can easily loop through the files and pull in all the column headers, pasting them into an empty file to use as a base. The problem I'm having is that the column headers are on different rows in each file. For example: Table1 Random Text !,Header1,Header2,Header3 *,123,124,5235 *,124,15,23624 *,135,677,234 Table2 Random Text Random Text !,Header1,Header2,Header4 *,124,2156,7478 *,126,12357,547 *,237,12,267 Output: Table,Header1,Header2,Header3,Header4 Table1,123,124,5235 Table1,124,15,23624 Table1,135,677,234 Table2,124,2156,7478 Table2,126,12357,547 Table2,237,12,267 My existing code looks something like this: files = glob.glob(r'//Directory/*.csv') #This block goes through each file and works out which variables exist variablelist=[] for f in files: with open(f,'r') as csvfile: read_rows = csv.reader(csvfile) for row in read_rows: if row[0]!="*": #The last row with no * in column 1 is the header row rowlist = row variablelist.extend(x for x in rowlist if x not in variablelist) list.sort(variablelist) I use the fact that the header row is the last row without a * in the first column. I work out which row the headers are on and then store the header names in a list - combining the same list from all files. I then try and combine the files together using this code that I found by searching this website: with open("out.csv", "w", newline="") as f_out: # Comment 2 below writer = csv.DictWriter(f_out, fieldnames=variablelist) for f in files: with open(f, "r", newline="",) as f_in: reader = csv.DictReader(f_in) # Uses the field names in this file for line in reader: # Comment 3 below writer.writerow(line) The problem is, I don't know how to deal with the headers being on different lines. I tried using code to define the header row number, but don't know how to implement this into the code above - (Can dictreader skip a dynamic number of rows before findin…
has title: Using Python to combine csv files with headers on different rows
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80657913
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/80660003

qfilesystemmodel
tag name: qfilesystemmodel
type: Tag
tags question: http://stackoverflow.com/q/46835109

http://stackoverflow.com/comment/80738170
has text: @c11o - this is crazy, i guess i had a issue of some sort in my heroku deploy procedure. now i moved to latest, and I dont see that problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46890665
score: 0

http://stackoverflow.com/comment/80520932
type: Comment
type: QuestionComment
has text: @MohitC When I say `Just to be clear, this is the entire code:` there I have pasted the entire code, as a minimal working example
comment on: http://stackoverflow.com/q/46787345
score: 0

http://stackoverflow.com/comment/80620947
type: Comment
comment on: http://stackoverflow.com/a/46836067
type: AnswerComment
has text: What problem do you have there? Maybe check if an object is iterable instead of if it's a list?
score: 0

http://stackoverflow.com/comment/80449319
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46751428
has text: @PM2Ring Running this on a Unix system! (macOS Sierra to be specific). I just updated the question to reflect this. and thanks for letting me know about the way notifications work. And yes I understand he's under no obligation. Didn't think it hurt to ask though.

http://stackoverflow.com/comment/80678164
comment on: http://stackoverflow.com/a/46865134
score: 0
type: AnswerComment
has text: i get the error AttributeError: 'str' object has no attribute 'values'
type: Comment

http://stackoverflow.com/comment/80632065
has text: Yes. At the source where you read in a string, convert to a `unicode` object. Then *only work with unicode objects*.
comment on: http://stackoverflow.com/q/46842098
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80701934
has text: Has been asked before https://stackoverflow.com/q/28617841/1328439
comment on: http://stackoverflow.com/q/46877403
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/80474223
has text: Please, could you help me what should I modify if I need to do `print(team.playerlist)` ? @tuned
type: AnswerComment
comment on: http://stackoverflow.com/a/46756538
score: 0
type: Comment

http://stackoverflow.com/comment/80590460
has text: driver.execute_script("$(window.open('child_link'))") seems will not to open the link, but open new window/dialog. because window.open() use to open dialog/window. Are you sure you use the right way to open the link?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46820559

http://stackoverflow.com/comment/80617850
type: Comment
comment on: http://stackoverflow.com/a/46834777
score: 0
type: AnswerComment
has text: @martineau Since we don't have the script and the OP mentions "printing to a single file", so the results from different processes are likely to be strings and in this case, you are right. What is your solution? I don't think asynchronous operation is a solution here!

http://stackoverflow.com/comment/80580256
score: 1
comment on: http://stackoverflow.com/q/46816085
has text: What is fasta file? What format has it? I suppose not many people know it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80700788
has text: Just to make sure I'm understanding this, if I have several signals connected to a slot, and I want to update all of those, the I would use emit?
type: Comment
comment on: http://stackoverflow.com/a/46856186
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80584434
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46818313
has text: It might help to include what the output looks like
score: 1

http://stackoverflow.com/comment/80493826
comment on: http://stackoverflow.com/a/46772433
type: AnswerComment
score: 0
has text: @DanielMöller Keras used to require `tensorflow` (i.e. CPU version), but it seems not anymore https://github.com/fchollet/keras/blob/master/setup.py
type: Comment

http://stackoverflow.com/a/46851005
upvote count: 1
answers question: http://stackoverflow.com/q/46850938
score: 1
has body: You could use all: all(any(p_name==p.project_name for p in projects) for p_name in projects_list) Or more readable: appears = lambda p_name: any(p_name==p.project_name for p in projects) all(appears(p_name) for p_name in projects_list)
downvote count: 0
type: Answer

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/46759741
tags question: http://stackoverflow.com/q/46797224
tags question: http://stackoverflow.com/q/46757272
tags question: http://stackoverflow.com/q/46799137
tags question: http://stackoverflow.com/q/46824495
tags question: http://stackoverflow.com/q/46818471
type: Tag
tags question: http://stackoverflow.com/q/46799018
tags question: http://stackoverflow.com/q/46800671
tags question: http://stackoverflow.com/q/46825445

http://stackoverflow.com/a/46797640
type: Answer
accepted answer of: http://stackoverflow.com/q/46797494
has body: The issue is now fixed in version 0.8.1 of seaborn. You may simply use g = sns.pairplot(iris, hue="species", palette="Set2", diag_kind="kde", size=2.5) as stated in the documentation. Also the workaround posted in this answer will work as expected in seaborn 0.8.1 and not have any yscaling issues.
has comment: http://stackoverflow.com/comment/80543408
answers question: http://stackoverflow.com/q/46797494
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80543439

http://stackoverflow.com/q/46808538
has answer: http://stackoverflow.com/a/46808672
has title: Exporting each row of a 2D numpy array as a single element in csv column
type: Question
tagged with: numpy
tagged with: arrays
score: 0
has body: I have a 2D numpy array which has a shape of (15015,262). I need to export it to a csv file so that each row of the numpy 2Darray is a single element list of the csv file (i.e., the csv file should have a shape of (15015,1). I tried using the csv modules of python and the numpy modules but nothing seems to work properly. For example, I tried using with open('filename.csv', 'wb') as f: writer = csv.writer(f) for val in modified_seq_data: writer.writerow([val]) In the above case (even though the csv file does get saved in a single column), when I call it back via np.genfromtxt (for a different code) I get the following output: [nan nan nan nan nan ..... nan nan nan] Somehow it is not able to export the csv into a numpy 1D array where each element is a list. Any help will be much appreciated!
answer count: 2
has answer: http://stackoverflow.com/a/46809557
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/a/46873257
upvote count: 2
answers question: http://stackoverflow.com/q/46872850
has body: The problem is that you don't call the QMouseEvent.buttons method, you are comparing a method with the numeric value of Qt.LeftButton. You must do: if event.buttons() == Qt.LeftButton: # ^^
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46872850

http://stackoverflow.com/comment/80748193
type: Comment
type: QuestionComment
has text: You need to parse each line of the file. The [`re`](https://docs.python.org/3/library/re.html#module-re) regular expression library module would be a good choice.
score: 0
comment on: http://stackoverflow.com/q/46900467

http://stackoverflow.com/comment/80691667
type: QuestionComment
type: Comment
has text: @vaultah Subclassing `collections.UserString` does work for `+` and `*` operators, but not for `join`.. how do `__rmul__` and `join` differ?
comment on: http://stackoverflow.com/q/46868085
score: 0

http://stackoverflow.com/q/46836284
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Python 3 readline() does not work
tagged with: python
type: AnsweredQuestion
has body: The Text File: username password other The code: filepass = datafile.readline(1) filepass.rstrip('\n') datafile.close() entered_password = input("Enter Password") if entered_password == filepass: print ("Success") else: print ("Failure") Python always says "Failure" no matter what I type in. What do I need to do? Thanks in Advance.
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80620323
has comment: http://stackoverflow.com/comment/80620211
has comment: http://stackoverflow.com/comment/80620724
has answer: http://stackoverflow.com/a/46836425
has comment: http://stackoverflow.com/comment/80620369
accepted answer: http://stackoverflow.com/a/46836425
answer count: 1

http://stackoverflow.com/comment/80446286
comment on: http://stackoverflow.com/q/46750071
score: 0
has text: Yeah. `input()` waits for the user to respond, so the `print()`s don't happen until after the user responded when you call `input()` first.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46837554
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46837679
accepted answer: http://stackoverflow.com/a/46837679
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I'm new to Python and would very much appreciate your help! I have a dataframe with three columns and would like to combine the rows where the first two columns have the same associations (i.e. being in column A vs column B doesn't really matter in this situation) and sum their values in the third column. For example, starting with this dataframe: A B C x y 5 z z 6 y x 4 z y 3 y z 2 I would like to be able to produce a dataframe like this (combining x y with y x; and z y with y z): A B C x y 9 z z 6 y z 5 Any suggestions on how to do this? Here's my code so far: df = pd.DataFrame.from_dict({k:dict(v) for k,v in dic.items()}).fillna(0) MG_df = df.stack().reset_index().rename(columns {'level_0':'Source','level_1':'Target', 0:'Weight'}) pd.DataFrame(np.sort(MG_df'Source','Target'.values, axis=1)) MG_df.groupby(['Source','Target']).Weight.sum().reset_index() MG_df = MG_df[MG_df.Weight != 0]
tagged with: dataframe
has title: Python dataframe combining rows where first two column values inverse
tagged with: pandas

http://stackoverflow.com/comment/80561939
type: Comment
type: QuestionComment
score: 2
has text: By "null" do you mean `None`? Because in that case you'll get an `AttributeError`. Or an empty dictionary `{}`? You say you want a dictionary instead of a list, so where's your attempt to implement that? It would be straightforward to change the definition of `dd` to accommodate that, why not start there? And don't just *assert* that your question isn't a duplicate, that's no use to anybody - show your research, what have you read that you think others would consider duplicates and how precisely do they fail to answer your question?
comment on: http://stackoverflow.com/q/46807337

http://stackoverflow.com/a/46750845
has comment: http://stackoverflow.com/comment/80447666
score: 3
answers question: http://stackoverflow.com/q/46750772
type: Answer
has body: You can use .tolist(): # example data N = 20000 cdata = np.random.random(N).reshape(10, 20, 20, 5) adata = [True] * len(cdata) df = pd.DataFrame({"A":adata, "C":cdata.tolist()}) df.head() A C 0 True [[[0.18399037775743088, 0.6762324340882544, 0.... 1 True [[[0.9030084241016858, 0.4060105756597291, 0.4... 2 True [[[0.2659580640570838, 0.8247979431136298, 0.6... 3 True [[[0.9626035946363627, 0.16487112072561239, 0.... 4 True [[[0.034946598341842106, 0.17646725825025167, ... c = np.array(df.C.tolist()) c.shape # (10, 20, 20, 5)
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46750772

http://stackoverflow.com/comment/80732917
has text: @Khaine775 seems like you need do the exchange rate?
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46877673

http://stackoverflow.com/q/46820068
tagged with: join
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/80588133
answer count: 2
accepted answer: http://stackoverflow.com/a/46820286
has comment: http://stackoverflow.com/comment/80588042
favorite count: 0
has comment: http://stackoverflow.com/comment/80587670
tagged with: pandas
tagged with: python
tagged with: merge
type: AnsweredQuestion
has title: Join two dataframes along columns with non-unique index
has answer: http://stackoverflow.com/a/46820235
has comment: http://stackoverflow.com/comment/80587983
upvote count: 3
downvote count: 2
has body: I have two data frames that I want to join them along columns. The index is not unique: df1 = pd.DataFrame({'A': ['0', '1', '2', '2'],'B': ['B0', 'B1', 'B2', 'B3'],'C': ['C0', 'C1', 'C2', 'C3']}): A B C 0 0 B0 C0 1 1 B1 C1 2 2 B2 C2 3 2 B3 C3 df2 = pd.DataFrame({'A': ['0', '2', '3'],'E': ['E0', 'E1', 'E2']},index=[0, 2, 3]) A E 0 0 E0 1 2 E1 2 3 E2 A should be my index. what I want is: A B C E 0 0 B0 C0 E0 1 1 B1 C1 NAN 2 2 B2 C2 E1 3 2 B3 C3 E1 This pd.concat([df1, df2], 1) gives me error: Reindexing only valid with uniquely valued Index objects
has answer: http://stackoverflow.com/a/46820286
type: Question
possible better answer: http://stackoverflow.com/a/46820235

http://stackoverflow.com/a/46830369
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46830231
has body: df.loc[df['mycolumn'] != '0', 'mycolumn'] = 'not empty' or if the value is an int, df.loc[df['mycolumn'] != 0, 'mycolumn'] = 'not empty' df.loc[rows, cols] allows you to get or set a range of values in your DataFrame. First parameter is rows, in which case I'm using a boolean mask to get all rows that don't have a 0 in mycolumn. The second parameter is the column you want to get/set. Since I'm replacing the same column I queried from, it is also mycolumn. I then simply using the assignment operator to assign the value of 'not empty' like you wanted. New column containing 'not empty' If you want a new column to contain the 'not empty' so you're not contaminating your original data in mycolumn, you can do: df.loc[df['mycolumn'] != 0, 'myNewColumnsName'] = 'not empty'
upvote count: 5
score: 5
accepted answer of: http://stackoverflow.com/q/46830231
type: AcceptedAnswer

http://stackoverflow.com/a/46890238
upvote count: 0
has comment: http://stackoverflow.com/comment/80727634
has comment: http://stackoverflow.com/comment/80727880
score: -1
type: Answer
answers question: http://stackoverflow.com/q/46890172
has body: You have to add the path of your installation to the Environment variables. Simply go to the System Properties / Environment Variables / From there, create a new system variables and add your python path.
downvote count: 1

http://stackoverflow.com/a/48558721
score: 2
answers question: http://stackoverflow.com/q/46892085
has body: Google-resumable-media can be used to download file through chunks from GCS and smart_open to upload them to S3. This way you don't need to download whole file into memory. Also there is an similar question that addresses this issue Can you upload to S3 using a stream rather than a local file?
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/46901669
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: sorting
has body: I have a problem with MergeSort in Python-3.x. This is that the algorithm does not do the sorting. What's my mistakes? Can you help me? The code is: def mergeSort(lista): #Precondición: elem comparables #Postcondición: lista ordenada if len(lista) &lt; 2: return lista medio = len(lista) // 2 izq = mergeSort(lista[:medio]) der = mergeSort(lista[medio:]) return merge(izq,der) def merge(lista1,lista2): #Precondición: listas ordenadas #Postcondición: retorna lista con elem de lista1 y lista2 i,j = 0,0 resultado = [] while i&lt;len(lista1) and j&lt;len(lista2): if (lista1[i] &lt; lista2[j]): resultado.append(lista1[i]) i += 1 else: resultado.append(lista2[j]) j += 1 resultado += lista1[i:] resultado += lista2[j:] return resultado L = [6,7,-1,0,5,2,3,8] mergeSort(L) print(L) And the result is: [6, 7, -1, 0, 5, 2, 3, 8] [Finished in 0.2s]
has title: Problems with MergeSort in Python-3
has comment: http://stackoverflow.com/comment/80750209
upvote count: 1
answer count: 1
tagged with: mergesort
accepted answer: http://stackoverflow.com/a/46901738
linked to: http://stackoverflow.com/q/18761766
has comment: http://stackoverflow.com/comment/80750197
tagged with: python
has answer: http://stackoverflow.com/a/46901738

http://stackoverflow.com/a/46814794
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/122245310
type: Answer
has comment: http://stackoverflow.com/comment/109310214
has comment: http://stackoverflow.com/comment/80727498
accepted answer of: http://stackoverflow.com/q/46814200
upvote count: 10
score: 10
has comment: http://stackoverflow.com/comment/105415745
answers question: http://stackoverflow.com/q/46814200
has body: Passing sheetname=None will give you an OrderedDict with keys of the sheet name and values as dataframes, you then loop over that. import pandas as pd import sqlite3 db = sqlite3.connect(':memory:') dfs = pd.read_excel('somefile.xlsx', sheet_name=None) for table, df in dfs.items(): df.to_sql(table, db)

http://stackoverflow.com/q/46796795
tagged with: python
tagged with: folium
possible better answer: http://stackoverflow.com/a/46822314
type: AnsweredQuestion
has title: How do I achieve this in Folium?
type: Question
answer count: 2
has body: I am working on plotting the major earthquakes using Folium. I am able to plot all the instances, about 25000 of them. But the map starts looking very clumsy. I have used the following code: map1 = folium.Map(location=[80., -180], zoom_start=1) def color(magnitude): if magnitude&lt;6: col='green' elif [(magnitude&gt;6)&amp;(magnitude&lt;7.5)]: col='yellow' else: col='red' return col fg=folium.FeatureGroup(name="Earthquake Locations") for latitude,longitude,magnitude in zip(earthquakes['Latitude'][:30],earthquakes['Longitude'][:30],earthquakes['Magnitude'][:30]): fg.add_child(folium.Marker(location=[latitude,longitude],popup=(folium.Popup(magnitude)),icon=folium.Icon(color=color(magnitude)))) map1.add_child(fg) Now I want to make the plot look something like the first plot in the following R notebook: Notebook. Can someone help me in achieving such a plot, where in the individual points are clustered and as we zoom, the points show up. Thanks
has answer: http://stackoverflow.com/a/46822314
score: 0
tagged with: visualization
has answer: http://stackoverflow.com/a/46821533
accepted answer: http://stackoverflow.com/a/46821533

icinga
type: Tag
tags question: http://stackoverflow.com/q/46801078
tag name: icinga

http://stackoverflow.com/comment/80758109
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46905576
has text: what should happen to the 19:00 in `2005-07-15 17:00:00, 2005-07-17 18:00:00 , 2005-07-17 19:00:00 `

http://stackoverflow.com/comment/80742584
type: Comment
has text: @ Joe Iddon i did what you say and the result is deleting all the files but one. then rename it and rename it again and again till the list of names ends
comment on: http://stackoverflow.com/a/46896757
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80733293
type: Comment
comment on: http://stackoverflow.com/q/46892830
score: 0
has text: If you want to do things Properly, and don't have another reason to install the package globally, use a virtual environment based on the 2.7 installation. (It's been a while since I actively did Python, so I'm not sure what solution is the one to use these days, I remember using `virtualenv`.) That way you only use the full path to the 2.7 python once, then activate that env in your shell and "python", "pip" etc. will point into the env's base installation.
type: QuestionComment

http://stackoverflow.com/comment/80685675
type: AnswerComment
has text: upgraded to the newest version of pandas as suggested and still getting the same error message. Even if you think about it, what the snippet of code provided in the earlier comment by @Psidom do is that it takes the 2 lists in every row and put a '-' between them. What is desired is to take element by element in each list and do a one to one mapping between them so that the first string element in the first list in A is concatenated with the first string element in the first list in B and so on
comment on: http://stackoverflow.com/a/46866505
score: 0
type: Comment

http://stackoverflow.com/q/46772164
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/46772188
has body: I have a dataframe called Dataprep with 19 columns and 18484 raws. I have aggregated the columns I wanted with the code below: Dataprep.groupby('CustomerKey').OrderQuantity.agg('count') CustomerKey is the ID number for customers and orderquantity is the number of orders by each customer. The data look like 11000 - 1 11000 - 1 11000 - 1 11000 - 1 11001 - 1 11001 - 1 11001 - 1 11001 - 1 11002 - 1 11002 - 1 11002 - 1 11002 - 1 11002 - 1 11003 - 1 11003 - 1 11003 - 1 11003 - 1 11003 - 1 11004 - 1 11004 - 1 11004 - 1 11004 - 1 First column is customerkey and other one is orderquantity. My question is how would I apply this to the DataFrame Dataprep. I want to keep all other columns. Thanks
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/46772188
type: AnsweredQuestion
has title: How to apply aggregation and groupby to a DataFrame in python?

http://stackoverflow.com/a/46839088
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46839032
upvote count: 19
has comment: http://stackoverflow.com/comment/80626273
has comment: http://stackoverflow.com/comment/80626019
downvote count: 0
has comment: http://stackoverflow.com/comment/80626132
has body: I'd convert this to a datetime column and then use pd.TimeGrouper: dates = pd.to_datetime(df.date, format='%m-%d-%y') print(dates) 0 2017-01-01 1 2017-01-01 2 2017-01-01 3 2017-01-01 4 2017-01-02 5 2017-01-02 6 2017-01-10 7 2017-02-01 Name: date, dtype: datetime64[ns] df = (df.assign(date=dates).set_index('date') .groupby(['user_id', pd.TimeGrouper('3D')]) .sum() .reset_index()) print(df) user_id date val 0 1 2017-01-01 3 1 2 2017-01-01 2 2 2 2017-01-10 1 3 3 2017-01-01 1 4 3 2017-01-31 1 Similar solution using pd.Grouper: df = (df.assign(date=dates) .groupby(['user_id', pd.Grouper(key='date', freq='3D')]) .sum() .reset_index()) print(df) user_id date val 0 1 2017-01-01 3 1 2 2017-01-01 2 2 2 2017-01-10 1 3 3 2017-01-01 1 4 3 2017-01-31 1 Update: TimeGrouper will be deprecated in future versions of pandas, so Grouper would be preferred in this scenario (thanks for the heads up, Vaishali!).
type: Answer
has comment: http://stackoverflow.com/comment/80626390
score: 19
has comment: http://stackoverflow.com/comment/80626100
has comment: http://stackoverflow.com/comment/80626245
has comment: http://stackoverflow.com/comment/80626118
accepted answer of: http://stackoverflow.com/q/46839032

http://stackoverflow.com/a/46891286
score: 1
answers question: http://stackoverflow.com/q/46879688
has body: There are multiple ways you can represent relational field in DRF serializers. For your specific case SlugRelatedField suits better. class WordsSerializer(serializers.ModelSerializer): days = serializers.SlugRelatedField(many=True, slug_field='day`) class Meta: model = Words fields = ('word', 'days') But remember When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True.
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/80641510
type: QuestionComment
score: 0
has text: Where do those timestamp numbers come from? A Unix timestamp gives the number of seconds since the epoch. So the time span from 1408323255 to 1483196400 is around 866.587326 days.
comment on: http://stackoverflow.com/q/46846950
type: Comment

http://stackoverflow.com/q/46822744
type: AnsweredQuestion
upvote count: 2
score: 0
downvote count: 2
tagged with: selenium
has answer: http://stackoverflow.com/a/46822915
possible better answer: http://stackoverflow.com/a/46824375
type: Question
has body: Trying to run the following script to go to this website and click a link to export a csv. from selenium import webdriver driver=webdriver.Firefox() driver.get("https://www.draftkings.com/contest/gamecenter/46877680") elem1 = driver.find_element_by_link_text("Export Lineups to CSV") elem1.click() I get the following error and can't find a geckodriver. I pip installed selenium. I got this from an older video and I currently run Python 3.6 so that is probably part of the problem as well. Where am I going wrong? Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "C:\Program Files\Python36\lib\subprocess.py", line 707, in init restore_signals, start_new_session) File "C:\Program Files\Python36\lib\subprocess.py", line 992, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/mike/Desktop/Lineup1.py", line 2, in driver=webdriver.Firefox() File "C:\Program Files\Python36\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 144, in init self.service.start() File "C:\Program Files\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
has answer: http://stackoverflow.com/a/46824375
has comment: http://stackoverflow.com/comment/80594253
accepted answer: http://stackoverflow.com/a/46822915
has title: Click button script with Python
answer count: 2
favorite count: 0
linked to: http://stackoverflow.com/q/40208051
tagged with: geckodriver
tagged with: python
has comment: http://stackoverflow.com/comment/80609668
duplicate of: http://stackoverflow.com/q/40208051

http://stackoverflow.com/comment/80449546
comment on: http://stackoverflow.com/a/46751598
has text: @YaroslavSurzhikov I've tried that too before, the problem is tweepy has some authentication functionality which fails if i use one line for customtweepy and the rest for tweepy
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80563121
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46807792
has text: I still don't get the error message although I changed it to "OR"

http://stackoverflow.com/comment/80553903
score: 0
type: Comment
has text: How can i do that? Please! I'm new to django.
type: QuestionComment
comment on: http://stackoverflow.com/q/46802763

http://stackoverflow.com/comment/80655758
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46851735
type: Comment
has text: Retried your edit. Getting: selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (627, 14). Other element would receive the click: ...

http://stackoverflow.com/comment/80510192
comment on: http://stackoverflow.com/q/46781835
score: 0
has text: Try running `mysql` query separately, collect query output a text/csv file and then adding to `df`. That may help pinpoint the issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46905201
answer count: 1
has comment: http://stackoverflow.com/comment/80757808
has comment: http://stackoverflow.com/comment/80757168
has comment: http://stackoverflow.com/comment/80757378
has title: How to build a python server to communicate with a raspberry pi?
tagged with: sockets
accepted answer: http://stackoverflow.com/a/46906730
tagged with: python
has comment: http://stackoverflow.com/comment/80757195
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/80757130
has comment: http://stackoverflow.com/comment/80757464
downvote count: 1
has body: I'm an newbie to build a secure connection between python server and raspberry pi. I have a python server, and a raspberry pi at home. Currently, pi is using socket to listen a specific port when the python server is trying connect to pi. It's a low level networking interface. It's a simple but not secure method. Could anyone tell or point out a way to build a secure communication between python server and raspberry pi. It should be able to do following basic requirements. 1. Password check 2. When python server want some information from Pi, it connect to pi. After python server gets what it wanted, it disconnect to pi. Thanks!!
type: AnsweredQuestion
tagged with: server
has comment: http://stackoverflow.com/comment/80760363
has answer: http://stackoverflow.com/a/46906730
tagged with: iot
type: Question
tagged with: raspberry-pi
upvote count: 0

http://stackoverflow.com/q/46806895
has comment: http://stackoverflow.com/comment/80560781
type: UnansweredQuestion
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/3459098
has body: This is the only method I know of making a list of the same size with zeros. Just curious, is there another way? line = [13,20,0,44] result = [] for i in range(len(line)): result.append(0) print (result)
has comment: http://stackoverflow.com/comment/80560850
has answer: http://stackoverflow.com/a/46806921
score: 0
answer count: 1
has title: Another method of implementing '0' list in Python

http://stackoverflow.com/q/46902090
tagged with: ajax
has comment: http://stackoverflow.com/comment/80752516
tagged with: google-app-engine
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80761445
tagged with: webapp2
has title: Redirect function stops working after I implemented an AJAX function for the Post request
has comment: http://stackoverflow.com/comment/80883477
tagged with: javascript
has comment: http://stackoverflow.com/comment/80752260
has body: After I make a POST to the GAE, I want to render the HTML page that will display the data I just posted. Thus in the POST request, at the end, I call a GET request with the entity ID. It worked until I implemented the POST request with AJAX request (rather than just an HTML form), but now it won't work. This is the request that isn't working: self.redirect('/house/%s' % str(p.key.id())). My intuition says that it is because I'm am calling this from an AJAX function on the client side, and it is trying to go to a new page before that AJAX function is done. However, I'm not very good at JS or Python, so any help would be greatly appreciated. Thanks! A terminal is responding this: Magikarp uses Splash. It's not very effective. INFO 2017-10-24 04:03:00,931 module.py:832] default: "POST /house HTTP/1.1" 302 - INFO 2017-10-24 04:03:00,994 module.py:832] default: "GET /house/4554452040123423436 HTTP/1.1" 200 3024 def post(self): if not self.user: self.redirect('/home') data = json.loads(self.request.body) city = data["city"] state = data["state"] jsObject = data["jsObject"] if city and state: p = Post(parent = blog_key(), city = city, state = state, jsObject = jsObject) p.put() print ("Magikarp uses Splash. It's not very effective.") self.redirect('/house/%s' % str(p.key.id())) else: error = "city and state, please!" self.render("newhouse.html", city=city, state=state, error=error) function postRequest() { var city = $("#city").val(); var state = $("#state").val(); var jsObject = JSObject; $.ajax({ type: "POST", url: "/submit", contentType: "application/json; charset=utf-8", data: JSON.stringify({ "city": city, "state": state, "jsObject": jsObject }), dataType: "json" }) .done(function(jsonResponse) { $("#error").html(jsonResponse.message); }); }
type: Question
has comment: http://stackoverflow.com/comment/80752090
has comment: http://stackoverflow.com/comment/82072783

http://stackoverflow.com/a/46790369
answers question: http://stackoverflow.com/q/46789970
downvote count: 0
has body: Define the key you want to use for sorting as follows: print(sorted([(r, d, f) for r, d, f in os.walk('/home/vibhor/Downloads')], key=lambda x: len(x[2]), reversed=True)) reversed=True gives the answer in decreasing order.
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/80533894
has comment: http://stackoverflow.com/comment/80533974

http://stackoverflow.com/comment/80553647
score: 0
type: Comment
has text: Ok it's nearly what I'm looking for, but i want to except all the zeros from that meaning to leave the zeros alone work on other values or if I could replace the zeros from the mask with another value say 7, because they represent different labels
comment on: http://stackoverflow.com/a/46803222
type: AnswerComment

http://stackoverflow.com/q/46791798
tagged with: deployment
tagged with: ffmpeg
upvote count: 2
tagged with: python
downvote count: 1
has title: What are the ways to deploy python code on aws ec2?
type: AnsweredQuestion
score: 1
type: Question
tagged with: amazon-ec2
answer count: 1
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/46792730
has body: I have a python project and i want to deploy it on an AWS EC2 instance. My project has dependencies to other python libraries and uses programs installed on my machine. What are the alternatives to deploy my project on an AWS EC2 instance? Further details : My project consist on a celery periodic task that uses ffmpeg and blender to create short videos. I have checked elastic bean stalk but it seems it is tailored for web apps. I don't know if containerizing my project via docker is a good idea... The manual way and the cheapest way to do it would be : 1- Launch a spot instance 2- git clone the project 3- Install the librairies via pip 4- Install all dependant programs 5- Launch periodic task I am looking for a more automatic way to do it. Thanks.
accepted answer: http://stackoverflow.com/a/46792730

http://stackoverflow.com/comment/80687352
score: 0
type: QuestionComment
has text: @SuperSaiyan I installed `libjpeg-dev`, `zlib1g-dev`, and `libpng-dev`. Afterwards I ran `sudo python -m pip install pillow` and everything worked perfectly. Thanks!
type: Comment
comment on: http://stackoverflow.com/q/46869343

http://stackoverflow.com/q/46840474
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46841703
type: Question
tagged with: django
tagged with: python
has title: Form not saving object a redirect to new form view
has body: I am attempting to build an app the creates patient data, saves it, and displays it. Problem : When I populate the fields and click save it does not save the object and render data to the document object model. It reloads the page with the field data still in the fields. I am not sure what I have done wrong. The view, form and models code seem to be accurate. I welcome any useful assistance. Here is the code : models.py from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) first_Name = models.CharField(max_length = 80, null = True ) last_Name = models.CharField(max_length = 80, null = True ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) contact = models.CharField(max_length = 15, null = True) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, UpdateView from nesting.forms import Identity_Form, Symptom_Form from nesting.models import Identity_unique, Symptom_relation class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_Form() Identities = Identity_unique.objects.filter(user = request.user) var = {'form': form, 'Identities': Identities} return render(request, self.template_name, var) def post(self, request): form = Identity_Form(request.POST or None) content = None if form.is_valid(): NIS = form.save(commit = False) NIS.user = request.user NIS.save() content = form.cleaned_data['NIS'] form = Identity_Form() return redirect('nesting:nesting') var = {'form': form, 'content': content} return render(request,self.template_name, var) forms.py from django import forms from nesting.models import…
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80628832
has comment: http://stackoverflow.com/comment/80628862
type: UnansweredQuestion
tagged with: forms

http://stackoverflow.com/comment/80541731
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46796338
has text: I checked, and apparently it doesn't matter single or double quotes.

http://stackoverflow.com/comment/80639172
score: 1
type: Comment
type: QuestionComment
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
comment on: http://stackoverflow.com/q/46843539

http://stackoverflow.com/q/46787980
tagged with: ubuntu
tagged with: conda
score: 0
has comment: http://stackoverflow.com/comment/80528421
tagged with: python
has body: I was using an anaconda environment on Ubuntu that had tensoflow, scipy, jupyter, pandas, numpy and many other packages installed. Then I decided to install opencv on this same environment and after doing that, all of the previous packages were gone except for numpy. I used conda install opencv for installing opencv and after running conda list, I realized I have lost the packages I mentioned above. I don't understand how installing a new package deletes others, at least without asking for my permission first. And I really hope there is a way to retain the installed packages because I don't want to reinstall tensorflow again. Thank you. Additionally, using the revisions feature in anaconda didn't show the previous package list that contained tensorflow, etc. Edit: I tried something new today. Without being in any environment I typed conda list and the output actually contained all the packages I previously installed (I can show you the output if it's really necessary). However when I activate the environment I work on I don't find these packages there, although they were there before installing opencv. Can you tell me how to make these packages accessible in the working environment again?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80561343
has title: Package list changed after installing a new package on Anaconda Ubuntu 16.04
type: Question
tagged with: anaconda

http://stackoverflow.com/q/46771388
has comment: http://stackoverflow.com/comment/80489008
has title: Can you create a list of variables in Python without instantiating the variables?
type: AnsweredQuestion
tagged with: list
upvote count: 3
possible better answer: http://stackoverflow.com/a/46771862
accepted answer: http://stackoverflow.com/a/46771657
tagged with: loops
has answer: http://stackoverflow.com/a/46771862
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80488312
tagged with: variables
has comment: http://stackoverflow.com/comment/80489429
has comment: http://stackoverflow.com/comment/80488269
has comment: http://stackoverflow.com/comment/80488740
has comment: http://stackoverflow.com/comment/80488257
score: 2
has answer: http://stackoverflow.com/a/46771657
favorite count: 0
has comment: http://stackoverflow.com/comment/80488344
has body: I'm trying to make my code cleaner. I want to do something like: gesture_sensor_data = [nod_gyro, nod_acc, swipe_left_gyro, swipe_right_acc, etc.] I have this right now: nod_gyro, nod_acc = fill_gyro_and_acc_data(nod_intervals, merge) swipe_right_gyro, swipe_right_acc = fill_gyro_and_acc_data(swipe_right_intervals, merge) swipe_left_gyro, swipe_left_acc = fill_gyro_and_acc_data(swipe_left_intervals, merge) whats_up_gyro, whats_up_acc = fill_gyro_and_acc_data(whats_up_intervals, merge) I want to run a loop through the gesture_sensor_data. Is there a way to do this? Some kind of structure or something? EDIT: I'll just show my full code in this function for context. def generate_gesture_files(i): nod_intervals, swipe_left_intervals, swipe_right_intervals, whats_up_intervals = generate_gesture_intervals(i) merge = pandas.read_csv(final_user_study_path + "/P" + str(i) + "/DataCollection/data/merge.csv") nod_gyro, nod_acc = fill_gyro_and_acc_data(nod_intervals, merge) swipe_right_gyro, swipe_right_acc = fill_gyro_and_acc_data(swipe_right_intervals, merge) swipe_left_gyro, swipe_left_acc = fill_gyro_and_acc_data(swipe_left_intervals, merge) whats_up_gyro, whats_up_acc = fill_gyro_and_acc_data(whats_up_intervals, merge) return nod_gyro, nod_acc, swipe_right_gyro, swipe_right_acc, swipe_left_gyro, swipe_right_acc, whats_up_gyro, whats_up_acc
has comment: http://stackoverflow.com/comment/80488333
tagged with: python
has comment: http://stackoverflow.com/comment/80488456
linked to: http://stackoverflow.com/q/3204245

http://stackoverflow.com/comment/80695189
type: QuestionComment
comment on: http://stackoverflow.com/q/46873915
score: 0
has text: I have included it
type: Comment

http://stackoverflow.com/q/46867841
type: Question
has comment: http://stackoverflow.com/comment/80683048
has comment: http://stackoverflow.com/comment/80683106
has title: how to assign new column of values by a specific column?
tagged with: function
answer count: 2
has answer: http://stackoverflow.com/a/46867891
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/46868101
favorite count: 0
has answer: http://stackoverflow.com/a/46868101
has comment: http://stackoverflow.com/comment/80683114
tagged with: python
accepted answer: http://stackoverflow.com/a/46867891
type: AnsweredQuestion
score: 3
has body: I have a data like this: Id Date 12 2017 12 2016 13 2014 13 2013 14 2017 14 2015 14 2016 Also I have a list of Ids that if Id is in 'check_list' should assign a value 'On',otherwise assign 'Off' : check_list= [12,13] So data should be like this: Id Date Check 12 2017 On 12 2016 On 13 2014 On 13 2013 On 14 2017 Off 14 2015 Off 14 2016 Off Code I have tried to define a function but i don't know why it just returns ids, here is the code: def check(): if df['Id'] in check_list: return 'On' else: return 'Off' f['Check'] = df['Id'].apply(check())
has comment: http://stackoverflow.com/comment/80683098
upvote count: 3

http://stackoverflow.com/q/46898796
has answer: http://stackoverflow.com/a/46898878
tagged with: django
accepted answer: http://stackoverflow.com/a/46898878
type: Question
score: 3
tagged with: forms
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm still relatively new to Django and I've managed to set up a password change form using my template. I don't know how to change the order and labels for the elements. I have attached an image showing how the form currently looks, I would like to move the second text box (new password) underneath the explanation text and to change the first and last input labels. Could you please point me in the right direction?
tagged with: python
has title: Reorder form elements and change labels on django password change form
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/46769786
accepted answer: http://stackoverflow.com/a/46769876
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46769876
tagged with: dataframe
has body: I have a dataframe like this import pandas as pd df = pd.DataFrame({'id' : [1, 1, 1, 1, 2, 2, 2, 3, 3, 3], \ 'counter' : [1, 2, 3, 4, 1, 2, 3, 1, 2, 3], \ 'status':['a', 'b', 'b' ,'c', 'a', 'a', 'a', 'a', 'a', 'b'], \ 'additional_data' : [12,35,13,523,6,12,6,1,46,236]}, \ columns=['id', 'counter', 'status', 'additional_data']) df Out[37]: id counter status additional_data 0 1 1 a 12 1 1 2 b 35 2 1 3 b 13 3 1 4 c 523 4 2 1 a 6 5 2 2 a 12 6 2 3 a 6 7 3 1 a 1 8 3 2 a 46 9 3 3 b 236 The id column indicates which data belongs together, the counter indicates the order of the rows, and status is a special status code. I want to drop all rows after the first occurence of a row with status='b', keeping the first row with status='b'. Final output should look like this id counter status additional_data 0 1 1 a 12 1 1 2 b 35 4 2 1 a 6 5 2 2 a 12 6 2 3 a 6 7 3 1 a 1 8 3 2 a 46 9 3 3 b 236 All help is, as always, greatly appreciated.
tagged with: pandas
answer count: 1
downvote count: 0
has title: Python dataframe, drop everything after a certain record
favorite count: 0

time
tags question: http://stackoverflow.com/q/46851868
tags question: http://stackoverflow.com/q/46904778
tags question: http://stackoverflow.com/q/46902433
tags question: http://stackoverflow.com/q/46860706
tags question: http://stackoverflow.com/q/46836922
tags question: http://stackoverflow.com/q/46823064
tag name: time
tags question: http://stackoverflow.com/q/46856981
tags question: http://stackoverflow.com/q/46903195
type: Tag
tags question: http://stackoverflow.com/q/46882803

http://stackoverflow.com/q/46778249
accepted answer: http://stackoverflow.com/a/46778477
answer count: 1
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to write source code snippets from scripts and other relevant information to csv file, where each cell would contain one piece of information. Desired output would be like: function name, number of lines, source code helloWorld, 3, { printf("hello, world\n"); } fooBar, 5, { const char *foo = "Hello"; const char *bar = "World!"; fprintf(stdout, "%s %s\n", foo, bar); return 0; } where each source code snippet should be in a single cell while preserving the code structure. Below is the code: with open('functionInformation.csv', 'wb') as csvOut: csvwriter = csv.writer(csvOut, delimiter = ',') csvwriter.writerow(['function name', 'number of lines', 'source code']) for functionObject in functionObjectRepository: csvwriter.writerow([functionObject.funcName, functionObject.numLines, functionObject.sourceCode]) where functionObject is the object with attributes like the name of the function (funcName), number of lines of code (numLines), and the actual source code (sourceCode). Output I am getting right now looks like: helloWorld, 3, { printf("hellp, world\n"); } fooBar, ....
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46778477
has title: python csv writer to write source code snippets to a single cell
type: Question

http://stackoverflow.com/q/46840266
has answer: http://stackoverflow.com/a/46840383
has body: Question: I currently have a process of taking a file from yesterday, comparing it to today's file, and dropping all values that haven't changed. The idea is to limit the amount of data being uploaded to a database to only data that has changed and is not currently in the DB. I was recently introduced to the function, combine_first, and I realized that I could quickly get an updated merged file, but I'm not sure if there is a way to also find values that have not changed. Data: data = { "inventory number": { "1236": "110", "5188": "101", "19497": "111", "5123": "010", "27358": "011" }, "cost": { "1236": 20.80, "5188": 28.86, "19497": 112.69, "5123": 165.03, "27358": 54.02 }, "map": { "1236": "True", "5188": "True", "19497": "True", "5123": "True", "27358": "False" }, "cat": { "1236": "CONSUMABLE", "5188": "ELECTRONICS", "19497": "POWER TOOL", "5123": "POWER TOOL", "27358": "APPLIANCES" } } dest = pd.DataFrame(data=data) data = { "inventory number": { "1236": "110", "5188": "101", "19497": "111", "5123": "010", "27358": "011" }, "cost": { "1236": 21.80, "5188": 33.86, "19497": 100.69, "5123": 169.03, "27358": 49.99 }, "map": { "1236": "True", "5188": "True", "19497": "True", "5123": "False", "27358": "False" }, "cat": { "1236": "CONSUMABLE", "5188": "ELECTRONICS", "19497": "Electronics", "5123": "POWER TOOL", "27358": "Home/Kitchen" } } source = pd.DataFrame(data=data) Append and find duplicates solution resulting in desired output: icol = 'inventory number' combined = source.append(dest) combined.dropna(axis=0, subset=[icol], inplace=True) i = combined.groupby(icol).cumcount() transposed = combined.set_index([icol,i]).unstack(0).T cleaned = transposed[transposed[0]!=transposed[1]].unstack(0)[0].reset_index() cleaned.fillna(values=np.nan, inplace=True) Desired Output: data = { "inventory number": { "0": "010", "1": "011", "2": "101", "3": "110", "4": "111" }, "cat": { "0": np.nan, "1": "Home\\/Kitchen", "2": np.nan, "3": np.nan, "4": "Electronics" }, "cost": { "0": 1…
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80628553
accepted answer: http://stackoverflow.com/a/46840383
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has title: Is there a drop duplicates option with combine first (pandas)
score: 1
has comment: http://stackoverflow.com/comment/80628502
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/80568087
has text: Yes indeed! Thank you so much.
comment on: http://stackoverflow.com/a/46810378
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46868072
answer count: 2
has title: Randomly select value 1 in list and get index
has comment: http://stackoverflow.com/comment/80683525
upvote count: 0
accepted answer: http://stackoverflow.com/a/46868155
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/46868319
has answer: http://stackoverflow.com/a/46868155
possible better answer: http://stackoverflow.com/a/46868319
downvote count: 6
type: AnsweredQuestion
score: -6
has body: I have a list y of integers made up of 1's or 0's. For example, y = [1,0,0,0,0,1,0] I wish to randomly select two values in the list y where it equals 1 and get the index of these items in the list. For example, index = [0,5]
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/80683483

object-composition
tags question: http://stackoverflow.com/q/46883517
tag name: object-composition
type: Tag

http://stackoverflow.com/comment/94554485
type: AnswerComment
type: Comment
score: 1
has text: To me, including the C files in the repo seems contrary to the goal of ensuring consistent builds. It would introduce a second source of truth and would prevent having a centralized automated build environment, since part of the build would be manual and on the developer's machine, so the full build environment would be dependent on whoever made the last commit.
comment on: http://stackoverflow.com/a/46787348

http://stackoverflow.com/comment/80520773
has text: thanks that works thank you. could i ask one more thing please. lets say there are 3 columns that have the number 0 but within each of those 3 column the number 0 means different such as, columns one 0 = yes column two 0 = red and column three 0 = fast. with the code you given me which works but it gives 0 a default of true. how would i be able to assign 0 to other words in different columns?
comment on: http://stackoverflow.com/a/46786916
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80750087
comment on: http://stackoverflow.com/q/46901638
has text: You could try `for k in FPKM: print FPKM[k]`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80737644
comment on: http://stackoverflow.com/a/46876886
score: 1
type: AnswerComment
has text: Yep, well spotted, I removed them.
type: Comment

http://stackoverflow.com/q/46779821
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46779868
tagged with: python
has comment: http://stackoverflow.com/comment/80505700
has answer: http://stackoverflow.com/a/46779943
tagged with: list
has comment: http://stackoverflow.com/comment/80505626
has comment: http://stackoverflow.com/comment/80505743
has title: Converting strings within a list into floats
type: Question
has comment: http://stackoverflow.com/comment/80505664
has answer: http://stackoverflow.com/a/46779933
has body: I have a list of numerical values that are of type "string" right now. Some of the elements in this list have more than one value, e.g.: AF=['0.056', '0.024, 0.0235', '0.724', '0.932, 0.226, 0.634'] The other thing is that some of the elements might be a . With that being said, I've been trying to convert the elements of this list into floats (while still conserving the tuple if there's more than one value), but I keep getting the following error: ValueError: could not convert string to float: . I've tried a LOT of things to solve this, with the latest one being: for x in AF: if "," in x: #if there are multiple values for one AF elements= x.split(",") for k in elements: #each element of the sub-list if k != '.': k= map(float, k) print(k) #check to see if there are still "." else: pass But when I run that, I still get the same error. So I printed k from the above loop and sure enough, there were still . in the list, despite me stating NOT to include those in the string-to-float conversion. This is my desired output: AF=[0.056, [0.024, 0.0235], 0.724, [0.932, 0.226, 0.634]]
score: 0
answer count: 3
tagged with: string
tagged with: tuples

http://stackoverflow.com/comment/80723199
score: 0
type: Comment
has text: The logic is correct, you need to return the values directly instead of saving it in `score` variable. At first i also thought logic is wrong, but it isnt. :)
comment on: http://stackoverflow.com/a/46888145
type: AnswerComment

http://stackoverflow.com/q/46782289
has body: I have a Pandas dataframe as follows: df = open high low close Timestamp 2014-01-07 13:18:00 874.67040 892.06753 874.67040 892.06753 2014-01-07 13:19:00 NaN NaN NaN NaN 2014-01-07 13:20:00 NaN NaN NaN NaN 2014-01-07 13:21:00 883.23085 883.23085 874.48165 874.48165 2014-01-07 13:22:00 NaN NaN NaN NaN For each of the NaN's, they should take the value of the previous period's close. Edit: I have tried using df.fillna(method='ffill') but it makes each NaN take values directly above it. I would like each NaN to take only the value of Close before it. Using ffill yields: open high low close Timestamp 2014-01-07 13:18:00 874.67040 892.06753 874.67040 892.06753 2014-01-07 13:19:00 874.67040 892.06753 874.67040 892.06753 But I am looking for: open high low close Timestamp 2014-01-07 13:18:00 874.67040 892.06753 874.67040 892.06753 2014-01-07 13:19:00 892.06753 892.06753 892.06753 892.06753
tagged with: dataframe
type: Question
has title: Fill in NaNs with previous values of a specific column in Python
answer count: 2
has answer: http://stackoverflow.com/a/46782695
has comment: http://stackoverflow.com/comment/80511018
has comment: http://stackoverflow.com/comment/80510900
possible better answer: http://stackoverflow.com/a/46782695
linked to: http://stackoverflow.com/q/27905295
has comment: http://stackoverflow.com/comment/80510947
tagged with: pandas
has answer: http://stackoverflow.com/a/46782629
favorite count: 0
upvote count: 8
tagged with: python
has comment: http://stackoverflow.com/comment/80511140
linked to: http://stackoverflow.com/q/45262040
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46782629
has comment: http://stackoverflow.com/comment/80511326
score: 7

http://stackoverflow.com/a/46822667
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: Use a list comprehension lst = [['a','1', '2'], ['b', 1, 2], ['c', 1, 2], ['b', 3, 4]] lst = [x for x in lst if x[0] != 'b'] print(lst) prints [['a', '1', '2'], ['c', 1, 2]]
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46822640
answers question: http://stackoverflow.com/q/46822640

http://stackoverflow.com/comment/80672627
type: Comment
has text: Truthfully, I thought of this myself, but I wanted something a little less... loopy.
comment on: http://stackoverflow.com/a/46862564
score: 0
type: AnswerComment

http://stackoverflow.com/q/46839032
has answer: http://stackoverflow.com/a/46839088
type: AnsweredQuestion
upvote count: 9
tagged with: group-by
type: Question
score: 9
answer count: 2
has title: Grouping by date range with pandas
possible better answer: http://stackoverflow.com/a/46839402
downvote count: 0
accepted answer: http://stackoverflow.com/a/46839088
has answer: http://stackoverflow.com/a/46839402
favorite count: 0
has body: I am looking to group by two columns: user_id and date; however, if the dates are close enough, I want to be able to consider the two entries part of the same group and group accordingly. Date is m-d-y user_id date val 1 1-1-17 1 2 1-1-17 1 3 1-1-17 1 1 1-1-17 1 1 1-2-17 1 2 1-2-17 1 2 1-10-17 1 3 2-1-17 1 The grouping would group by user_id and dates +/- 3 days from each other. so the group by summing val would look like: user_id date sum(val) 1 1-2-17 3 2 1-2-17 2 2 1-10-17 1 3 1-1-17 1 3 2-1-17 1 Any way someone could think of that this could be done (somewhat) easily? I know there are some problematic aspects of this. for example, what to do if the dates string together endlessly with three days apart. but the exact data im using only has 2 values per person.. Thanks!
tagged with: pandas-groupby
tagged with: pandas
tagged with: datetime
tagged with: python

http://stackoverflow.com/a/46836146
has comment: http://stackoverflow.com/comment/80620922
has body: You are creating a generator, then using yield from, which essentially flattens. Instead, you'll want to materialize the generator instead of yielding from it: In [1]: def rec_map(l, f): ...: for v in l: ...: if isinstance(v, list): ...: yield list(rec_map(v, f)) ...: else: ...: yield f(v) ...: In [2]: a = ["0", ["1", "2", ["3", "4"]], [[[[["5"]]]]]] ...: In [3]: list(rec_map(a, lambda x: x + "_tweaked")) Out[3]: ['0_tweaked', ['1_tweaked', '2_tweaked', ['3_tweaked', '4_tweaked']], ['5_tweaked']] The problem you are encountering is that it is much more difficult to do this with a generator, because you have to carefully curate what is returned. Honestly, it doesn't seem like you even need a generator, just use: In [16]: def rec_map(l, f): ...: if isinstance(l, list): ...: return [rec_map(v, f) for v in l] ...: elif isinstance(l, dict): ...: return {k:rec_map(v, f) for k,v in l.items()} ...: else: ...: return f(l) ...: In [17]: rec_map(b, lambda x: x + '_tweaked') Out[17]: {'a': ['0_tweaked', '1_tweaked'], 'b': '2_tweaked', 'c': {'d': [{'e': ['3_tweaked']}]}} Also, don't use collections.Iterable, check explicitely for thet ypes you are handling. Note: In [18]: isinstance('I am a string but I am iterable!', collections.Iterable) Out[18]: True
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80622150
accepted answer of: http://stackoverflow.com/q/46835876
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46835876

http://stackoverflow.com/comment/80676668
comment on: http://stackoverflow.com/q/46856915
score: 0
type: Comment
type: QuestionComment
has text: But how do I incorporate my_weights into a constant tensor at the desired positions? Also, I don't want to prevent them to stop from being trainable, unless by my_weights you meant the "constant" part of the matrix itself.

http://stackoverflow.com/comment/80611731
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46831964
type: QuestionComment
has text: chepner - The other direction is usually the problem. You put %d and got a string...

http://stackoverflow.com/a/46903864
has body: You can't execute a module from within other module, because modules in Ansible are self-contained entities, that are packaged on the controller and delivered to remote host for execution. But there are action plugins for this situations. You can create action plugin spt_module (it will be executed locally on Ansible controller) that can in turn execute several different modules, based on lan/vnic parameters. This is how your action (spt_module.py) plugin may look like (very simplified): from ansible.plugins.action import ActionBase class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): result = super(ActionModule, self).run(tmp, task_vars) vnic_list = self._task.args['LAN']['VNIC'] common_args = {} common_args['name'] = self._task.args['name'] res = {} res['create_server'] = self._execute_module(module_name='ls_server_module', module_args=common_args, task_vars=task_vars, tmp=tmp) for vnic in vnic_list: module_args = common_args.copy() module_args['other_args'] = vnic['other_args'] res['vnic_'+vnic['name']] = self._execute_module(module_name='vnic_ether_module', module_args=module_args, task_vars=task_vars, tmp=tmp) return res Code is not tested (bugs, typos possible).
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80771226
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/80771572
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46893066
answers question: http://stackoverflow.com/q/46893066
score: 10

http://stackoverflow.com/comment/80748134
type: Comment
type: QuestionComment
score: 2
has text: It's fine that you're new to Python, but good Stackoverflow questions include your own attempts at the solution. https://stackoverflow.com/help/asking You may [edit] your question to include more information
comment on: http://stackoverflow.com/q/46900467

http://stackoverflow.com/comment/80457106
score: 0
has text: the error is ' that at least 3 vertices have to be chosen' although i defined them in the list 'triangle1'
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46755129

http://stackoverflow.com/comment/80665058
has text: But wsgi.py is in the directory.... :/
comment on: http://stackoverflow.com/q/46858541
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80738523
type: AnswerComment
has text: hey sorry for the late accept. I used your code, and I was able to export it to csv file, but when I opened the csv file in Excel, it created an empty line between each lines. I edited the post so that you can see how it is
comment on: http://stackoverflow.com/a/46870867
type: Comment
score: 0

http://stackoverflow.com/comment/80539281
comment on: http://stackoverflow.com/q/46796266
score: 0
type: QuestionComment
type: Comment
has text: How different were they? There's a few ways of running `timeit`

http://stackoverflow.com/comment/81875058
type: QuestionComment
has text: AFAIK, pickle is a little bit slow while packing the huge data. I use protobuf and zmq to communicate between different process, it's way more faster.
score: 0
comment on: http://stackoverflow.com/q/46863560
type: Comment

http://stackoverflow.com/comment/80510458
type: AnswerComment
score: 0
has text: Thank you man, I accepted your answer and tried the program. However, now I got permission to use `itertools` or a big range instead. I'd be interested in using either this solution or one of the others, whichever is more appropiate, but I still need a little help to understand how I can store values from the inputs at the foor loop. If you have any advice, I would appreciate it, I made a new [question](https://stackoverflow.com/questions/46782017/how-to-save-values-from-a-for-loop-python-3) if you prefer to reply there, in case you have any advice. Thanks again man! :)
type: Comment
comment on: http://stackoverflow.com/a/46763245

http://stackoverflow.com/comment/80496341
comment on: http://stackoverflow.com/q/46775388
score: 0
type: Comment
type: QuestionComment
has text: Is that your desired output?

alias
tags question: http://stackoverflow.com/q/46765803
type: Tag
tag name: alias

http://stackoverflow.com/a/47138757
has body: I check it like this now: # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function import os import subx import unittest class Test(unittest.TestCase): def test_readme_rst_valid(self): base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) subx.call(cmd=['python', os.path.join(base_dir, 'setup.py'), 'check', '--metadata', '--restructuredtext', '--strict']) Source: https://github.com/guettli/reprec/blob/master/reprec/tests/test_setup.py
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46766570
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81570942
has comment: http://stackoverflow.com/comment/81840707
type: Answer
has comment: http://stackoverflow.com/comment/81623611
answers question: http://stackoverflow.com/q/46766570

http://stackoverflow.com/comment/80730593
type: Comment
type: QuestionComment
has text: @roganjosh yea it's just the syntax, and the fact that i didn't really know what to google, so I was struggling to find an explanation. Having googled list comprehension I'm definitely on the right track, thanks for the help
score: 1
comment on: http://stackoverflow.com/q/46891432

error-messaging
type: Tag
tags question: http://stackoverflow.com/q/46797134
tag name: error-messaging

http://stackoverflow.com/a/46767535
has body: I don't really see the point in c* variables other than c itself in your example. Can you try the following, ? def dtr(x, y): c = os.listdir(str(x)) for fname in c: os.rename(fname, fname.replace(str(y), '')) As I understand, that would do what you want (rename the files/ folders in x path, removing string passed in y) However, as I understand the community: Try and describe what you are trying to do, not just what you're getting Try and make your code language-independent
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46767256
score: 1

http://stackoverflow.com/comment/80629817
comment on: http://stackoverflow.com/q/46840875
type: QuestionComment
has text: Assuming you mean mod_wsgi and not uWSGI as you tagged the question. The error message in title of question looks to be from mod_wsgi and not uWSGI.
score: 0
type: Comment

http://stackoverflow.com/comment/80574966
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46813929
has text: how would i use this with my code above? could you show me please
type: Comment

http://stackoverflow.com/comment/80528005
type: Comment
has text: @seanysull this is the point of providing a minimal and complete verifiable example. Without it, I can’t be certain what you are talking about.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/46779693

http://stackoverflow.com/a/46864702
type: Answer
has comment: http://stackoverflow.com/comment/119470781
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/128187920
has comment: http://stackoverflow.com/comment/119471068
upvote count: 4
has body: Yes, Python's __init__ is analogous to C++'s constructor. Both are typically where non-static data members are initialized. In both languages, these functions take the in-creation object as the first argument, explicit and by convention named self in Python and implicit and by language named this in C++. In both languages, these functions can return nothing. One notable difference between the languages is that in Python base-class __init__ must be called explicitly from an inherited class __init__ and in C++ it is implicit and automatic. C++ also has ways to declare data member initializers outside the body of the constructor, both by member initializer lists and non-static data member initializers. C++ will also generate a default constructor for you in some circumstances. Python's __new__ is analogous to C++'s class-level operator new. Both are static class functions which must return a value for the creation to proceed. In C++, that something is a pointer to memory and in Python it is an uninitialized value of the class type being created. Python's __del__ has no direct analogue in C++. It is an object finalizer, which exist also in other garbage collected languages like Java. It is not called at a lexically predetermined time, but the runtime calls it when it is time to deallocate the object. __exit__ plays a role similar to C++'s destructor, in that it can provide for deterministic cleanup and a lexically predetermined point. In C++, this tends to be done through the C++ destructor of an RAII type. In Python, the same object can have __enter__ and __exit__ called multiple times. In C++, that would be accomplished with the constructor and destructor of a separate RAII resource holding type. For example, in Python given an instance lock of a mutual exclusion lock type, one can say with lock: to introduce a critical section. In C++, we create an instance of a different type taking the lock as a parameter std::lock_guard g{lock} to accomplish the same thing. The Py…
has comment: http://stackoverflow.com/comment/119469061
accepted answer of: http://stackoverflow.com/q/46864368
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/119470520
answers question: http://stackoverflow.com/q/46864368

http://stackoverflow.com/comment/80747059
comment on: http://stackoverflow.com/q/46889296
has text: i guess not everyone has a sense of humor. Anyway you might post your answer as an answer.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80468230
has text: The reason I didn't use dictionary is because the widgets in my code could be label, entry, or optionmenu. Is there an example how I could use dictionary for different widget type with different widget name? Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46761013
type: QuestionComment

http://stackoverflow.com/comment/80629129
type: Comment
has text: yeah im actually using linux on virtualbox so i think this could help me THANKS
comment on: http://stackoverflow.com/a/46840632
type: AnswerComment
score: 0

http://stackoverflow.com/q/46850792
has comment: http://stackoverflow.com/comment/80651140
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/80656558
tagged with: arrays
type: UnansweredQuestion
tagged with: python
has body: I have a list defined inside the init function of my class. I want to pass it as a parameter inside a function defined inside the same class. This function is looping, each time it takes a user_input and then performs operation on the list defined as other functions inside the parent class. How can I do this? Each time either the program takes a new list instead of operating on the old one after each loop, or there is a syntactical error. This is the parent class and init function: class game: def __init__(self): import random self.inducerlist=[0,1,2,3] self.myArray=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] self.myArray[random.choice(self.inducerlist)][random.choice(self.inducerlist)]=2 And this is the function def users_choice(self,user_input,self.myArray=self.myArray): if user_input=='u': game.up(self) elif user_input=='d': game.down(self) elif user_input=='l': game.left(self) elif user_input=='r': game.right(self) while True: print self.myArray[0][0],"\t",self.myArray[0][1],"\t",self.myArray[0][2],"\t",self.myArray[0][3],"\n" print self.myArray[1][0],"\t",self.myArray[1][1],"\t",self.myArray[1][2],"\t",self.myArray[1][3],"\n" print self.myArray[2][0],"\t",self.myArray[2][1],"\t",self.myArray[2][2],"\t",self.myArray[2][3],"\n" print self.myArray[3][0],"\t",self.myArray[3][1],"\t",self.myArray[3][2],"\t",self.myArray[3][3],"\n" user_input = raw_input("u for upward direction, d for downwards, l for left and r for Right") game.users_choice(self,user_input,self.myArray=self.myArray) self.listfori = [] self.listforj = [] count = 0 for i in range(0,4): for j in range(0,4): if self.myArray[i][j]==0: count+=1 self.listfori.append(i) self.listforj.append(j) if count &gt; 0: if count &gt; 1: randomindex = listfori.index(random.choice(listfori)) self.myArray[listfori[randomindex]][listforj[randomindex]]=2 else: self.myArray[listfori[0]][listforj[0]]=2 else: break print "Game over"
answer count: 0
has comment: http://stackoverflow.com/comment/80656666
has title: Looping function defined inside classes
tagged with: loops
type: Question

http://stackoverflow.com/q/46790388
has answer: http://stackoverflow.com/a/46794669
has title: Unable to extract value for Z3 EnumSort in z3py
tagged with: smt
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am currently trying to encode a problem into Z3, and I wish to model a "tristate" Boolean (i.e., a Boolean with true, false and unknown). Here is how I have modelled it: #!/usr/bin/env python import z3 from collections import OrderedDict TristateValues = ["True", "False", "Unknown"] Tristate, consts = z3.EnumSort("Tristate", TristateValues) TristateValues = OrderedDict(zip(TristateValues, consts)) s = z3.Solver() x = z3.Const("x", Tristate) s.add(x != TristateValues["Unknown"]) value = s.check() if value == z3.sat: m = s.model() print str(m.eval(x)) else: print str(value) # EOF And on this small example, things work well, and I get values such as True or False. However, on larger examples, I get results such as: Tristate!val!0 Tristate!val!1 Tristate!val!2 Clearly, it seems that there would be a mapping between these "Tristate" strings and the real values, so I wrote something like this: ModelToTristate = {} as_list = list(TristateValues.keys()) for idx in range(0, len(as_list)): ModelToTristate["Tristate!val!{:d}".format(idx)] = as_list[idx] to try and map back between the values (this is why the use of OrderedDict is important to preserve the ordering). And, initially, it seemed that this worked. However, I then hit some more, stranger errors: I'd eventually get lookup errors into ModelToTristate where it seems I was indeed getting the correct value for calling str on the result of model.eval() (i.e., Z3 would give True, False, etc. rather than than Tristate!val!*) I'd get inconsistencies in the model (e.g., even when asserting x == Tristate["False"], checking the look-up would result in model.eval(x) == Tristate!val!1, where Tristate!val!1 maps to True) For this last issue, I think there is a lookup problem, rather than Z3 giving incorrect values. So, my question is: what is causing Z3 to use these Tristate!val!* strings, and can I "force" Z3 to use the correct values (i.e., True, False, Unknown)? I am using Z3 4.5.0. Update after checking it, it seems that thi…
upvote count: 1
tagged with: z3py
type: Question
tagged with: z3
score: 1

http://stackoverflow.com/comment/80724511
type: Comment
comment on: http://stackoverflow.com/a/46888308
type: AnswerComment
score: 0
has text: @Ajax1234 This is overkill. You open the file without closing it then you implement a json parser using regular expressions.

http://stackoverflow.com/q/46840536
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80628958
has comment: http://stackoverflow.com/comment/80628932
has comment: http://stackoverflow.com/comment/80628933
type: Question
has body: Warning: beginner here: So I am reading in a text file that is in the form of a json file. Since the son file is just like a dictionary I want to address parts of the json like I would a dictionary but I don't know how to do this. This is the little bit of what i have: code: with open("trump.txt","r") as lines: for line in lines: print(line) what this prints: {"created_at":"Wed Sep 27 01:19:39 +0000 2017","id":912849180741087232,"id_str":"912849180741087232","text":"RT @TheRickWilson: I see the clickservatives are out in force screaming there were special circumstances in AL.\n\nYes, it's because Trump ca\u2026","source":"\u003ca href=\"http://twitter.com/download/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":66914769,"id_str":"66914769","name":"Kathy","screen_name":"mydoggigi","location":"Earth","url":null,"description":"Love politics, Grandchildren &amp; PSU #StillWithHer #NotMyPresident Blocked by Susan Sarandon, Glenn Greenwald, Joel Osteen and Joe Scarborough!!\ud83d\ude0e #TheResistance","translator_type":"none","protected":false,"verified":false,"followers_count":5878,"friends_count":5973,"listed_count":143,"favourites_count":110285,"statuses_count":138191,"created_at":"Wed Aug 19 04:55:41 +0000 2009","utc_offset":-14400,"time_zone":"Eastern Time (US &amp; Canada)","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http://abs.twimg.com/images/themes/theme1/bg.png","profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme1/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_im…
has comment: http://stackoverflow.com/comment/80628994
has title: calling values from a json file like a dictionary
has comment: http://stackoverflow.com/comment/80628903
has comment: http://stackoverflow.com/comment/80628950
answer count: 1
has comment: http://stackoverflow.com/comment/80628918
linked to: http://stackoverflow.com/q/38307068
favorite count: 0
score: -1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46840587
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/a/46869880
answers question: http://stackoverflow.com/q/46867731
score: 0
type: Answer
has body: I recommend you read this post on repeating key events and first determine whether your operating system provides key repeat and whether you can/want to adjust that and/or how to turn it off to implement your own. That link includes code to implement your own key repeat behavior in turtle. I've reworked your code below and the keys repeat fine for me because my operating system (OSX) implements key repeat: from turtle import Turtle, Screen # Setup Screen wn = Screen() wn.setup(700, 700) wn.title('white') wn.bgcolor('black') # Create Player player = Turtle('triangle') player.speed('fastest') player.color('white') player.penup() def forward(): player.forward(20) def left(): player.left(90) def right(): player.right(90) wn.onkey(forward, 'Up') wn.onkey(left, 'Left') wn.onkey(right, 'Right') wn.listen() wn.mainloop() In OSX I can control the rate (and turn it off) in the Keyboard panel of Systems Preferences. Look into what your OS provides. Some programming notes: avoid importing the same module two different ways, this always leads to confusion. If you find you're getting interference between keyboard events at high repetition rates consider the following for all three event handlers: def forward(): wn.onkey(None, 'Up') # disable event in handler player.forward(20) wn.onkey(forward, 'Up') # reenable event

http://stackoverflow.com/q/46898464
accepted answer: http://stackoverflow.com/a/46898989
has body: I have the following table in Django-1.11: class Market(models.Model): slug = models.SlugField(...) active = models.DateTimeField(...) It would be great if the slug was a foreign key to avoid duplicate values but this is not the case, I am coping with a third party app. data = [ {'id': 1, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;)'}, {'id': 2, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;)'}, {'id': 3, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;)'}, {'id': 4, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;)'}, ] I am looking for a query which will return the latest entry with slug test-1 and the latest entry with slug test-2. Using annotate I just receive the results with their datetime: Market.objects.values('slug').annotate(Max('active')) Out[11]: &lt;QuerySet [ {'active__max': datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;), 'slug': 'test-1'}, {'active__max': datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;), 'slug': 'test-1'}, {'active__max': datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;), 'slug': 'test-2'}, {'active__max': datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=&lt;UTC&gt;), 'slug': 'test-2'} ]&gt; This result does not seem to follow the docs. What am I doing wrong? Is it the SlugField that does not permit "grouping"?
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/46898989
tagged with: django-queryset
answer count: 1
favorite count: 0
has title: Django Query: Group by field and get the latest entry per group
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/17887075

http://stackoverflow.com/comment/80835362
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46903875
has text: Thought that might be the problem, I assume `cur.next` and `cur` are meant to be `curr.next` and `curr` as well?

http://stackoverflow.com/comment/80448073
type: Comment
type: QuestionComment
has text: I think you've got a cut-and-paste error. `'2017-03-31,'df['Posting Date']` is a syntax error. (Presumably the comma should be _outside_ the quotes.) If this is actually correct numpy syntax, my apologies.
comment on: http://stackoverflow.com/q/46751078
score: 0

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/46841117
type: Tag

http://stackoverflow.com/q/46858499
has body: I'm trying to implement a simple voting score in a csv file using pandas. Basically, if the `dataframe['C'] == Active and dataframe['Count'] == 0, then dataframe['Combo'] == 0. If dataframe['C'] == Active and dataframe['Count'] == 1; then dataframe['Combo'] == 1. If dataframe['C'] == Active and dataframe['Count'] == 2; then dataframe['Combo'] == 2 and so on. This is my dataframe: A B C Count Combo Ptn1 Lig1 Inactive 0 Ptn1 Lig1 Inactive 1 Ptn1 Lig1 Active 2 2 Ptn2 Lig2 Active 0 0 Ptn2 Lig2 Inactive 1 Ptn3 Lig3 Active 0 0 Ptn3 Lig3 Inactive 1 Ptn3 Lig3 Inactive 2 Ptn3 Lig3 Inactive 3 Ptn3 Lig3 Active 4 3 This is my code so far for clarity: import pandas as pd df = pd.read_csv('affinity.csv') VOTE = 0 df['Combo'] = '' df.loc[(df['Classification] == 'Active') &amp; (df['Count'] == 0), 'Combo'] = VOTE df.loc[(df['Classification] == 'Active') &amp; (df['Count'] == 1), 'Combo'] = VOTE + 1 df.loc[(df['Classification] == 'Active') &amp; (df['Count'] == 2), 'Combo'] = VOTE + 2 df.loc[(df['Classification] == 'Active') &amp; (df['Count'] &gt; 3), 'Combo'] = VOTE + 3 My code was able to do this correctly. However, there are two 'Active' values for the pair Ptn3-Lig3; one at dataframe['Count'] = 0 and another at dataframe['Count'] = 4. Is there a way to ignore the second value (i.e. consider only the smallest dataframe['Count'] value) and add the corresponding number to dataframe['Combo']? I know pandas.DataFrame.drop_duplicates()might be a way to select only unique values, but it would be really good avoid deleting any rows.
score: 0
has title: Ignore duplicated values in pandas
tagged with: pandas
answer count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46858602
accepted answer: http://stackoverflow.com/a/46858602
type: Question

http://stackoverflow.com/q/46855519
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80658976
answer count: 1
has answer: http://stackoverflow.com/a/46855669
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80658538
has title: Python concatenate SET or LIST
tagged with: python
has comment: http://stackoverflow.com/comment/80658590
has comment: http://stackoverflow.com/comment/80658685
has body: I try to test two to get set from list: In first from each list create set and then union to result set or create one list and the return the set of list. My result looks like no matter in which way to use, is it so? Or I have error logic in my research, or may be exist best way for such union? import time def set_from_set(*args): l = set() return set().union(*args) def set_from_list(*args): l = [] for larg in args: l += larg return set(l) l1 = [x for x in range(1000000)] l2 = [x for x in range(1000000)] l3 = [x for x in range(1000000)] dl1, dl2 = 0, 0 for x in range(100): start = time.time() set_from_list(l1, l2, l3) dl1 += time.time() - start for x in range(100): start = time.time() set_from_set(l1, l2, l3) dl2 += time.time() - start print(dl1, dl2) result: 19.815733194351196 16.40732741355896
type: AnsweredQuestion
tagged with: list
score: 0
accepted answer: http://stackoverflow.com/a/46855669
has comment: http://stackoverflow.com/comment/80658547
tagged with: set
has comment: http://stackoverflow.com/comment/80658736
upvote count: 1

http://stackoverflow.com/q/46886903
tagged with: python-3.x
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/472575
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/80721542
tagged with: linq
upvote count: 2
tagged with: python-2.7
has title: Python equivalent of LINQ Single() function?
favorite count: 0
has body: I'm looking for equivalent of .NET Linq IEnumerable.Single(predicate) function in Python. https://msdn.microsoft.com/en-us/library/bb535118(v=vs.110).aspx It is supposed to return exactly one element from enumerable/iterable that satisfy a condition and throw exception if there isn't exactly one element like that. I know it can be easily coded by hand but I'm looking for something built-in.
duplicate of: http://stackoverflow.com/q/472575
tagged with: python

http://stackoverflow.com/a/46850719
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46850584
score: 1
has body: So here is what is happening with your solution print df.ix[df[key]&lt;val,key] = val #syntax error Here you are trying to print and also assign it to variable val but that's not supportable. The code below serves as e example for you. df.loc[df[key]&lt;val,key] = val print(val)

http://stackoverflow.com/comment/80556985
type: QuestionComment
comment on: http://stackoverflow.com/q/46786643
has text: Here is another use-case where it makes sense to do it this way: https://stackoverflow.com/questions/1589058/nested-function-in-python
score: 0
type: Comment

http://stackoverflow.com/comment/80538827
type: QuestionComment
has text: Sounds like a circular import problem.
score: 0
comment on: http://stackoverflow.com/q/46796023
type: Comment

http://stackoverflow.com/a/46810052
answers question: http://stackoverflow.com/q/46800479
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46800479
has body: ok guys thanks Antii for clue as You said problem was that test.c should be included in sources tuple so i modified setup.py and everything works fine now it look`s like this: from setuptools import setup,Extension spam_module = Extension('spam', sources = ['spammodule.c','src/test.c'], include_dirs=['src/']) setup ( name = 'Spam', version = '1.0', description = 'Sample module.', ext_modules = [ spam_module ])

http://stackoverflow.com/a/46904371
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80807412
answers question: http://stackoverflow.com/q/46904273
score: 8
has comment: http://stackoverflow.com/comment/80781136
type: Answer
has comment: http://stackoverflow.com/comment/80807602
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/80755433
has body: Just remove the .first() method and add delete to the query itself session.query(Anwendung).filter_by(name="Max").delete() http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.delete Look at this for reference
accepted answer of: http://stackoverflow.com/q/46904273

http://stackoverflow.com/a/46903505
has body: The function takes a single character and a set of rules as a list. You should understand that [...] creates a single element list, I believe (based off your last question) that it's not what you want. You're looking for str.split: In [1429]: rules = input("Input your rules: ") ...: Input your rules: a:b b:c c:d In [1430]: rules.split() Out[1430]: ['a:b', 'b:c', 'c:d'] Pass this list to applyRules. Also, just a side note (since you're a beginner), str.split is not an inplace operation. In this example, I haven't assigned the result back to anything, but you should, if you want to store the list in another variable.
answers question: http://stackoverflow.com/q/46903438
has comment: http://stackoverflow.com/comment/80798469
score: 4
accepted answer of: http://stackoverflow.com/q/46903438
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80798636
has comment: http://stackoverflow.com/comment/80800802
type: Answer
has comment: http://stackoverflow.com/comment/80800763
upvote count: 4
has comment: http://stackoverflow.com/comment/80798228
downvote count: 0
has comment: http://stackoverflow.com/comment/80798271
has comment: http://stackoverflow.com/comment/80772323

http://stackoverflow.com/a/49772856
has comment: http://stackoverflow.com/comment/111317570
has comment: http://stackoverflow.com/comment/97206907
has comment: http://stackoverflow.com/comment/132218091
type: Answer
upvote count: 6
downvote count: 1
accepted answer of: http://stackoverflow.com/q/46864915
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108330686
has body: Use ffpyplayer to handle the audio part. import cv2 import numpy as np #ffpyplayer for playing audio from ffpyplayer.player import MediaPlayer video_path="../L1/images/Godwin.mp4" def PlayVideo(video_path): video=cv2.VideoCapture(video_path) player = MediaPlayer(video_path) while True: grabbed, frame=video.read() audio_frame, val = player.get_frame() if not grabbed: print("End of video") break if cv2.waitKey(28) &amp; 0xFF == ord("q"): break cv2.imshow("Video", frame) if val != 'eof' and audio_frame is not None: #audio img, t = audio_frame video.release() cv2.destroyAllWindows() PlayVideo(video_path) The sample code will work but you need to play around the cv2.waitKey(28) depending on the speed of your video.
has comment: http://stackoverflow.com/comment/97146164
answers question: http://stackoverflow.com/q/46864915

http://stackoverflow.com/a/46754359
type: Answer
upvote count: 3
has body: Short answer, Tuple From "What's the difference between lists and tuples?" thread, Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order. Using this distinction makes code more explicit and understandable. As tuples consists of heterogeneous entities, instead of an order of homogeius entities, tuple is a great way to deal with coordinate systems. Also the coordinate operations like addition &amp; substraction is fairly simple with tuples. Example: import operator a = (1,2,3) b = (5,6,7) c = tuple(map(operator.add, a, b)) Also tuple is immutable. This seems inconvenient at first, but using immutable data like this in functional programming techniques has substantial advantages.
downvote count: 0
has comment: http://stackoverflow.com/comment/80488911
answers question: http://stackoverflow.com/q/46754144
score: 3

http://stackoverflow.com/comment/80720953
comment on: http://stackoverflow.com/q/46826267
type: Comment
type: QuestionComment
score: 0
has text: @epeleg if you want the object to be aware of its type, use an instance variable

http://stackoverflow.com/comment/80748698
type: QuestionComment
has text: in the future, please post code directly.. not pictures
score: 0
comment on: http://stackoverflow.com/q/46900824
type: Comment

http://stackoverflow.com/q/46851776
tagged with: nodes
has answer: http://stackoverflow.com/a/46852003
type: Question
accepted answer: http://stackoverflow.com/a/46852003
score: 0
tagged with: iterator
answer count: 1
has title: python doubly linked list - insertAfter node
tagged with: doubly-linked-list
tagged with: python
type: AnsweredQuestion
has body: Im creating a python class to implement a doubly linked list. I have a seperate class for the DLL node itself and a class for the list. This is my class for the DLL nodes: class DLLNode: def __init__(self,element,nextnode=None,prevnode=None,): self._element = element self._next = nextnode self._prev = prevnode I have a method called insertAfter(self,x,y) which inserts node y after the first occurence x. Which is this : if self.size != 0: n = DLLNode(y) if self.head._element == x: n._next = self.head._next self.head._next._prev = n n._prev = self.head self.head._next = n self.size += 1 elif self.tail._element == x: self.tail._next = n n._prev = self.tail n._next = None self.tail = n self.size += 1 else: iterator = self.head._next while iterator._next is not None: if iterator._element == x: n._next = iterator._next iterator._next._prev = n n._prev = iterator iterator._next = n self.size += 1 else: iterator = iterator._next when i run this function however, the function loops forever, when i kill the function myself, the error refers back to the 4th last line iterator._next = n it doesnt say anything else which is why im confused. Would greatly appreciate any help :)

http://stackoverflow.com/q/46838068
tagged with: psycopg2
score: 2
downvote count: 0
tagged with: sqlalchemy
type: Question
upvote count: 2
has body: How does sqlalchemy handle buffering/chunking? with open('out', 'w') as f: query = table.select() for row in engine.execute(query): output_row = make_row_string(row) print(output_row, file=f) Reading from the ResultProxy docs I infer (correctly?) that it's processing the rows all at once when they're all available. How can I query and process in chunks to make this job faster for a many-row query? The two ideas I have for dealing with a many-row query are .fetchmany(chunksize) while True, or itertools chunks. What is the recommended way to get many rows from a remote database?
has answer: http://stackoverflow.com/a/46841134
answer count: 1
favorite count: 0
tagged with: postgresql
has title: How to query sqlalchemy in chunks?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80471554
has text: Maybe you need `from copy import deepcopy`?
comment on: http://stackoverflow.com/q/46763121
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46864449
tagged with: encryption
has comment: http://stackoverflow.com/comment/80678389
has comment: http://stackoverflow.com/comment/80677384
tagged with: python
has comment: http://stackoverflow.com/comment/80677160
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/46865647
has comment: http://stackoverflow.com/comment/80677213
has comment: http://stackoverflow.com/comment/80677308
upvote count: 2
has comment: http://stackoverflow.com/comment/80677412
has comment: http://stackoverflow.com/comment/80676425
has comment: http://stackoverflow.com/comment/80678434
type: Question
has comment: http://stackoverflow.com/comment/80677381
has body: The Bacon cipher is a very nice cipher which maps the letters A-Z to numbers from 0-25 in 5-bit representation (e.g. A = 00000, Z=11001 etc.). A good description is here. As part of this, I want to decrypt the following text which was encrypted with Bacon Cipher. Basically, if it is an upper letter I consider a bit 1 for it and 0 if it is a lower one. Then by splitting in 5-bit groups we get the decryption of the ciphertext. For example the first 5 letters CrYPt transforms into 10110 which transforms into W. I inserted the text in a file.txt: CrYPtogRapHY iS a ScIEnce Of "seCrET wriTinG". FOr aT Least Two THoUsAnd yeaRS ThErE haVE bEeN peOPlE WHo WAnTeD to SEnd MESsaGes WHiCh coUlD oNLY bEeN reAd bY tHe pEOplE FOR WhOm thEy were INtEndeD. a lOT oF different MEtHODs For CONceaLiNG MESSAgeS weRE InvENted startINg WiTh ancient cIPhERS lIke "skYtAle" AnD "AtbasH" AND EndINg WITh mOdERn SYMmetRIc And puBLiC key eNCryptiON algOriThMS SuCH AS aES AnD rSa. THe deVelOPMeNt oF CRyPTOgrAPhY coNtiNUeS aND neveR SToPs! DecRYpT the MessAGe ThAt iS hIDDeN iN tHE TeXt of This Task! thE alPhaBeT For thE mESsagE cOnsIsTS of alL TWENty SIx ENGliSh letTErs fROM "a" tO "Z" and sIx puNCtUAtiON MARkS " ", ".", ",", "!", "?", "'" Here is my python code: import re tr = {26: ' ', 27: '.', 28: ',', 29: '!', 30: '?', 31: '\''} def transform(binary_ch): v = int(binary_ch, 2) if v &lt; 26: return chr(65 + v) return tr[v] # read the ciphertext from file crypto_text = open("file.txt").read() # remove the unnecessary characters (e.g. punctuation marks) crypto_text = ''.join(ch for ch in crypto_text if ch.isalpha()) # convert to 1 the upper letter and to 0 the lower letter crypto_text = ''.join('1' if ch.isupper() else '0' for ch in crypto_text) # split in blocks of 5 characters crypto_text = re.findall('.'*5, crypto_text) plain_text = ''.join(transform(ch) for ch in crypto_text) print crypto_text print plain_text But the plain is not the expected one. I get this: WE[WELCOME[QOU[TO[THE[FOUSTH[EDITIA…
has comment: http://stackoverflow.com/comment/80678382
has comment: http://stackoverflow.com/comment/80677204
has comment: http://stackoverflow.com/comment/80677484
has comment: http://stackoverflow.com/comment/80677328
has comment: http://stackoverflow.com/comment/80677252
has comment: http://stackoverflow.com/comment/80676466
has comment: http://stackoverflow.com/comment/80677224
has title: Bacon Cipher Decryption
has answer: http://stackoverflow.com/a/46865647
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80677349
favorite count: 0
has comment: http://stackoverflow.com/comment/80677361

http://stackoverflow.com/a/46773137
has comment: http://stackoverflow.com/comment/80492994
score: 1
has comment: http://stackoverflow.com/comment/80493136
has comment: http://stackoverflow.com/comment/80492770
accepted answer of: http://stackoverflow.com/q/46771666
has body: Since it's an object you have to use a dot to access its properties : obj.oid Then you have a unicode string, encoding it using 'utf-8' charset you get bytes, which you then have to decode to get your string object : obj.oid.encode('utf-8').decode() Example (python 3) : &gt;&gt;&gt; s = u'hello' # unicode &gt;&gt;&gt; s.encode('utf-8') # to bytes b'hello' &gt;&gt;&gt; s.encode('utf-8').decode() # to string 'hello' Example (python 2) : &gt;&gt;&gt; s = u'hello' # unicode &gt;&gt;&gt; s.encode('utf-8') # to string 'hello'
answers question: http://stackoverflow.com/q/46771666
has comment: http://stackoverflow.com/comment/80493559
has comment: http://stackoverflow.com/comment/80492946
has comment: http://stackoverflow.com/comment/80493456
upvote count: 3
downvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/80641547
has text: @Hafnernuss yes I'm currently reading from my ssd.
score: 0
comment on: http://stackoverflow.com/q/46845656
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46877716
score: 0
has answer: http://stackoverflow.com/a/46892283
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I am trying to write a custom hive udf in python to calculate experience of an employee, but i'm getting runtime errors, please sort this out. This is the python script empexp.py import sys from datetime import datetime from dateutil.relativedelta import relativedelta cdate = datetime.now().date() for line in sys.stdin: line = line.strip() eno,ename,hiredate = line.split('\t') hdate = datetime.strptime(hiredate,'%Y-%m-%d').date() year = str(relativedelta(current_date,hdate).years) month = str(relativedelta(current_date,hdate).months) day = str(relativedelta(current_date,hdate).days) e = year+'-'+month+'-'+day list1 = [str(eno),str(ename),str(hiredate),str(cdate),str(e)] print '\t'.join(list1) and in the following I am giving the hive query, select transform(eno,ename,hiredate) using 'python empexp.py' as (eno,ename,hiredate,cdate,e) from emp; But I am getting runtime errors, here is the error log, Diagnostic Messages for this Task: Error: java.lang.RuntimeException: Hive Runtime Error while closing operators at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.close(ExecMapper.java:207) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: [Error 20003]: An error occurred when trying to close the Operator running your custom script. at org.apache.hadoop.hive.ql.exec.ScriptOperator.close(ScriptOperator.java:585) at org.apache.hadoop.hive.ql.exec.Operator.close(Operator.java:697) at org.apache.hadoop.hive.ql.exec.Operator.close(Operator.java:697) at org.apach…
tagged with: hive
has title: Runtime error in hive udf using python
type: Question

http://stackoverflow.com/comment/80622710
has text: Is this OK? `with open("usernames.txt", "a+")as fi: with open("userinfos.txt", "a+") as f: with open("quizzes.txt", "a+") as fil: listofinfos = ["surname", "yeargroup"] if True: name = input("Enter your name:") age = input("Enter your age:") username = name[:3]+age if str(username) in fi.read(): hasAccount = True print("found username") else: hasAccount = False print("notfound")
score: 0
comment on: http://stackoverflow.com/q/46837492
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46901004
has comment: http://stackoverflow.com/comment/80749066
has body: After checking the comments, your issue is that you are asking to check if the file at D:\ exists, but you are creating that file at your desktop. Those are two different places. Desktop is not located at the root of a hard drive like D:\. Desktop is usually located at something like D:\Users\CJPeine\Desktop (depends on your user) so you need to first find where is your desktop located. The easier way to find where your .txt is (the commonly known path of a file), is by right-clicking on the file and selecting properties option. Find the path or location information there. Then you just need to change the next line to find the file accurately. UsernameandPasswordfile = "D:\Users\CJPeine\Desktop\%s.txt" % username On backslashes: However, that would create a problem. Some characters like \n or \t (among others) create special behaviour, which is why we need to escape them. For example \n adds a new line so if you write: "this is a te\nst" The result is: this is a t est So in order to fix that we escape those characters by adding a double backslash instead of just one. Adding that pretty much means "don't try to find an special behaviour for my backslash". And in the end the working code is. UsernameandPasswordfile = "D:\\Users\\CJPeine\\Desktop\\%s.txt" % username
has comment: http://stackoverflow.com/comment/80749322
has comment: http://stackoverflow.com/comment/80749012
accepted answer of: http://stackoverflow.com/q/46900658
type: Answer
has comment: http://stackoverflow.com/comment/80749331
has comment: http://stackoverflow.com/comment/80749001
has comment: http://stackoverflow.com/comment/80749019
has comment: http://stackoverflow.com/comment/80749304
has comment: http://stackoverflow.com/comment/80748999
has comment: http://stackoverflow.com/comment/80749096
has comment: http://stackoverflow.com/comment/80749186
answers question: http://stackoverflow.com/q/46900658
has comment: http://stackoverflow.com/comment/80748960
has comment: http://stackoverflow.com/comment/80749353
has comment: http://stackoverflow.com/comment/80749169
score: 0
has comment: http://stackoverflow.com/comment/80749343
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80749291
has comment: http://stackoverflow.com/comment/80749162
has comment: http://stackoverflow.com/comment/80749038
has comment: http://stackoverflow.com/comment/80749301

http://stackoverflow.com/comment/80954573
type: AnswerComment
comment on: http://stackoverflow.com/a/46923485
type: Comment
has text: Thanks! It seems that I cannot configure Google's File Stream though... It says I need to use an administrator/Gsuite account...
score: 0

http://stackoverflow.com/a/46903929
score: 0
answers question: http://stackoverflow.com/q/46903330
has comment: http://stackoverflow.com/comment/80755485
type: Answer
has body: So I tried this and it kinda work and it is very fast, not sure what you guys think. result = df1.copy() result[result.notnull()] = 0 for name in df2.columns: result += (df1 == name).astype(int).multiply(df2[name], axis='index')

http://stackoverflow.com/comment/80475144
type: QuestionComment
type: Comment
has text: Thanks a lot @jezrael. Done! :)
comment on: http://stackoverflow.com/q/46755489
score: 0

http://stackoverflow.com/comment/80725610
type: Comment
comment on: http://stackoverflow.com/a/46888308
type: AnswerComment
has text: @Ajax1234 Thank you. Much more understandable to me now
score: 0

http://stackoverflow.com/comment/91535432
score: 0
type: Comment
has text: Thanks @coldspeed, i will keep this thing in mind :)
comment on: http://stackoverflow.com/a/52278238
type: AnswerComment

http://stackoverflow.com/comment/80704024
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46878460
has text: Look at the line above where the error is. Hint: count the number of brackets...
score: 0

http://stackoverflow.com/comment/80457936
type: Comment
type: QuestionComment
has text: @ClaytonGeist yes I was just suggesting the more convential import syntax. I'm sure there are reasons but it's not clear why `nm` can't be a parameter to testfunc.
comment on: http://stackoverflow.com/q/46756034
score: 0

http://stackoverflow.com/q/46869528
type: AnsweredQuestion
downvote count: 1
type: Question
score: 9
has body: How do you install Python 3.6.x in a virtualenv using pip in Windows 10? pip install python, pip install python3, pip install python3.6 don't work.
has comment: http://stackoverflow.com/comment/80686320
answer count: 1
has comment: http://stackoverflow.com/comment/115387990
tagged with: virtualenv
tagged with: windows-10
favorite count: 0
has title: Install Python 3.6.3 in Virtualenv using pip in WIndows 10?
upvote count: 10
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/46870341
accepted answer: http://stackoverflow.com/a/46870341

http://stackoverflow.com/a/46821366
upvote count: 1
answers question: http://stackoverflow.com/q/46821320
has comment: http://stackoverflow.com/comment/80590181
downvote count: 0
has comment: http://stackoverflow.com/comment/80590218
type: Answer
has body: Since you're numbering along rows first, the formula you need is row_number * column_count + column_number. If you were numbering down columns first, or right-to-left, or any other variation, you would have to adjust that formula accordingly. Keep in mind, also, that this works for zero-based indexing only.
score: 1

http://stackoverflow.com/q/46901076
has comment: http://stackoverflow.com/comment/80749107
score: 0
has answer: http://stackoverflow.com/a/46901594
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/80749330
type: UnansweredQuestion
tagged with: pointer-aliasing
type: Question
has body: Say I have a list called list, which is comprised of boolean values. Also say that I have some (valid) index i which is the index of list where I want to switch the value. Currently, I have: list[i] = not list[i]. But my question is, doesn't this iterate through list twice? If so is there are way to setup a temp value through aliasing to only iterate through the list once? I tried the following: temp = list[i] temp = not temp But this has not worked for me, it has only switched the value of temp, and not the value of list[i].
has title: using aliasing to iterate through list once (python)
answer count: 1

http://stackoverflow.com/comment/80594829
comment on: http://stackoverflow.com/a/46823720
type: AnswerComment
has text: Never mind, I understand what you mean. I wonder if adding function calling overhead is even worse than kicking the GC.
score: 0
type: Comment

http://stackoverflow.com/q/46887098
score: 1
accepted answer: http://stackoverflow.com/a/46887589
favorite count: 0
type: Question
has title: Convert CSV file with values spareted in comma to multi columns CSV file
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80721547
tagged with: python
upvote count: 2
answer count: 2
has body: I want to create a small program to convert a CSV file with one column containing values separated by comma, to CSV file containing multiple columns with one value: input file: output file: Therefor I write this code: my_string1 = 'A,B,C,D,E' my_string2 = 'A,B,C,D,E' my_string3 = 'A,B,C,D,E' my_list1 = my_string1.split(",") my_list2 = my_string2.split(",") my_list3 = my_string3.split(",") path = 'C:\Dokumente\\n_1.csv' rows = zip(my_list1,my_list2,my_list3) with open(path, "wb") as csv_file: writer = csv.writer(csv_file, delimiter=',') for row in rows: for column in row: writer.writerow('%s;' % column) But the problem is that it writes all the values in one Column. I want to write column by column and then I want to move to second row to write again? I work with Eclipse Oxy with PyDev and Python 2.7
has comment: http://stackoverflow.com/comment/80722170
downvote count: 1
has answer: http://stackoverflow.com/a/46887589
has comment: http://stackoverflow.com/comment/80721799
tagged with: python-2.7
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46887565
has comment: http://stackoverflow.com/comment/80722586
has answer: http://stackoverflow.com/a/46887565

http://stackoverflow.com/q/46834364
has comment: http://stackoverflow.com/comment/80618094
tagged with: python
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/2823211
type: Question
has answer: http://stackoverflow.com/a/46834527
has comment: http://stackoverflow.com/comment/80616899
tagged with: binary-tree
tagged with: typeerror
score: 3
downvote count: 0
answer count: 1
tagged with: parsing
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46834527
has comment: http://stackoverflow.com/comment/80617841
has body: I have a problem with the Parse Tree code. When I try to show it with post-order, it gives me an error message that should be str the parameter and not int. from classStack import Stack from classTree import BinaryTree def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError("No se contempla el carácter evaluado") return eTree ParseTree = buildParseTree("( 8 * 5 )") ParseTree.printPostordenTree(0) Error: Traceback (most recent call last): File "C:\Users\Franco Calvacho\Downloads\Árboles\parseTree.py", line 38, in &lt;module&gt; ParseTree.printPostordenTree(0) File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 62, in printPostordenTree self.getLeftChild().printPostordenTree(n+1) File "C:\Users\Franco Calvacho\Downloads\Árboles\classTree.py", line 67, in printPostordenTree print("Level: "+ str(n) + " " + self.getRootVal()) TypeError: must be str, not int [Finished in 0.2s] Here's the BinaryTree code. I make it clear that the BinaryTree code alone is OK and it doesn't give me that error message. Under that code I leave you in python comments for you to see. class BinaryTree(object): def __init__(self, data): self.key = data self.leftChild = None self.rightChild = None def insertLeft(self, newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode)…
has title: [python-3]TypeError: must be str, not int

http://stackoverflow.com/comment/80771288
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46905044
has text: ah ok my bad. Didn't understand read properly.
type: QuestionComment

http://stackoverflow.com/a/46799103
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80545581
score: 2
accepted answer of: http://stackoverflow.com/q/46798995
upvote count: 2
answers question: http://stackoverflow.com/q/46798995
has body: As you can see, step by step def doThing(input_number,generated_number): return [x for x in generated_number if x &gt; input_number] print(doThing(10,[100,10,20,40])) def doSameThing(input_number,generated_number): res = [] for x in generated_number: if x &gt; 10: res.append(x) return res print(doSameThing(10,[100,10,20,40])) You are making a filter by >10, list comprehension is just syntactic sugar of it
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80545493
has comment: http://stackoverflow.com/comment/80545846
has comment: http://stackoverflow.com/comment/80607787

http://stackoverflow.com/q/46871522
has answer: http://stackoverflow.com/a/46871739
has comment: http://stackoverflow.com/comment/80690294
has comment: http://stackoverflow.com/comment/80690308
has body: I've written a function in python to see If i know what I'm doing but unfortunately I'm not. I thought my defined arg variable will hold a number and multiply each of the numbers which *args variable holds and print it all at a time. But, it is giving me the first result only. This is what I've written: def res_info(arg,*args): for var in args: return var*arg print(res_info(2,70,60,50)) Having: 140 Expected: 140 120 100 I don't understand why I'm not getting all the results. Thanks for taking a look into it.
answer count: 2
tagged with: function
accepted answer: http://stackoverflow.com/a/46871546
downvote count: 0
favorite count: 0
tagged with: python
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/18567773
upvote count: 3
has title: Having difficulty understanding how function works
linked to: http://stackoverflow.com/q/18567773
has answer: http://stackoverflow.com/a/46871546
type: Question
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/46871739

http://stackoverflow.com/q/46759492
has answer: http://stackoverflow.com/a/73389245
score: 6
has answer: http://stackoverflow.com/a/46759653
tagged with: python
has answer: http://stackoverflow.com/a/46759549
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50851189
has answer: http://stackoverflow.com/a/50851189
upvote count: 7
downvote count: 1
type: Question
tagged with: function
has answer: http://stackoverflow.com/a/50851801
accepted answer: http://stackoverflow.com/a/46759549
has body: I need to write a function that will read syllables in a word (for example, HAIRY is 2 syllables). I have my code shown on the bottom and I'm confident it works in most cases, because it works with every other test I've done, but not with "HAIRY" where it only reads as 1 syllable. def syllable_count(word): count = 0 vowels = "aeiouy" if word[0] in vowels: count += 1 for index in range(1, len(word)): if word[index] in vowels and word[index - 1] not in vowels: count += 1 if word.endswith("e"): count -= 1 if count == 0: count += 1 return count TEST print(syllable_count("HAIRY")) Expected: 2 Received: 1
has title: Syllable Count In Python
favorite count: 0
answer count: 5

http://stackoverflow.com/q/46867083
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/46867275
type: Question
has answer: http://stackoverflow.com/a/46867450
has answer: http://stackoverflow.com/a/46867111
score: -1
has body: What is the best way to create a dict from two other dicts (very big one and small one)? We have: big_dict = { 'key1':325, 'key2':326, 'key3':327, ... } small_dict = { 325:0.698, 326:0.684, 327:0.668 } Needs to get a dict for data in small_dict, but we should use keys from big_dict: comb_dict = { 'key1':0.698, 'key2':0.684, 'key3':0.668 }
accepted answer: http://stackoverflow.com/a/46867105
has title: create dict combining two other dicts
has answer: http://stackoverflow.com/a/46867105
favorite count: 0
possible better answer: http://stackoverflow.com/a/46867111
tagged with: python
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80681836
linked to: http://stackoverflow.com/q/38987
has comment: http://stackoverflow.com/comment/80691102

http://stackoverflow.com/comment/80682112
has text: @snowboard_maniac Give the full path: 'C:/Users/x/Desktop/train.csv'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46867064
type: AnswerComment

http://stackoverflow.com/comment/80705160
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46879064
has text: Yes, you iterate over the `val[key]`, and furthermore you do an additional membercheck with `test_date in value`.
type: Comment

class
tags question: http://stackoverflow.com/q/46821912
tags question: http://stackoverflow.com/q/46871860
tags question: http://stackoverflow.com/q/46849966
tags question: http://stackoverflow.com/q/46885618
tags question: http://stackoverflow.com/q/46750687
tags question: http://stackoverflow.com/q/46764475
tags question: http://stackoverflow.com/q/46871202
tags question: http://stackoverflow.com/q/46841035
tags question: http://stackoverflow.com/q/46897337
tags question: http://stackoverflow.com/q/46850792
tags question: http://stackoverflow.com/q/46858710
tags question: http://stackoverflow.com/q/46801195
tags question: http://stackoverflow.com/q/46800902
tags question: http://stackoverflow.com/q/46749486
tags question: http://stackoverflow.com/q/46808362
tags question: http://stackoverflow.com/q/46827674
tags question: http://stackoverflow.com/q/46864498
tags question: http://stackoverflow.com/q/46801284
tags question: http://stackoverflow.com/q/46885496
tags question: http://stackoverflow.com/q/46749969
tags question: http://stackoverflow.com/q/46761851
type: Tag
tags question: http://stackoverflow.com/q/46867715
tags question: http://stackoverflow.com/q/46831228
tags question: http://stackoverflow.com/q/46872930
tags question: http://stackoverflow.com/q/46844125
tags question: http://stackoverflow.com/q/46761594
tags question: http://stackoverflow.com/q/46805200
tags question: http://stackoverflow.com/q/46838422
tag name: class
tags question: http://stackoverflow.com/q/46838747
tags question: http://stackoverflow.com/q/46827554
tags question: http://stackoverflow.com/q/46822623
tags question: http://stackoverflow.com/q/46868790
tags question: http://stackoverflow.com/q/46818622
tags question: http://stackoverflow.com/q/46857728
tags question: http://stackoverflow.com/q/46756467
tags question: http://stackoverflow.com/q/46774295
tags question: http://stackoverflow.com/q/46817126
tags question: http://stackoverflow.com/q/46753320

http://stackoverflow.com/a/46832448
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80613086
type: Answer
answers question: http://stackoverflow.com/q/46832256
has body: I optimized the imports and wrote the password to a file: from string import digits from string import ascii_letters as letters import random punctuation =("!\"\&lt;&gt;@#£$%^&amp;*") PasswordCode = letters+punctuation+digits PassLenInput = int(input("How long should the password be?")) password = '' for i in range(PassLenInput): password += random.choice(PasswordCode) with open('password_file.txt', 'w') as f: f.write(password)
accepted answer of: http://stackoverflow.com/q/46832256
has comment: http://stackoverflow.com/comment/80613273
score: 0

http://stackoverflow.com/a/46861402
has body: Decimal can has more precision than regular python floats but it is still do rounding when it is dealing with fractions like 1/3. However there is Fraction class which is exaclty what you need. It is storing numbers as nominator and denominator and therefore lacking of precision and rounding issues. Let's say we have this code: t = 949253 a = [352305, 506833, 35384, 32278, 22453] b = [x/t for x in a] b[0] = 0 b[0] = -sum(b) print(sum(b)) # prints -2.0816681711721685e-17 Modifying it to use Fraction would be as simple as that: from fractions import Fraction t = 949253 a = [352305, 506833, 35384, 32278, 22453] b = [Fraction(x, t) for x in a] b[0] = 0 b[0] = -sum(b) print(sum(b)) # prints 0
type: Answer
has comment: http://stackoverflow.com/comment/80677960
accepted answer of: http://stackoverflow.com/q/46860457
answers question: http://stackoverflow.com/q/46860457
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80678032

http://stackoverflow.com/comment/108627399
score: 2
comment on: http://stackoverflow.com/a/55834112
type: AnswerComment
type: Comment
has text: add `from selenium import webdriver` to invoke `webdriver.Firefox()`

http://stackoverflow.com/comment/80733576
comment on: http://stackoverflow.com/q/46850454
score: 0
has text: Thanks for the insight! I actually find out I had used chained indexing some lines earlier. By killing this chained indexing problem, now my code works well.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46856698
has body: I have a workflow written in Snakemake for analyzing biological sequencing data. The workflow expects all the data files to be organized so that each raw read file begins with the type of assay (RNASeq, DNaseSeq, etc.) and this filename convention is maintained throughout all the files the workflow produces. I have a rule to align the reads for data from every assay except RNASeq, and a different rule that should only be applied to RNASeq data. I'm been having trouble getting these rules set up so that snakemake knows which to use for which files. In the RNASeq rule, I have this: wildcard_constraints: library='RNASeq_.+' and this works to make sure the RNASeq libraries use that rule. I'm still getting an error about ambiguous rules for other assays, though, so I think I need to constrain the wildcards in the other rules. I've tried this: wildcard_constraints: library='(!?RNASeq)_.+' to say match anything that doesn't have RNASeq, but while this works if I try it in the python interpreter, snakemake seems to not be able to match anything to this regex. I've tried it other ways, such as '[^R][^N][^A]' but can't get anything to work. Since these regexes work when I try them manually against strings, I think there's either a bug with how snakemake applies regular expressions, or I don't understand something about how they are used by snakemake. I was assuming it was simply "If this regex matches the wildcard string, use this rule. If it doesn't, don't use this rule."
tagged with: snakemake
has answer: http://stackoverflow.com/a/46856757
has answer: http://stackoverflow.com/a/48822608
type: Question
has comment: http://stackoverflow.com/comment/80660954
has comment: http://stackoverflow.com/comment/84645896
answer count: 2
has title: Can't get this regex to work for wildcard_constraints in snakemake
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80661233
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: regex
score: 2

http://stackoverflow.com/comment/80451157
has text: Have you more than one version of python installed? The configuration is applied to the project you using in tests? I use the both versions and this ever works, just try restart pycharm after setting up. On this page have a more detailed information https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html
comment on: http://stackoverflow.com/a/46752610
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46853819
favorite count: 0
has title: Creating alias for numpy functions
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46853855
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
tagged with: numpy
answer count: 1
has body: a=np.square creates an alias for pow(x,2) Similarly, I want to create an alias for pow(x,3) function a = np.power(x2=3) doesn't seem to work Any workaround?
downvote count: 0
tagged with: python

http://stackoverflow.com/q/46874343
has body: There are two text file tags and MobyDick , i have to check how many times a word extracted from the tag file is present in the mobydick. I have just extracted the words from the text file and saved it in a list, can anyone help with the function to check the frequency of the extracted words of tag file present in mobyDick below is the code i have written: with open('tags.txt','r') as f: words = f.read().split() #print(words) with open('MobyDick.txt',encoding='utf8') as g: text = g.read().split()
linked to: http://stackoverflow.com/q/18231542
score: 0
duplicate of: http://stackoverflow.com/q/18231542
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80696144
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/80695881
has comment: http://stackoverflow.com/comment/80695626
type: Question
has title: how many times a word from a list is present in another list

http://stackoverflow.com/comment/80996212
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46856265
has text: You can try playing the game of manually placing your operations on CPU or GPU (using `with tf.device('/cpu:0')`) if you can identify the specific operations that need a lot of memory, but as @yaroslav-bulatov mentioned, the overhead of moving data between GPU and CPU might eat up the benefit of using GPU.
type: QuestionComment

http://stackoverflow.com/comment/80585005
score: 1
type: Comment
comment on: http://stackoverflow.com/q/46812671
type: QuestionComment
has text: I know this is not an "answer". In general, when solving an ODE problem the "costly" part is to obtain an accurate solution. Once that is obtained, it is relatively "cheap" in terms of CPU time to recompute "P" and "Q". Consider whether you need to store them while solving the ODE or not based on performance.

http://stackoverflow.com/q/46851192
has title: Why is this regex code not working
tagged with: django
has answer: http://stackoverflow.com/a/46851349
type: AnsweredQuestion
tagged with: django-views
score: 1
has comment: http://stackoverflow.com/comment/80649953
tagged with: django-urls
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/80650104
has answer: http://stackoverflow.com/a/46851297
accepted answer: http://stackoverflow.com/a/46851297
downvote count: 1
possible better answer: http://stackoverflow.com/a/46851349
favorite count: 0
tagged with: python
tagged with: regex
has body: Working on a Django app Here's my urls.py urlpattterns = [url(r'^(?P&lt;leagueId&gt;[0-9]+)/(?P&lt;year&gt;[0-9]+)/(?P&lt;team&gt;[\S]+)/$', views.team_detail, name="team_detail"),] An example url would be along the lines of: http://localhost:8000/123456/2017/Johnny%20Rocket/ I tried playing around with Pythex, but I couldn't get the urls to match Note: The variables passed are /{number}/{year}/{name} The name can consist of alphanumeric characters and whitespaces.

http://stackoverflow.com/comment/80744607
score: 0
has text: Would you have a book or specific ressource to learn more about pandas ?
type: Comment
comment on: http://stackoverflow.com/a/46895771
type: AnswerComment

http://stackoverflow.com/comment/80541586
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46797412
has text: `output = pd.DataFrame(columns=df.columns)` is defined before the `for` loop. That's what you write to CSV; the `for` loop does basically nothing. Did you mean `df.to_csv("2008_data_test.csv_tostring2.csv", index=False)` instead?

http://stackoverflow.com/comment/80598140
comment on: http://stackoverflow.com/q/46825189
has text: @anupsabraham works perfectly! thank you :)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46837459
score: 4
upvote count: 4
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80719355
favorite count: 0
tagged with: latex
has comment: http://stackoverflow.com/comment/80625742
accepted answer: http://stackoverflow.com/a/61232784
tagged with: python
type: AnsweredQuestion
has title: pandas: create a caption with to_latex?
has body: I am exporting a table from a pandas script into a .tex and would like to add a caption. with open('Table1.tex','w') as tf: tf.write(df.to_latex(longtable=True)) (I invoke the longtable argument to span the long table over multiple pages.) The Table1.tex file gets imported into a bigger LaTeX document via the \import command. I would like to add a caption to the table, ideally on its top. Do you think there would be any way for doing that? I cannot manually edit the Table1.tex, it gets updated regularly using a Python script.
type: Question
has answer: http://stackoverflow.com/a/61232784

http://stackoverflow.com/comment/80686353
type: AnswerComment
comment on: http://stackoverflow.com/a/46869566
has text: @NewPieGuy did you add shopify_app to your apps inside settings?
type: Comment
score: 0

http://stackoverflow.com/q/46851963
answer count: 0
favorite count: 0
type: Question
tagged with: multithreading
tagged with: python
has title: Able to Plot real time serial data using Matplotlib but want to make the plotting to be done at SPECIFIC FREQUENCY. (eg. min 10 Hz or max 1000 Hz)
has body: I'm able to plot the serial data in real time. But the problem is, its taking longer.** (A) I am able to populate the QUEUE from incoming serial data at 10 Hz (i.e 40 data points in 4 secs) in a PRODUCER THREAD. (B) But, at the same time I am using the populated Queue in separate CONSUMER THREAD for live plotting using matplotlib and its taking totoal 8 secs to finish the plotting of 40 data points in real time. So, For 40 data points, its taking around 8 secs to plot in real time. But I want it at 10 Hz, that means 40 data points to be plotted in 4 secs. I have provided my code snippet here. Any help would be appreciated. Thanks. fig = plt.figure() plt.gcf().text(0.85, 0.91, samplingRate, fontsize=14, color='r') fig.suptitle('Plotting at 10 Hertz.', fontsize=20, color='r') axes = fig.add_subplot(221) axes.set_title('Plotting Attribute X', color='b') axes.set_xlabel("Number of Samples") axes.set_ylabel("Attribute X") axes.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) xdata = [] ydata = [] axes.set_xlim(0, 130) axes.set_ylim(-2, 2) line, = axes.plot( xdata, ydata, 'r-') counterFlag =0 while True : xdata.append(counterFlag) ydata.append(q1.get()) line.set_xdata( xdata) line.set_ydata( ydata) axes.relim() axes.autoscale() plt.pause(1e-50) counterFlag +=1 NOTE : Imagine q1 (line 17) declared above is the Queue that is getting serial data from the Producer thread and later getting consumed above in consumer THREAD for live plotting in matplotlib .
score: 0
tagged with: matplotlib
upvote count: 1
downvote count: 1
tagged with: queue
has comment: http://stackoverflow.com/comment/80651897
tagged with: pyserial
has comment: http://stackoverflow.com/comment/80651729
type: UnansweredQuestion

http://stackoverflow.com/comment/80669440
type: Comment
comment on: http://stackoverflow.com/q/46860749
has text: But the question ask me to use linked list
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80705628
comment on: http://stackoverflow.com/q/46879025
type: Comment
type: QuestionComment
has text: That whole `container.attrs["State"]` looks bogus to me - it's just a bunch of zeros.
score: 0

http://stackoverflow.com/comment/80726081
type: Comment
type: QuestionComment
has text: If you want to implement a stepwise function, you can do `f(x) if x > 0 else g(x)`. This might be a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you describe exactly what you want to do? Showing us the relevant code of what you've done so far might help.
comment on: http://stackoverflow.com/q/46888976
score: 1

http://stackoverflow.com/comment/80641393
comment on: http://stackoverflow.com/q/46846860
score: 0
type: Comment
type: QuestionComment
has text: There is not enough information to reproduce the problem. Make sure that in ipython you import from the expected location.

http://stackoverflow.com/comment/80598688
comment on: http://stackoverflow.com/a/46791461
score: 0
type: AnswerComment
type: Comment
has text: You are right. It seems validation data is different from the training and testing one.

http://stackoverflow.com/q/46840900
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46841203
accepted answer: http://stackoverflow.com/a/46841203
downvote count: 0
score: 1
tagged with: memory
type: Question
has body: I am trying to write the Python 3 code for a program that simulates the memory matching game: Write a program that plays the memory matching game. When it starts, the program prompts the user for the number of rows and columns for the game board that contains the cards. The total number of cards must be even. Assume that the board dimensions are at most 8 by 9 or 9 by 8. Your cards must be numbered from 1 through (number of rows * number of columns) / / 2. Your program allows the player to specify the cards that she would like to select through a coordinate system. I have written everything, but I keep getting one small error that I cannot for the life of me figure out. When I try to run the program using the following sample inputs, I get the error "List index out of range": &gt;&gt;&gt; main() Enter number of rows 3 Enter number of columns 3 &gt; ***The value of rows X columns must be even. Try again.*** Enter number of rows 2 Enter number of columns 3 &gt; * * * &gt; * * * Enter coordinates for first card 3 1 [THE ERROR IS GENERATED HERE] &lt;&lt;&lt; I understand that the 3 is outside of the array in this case, but the code I wrote is supposed to return an error message in the form of a string. Instead, the program crashes. If somebody could guide me in the right direction, I would appreciate it. Here is the full code I have written: import random class Card(object): def __init__(self,value): self._face = 0 self._value = value def __str__(self): if self._face == True: output = str(self._value) else: output = "*" return output def __eq__(self,other): if type(self)!=type(other): output = False elif self._value == other._value: output = True else: output = False return output class Deck(object): def __init__(self, pairs): self._pairs = pairs self._cards = [] for cards in range(self._pairs): self._cards.append(Card(cards)) self._cards.append(Card(cards)) def shuffle(self): random.shuffle(self._cards) def deal(self,index): return self._cards[index] def cardsleft(self…
has title: "List index out of range" error in Python Memory Match game
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80629687
has comment: http://stackoverflow.com/comment/80629702

http://stackoverflow.com/q/46873757
tagged with: macos
answer count: 2
has answer: http://stackoverflow.com/a/48020158
tagged with: python
tagged with: opencv
has title: Opencv contrib face library
score: 0
possible better answer: http://stackoverflow.com/a/48020158
has answer: http://stackoverflow.com/a/46941390
tagged with: opencv-contrib
tagged with: python-3.6
type: Question
accepted answer: http://stackoverflow.com/a/46941390
has body: I am trying to use LBPHfacerecognizer in my python3.6 code. recognizer = cv2.face.createLBPHFaceRecognizer() I am aware that face module is in opencv_contrib module. I even uninstalled openCV and installed again with contrib module. I compiled OpenCV with it and python still gives an error which is: AttributeError: module 'cv2.cv2' has no attribute 'face' Although in opencv/build/lib I have libopencv_face.dylib, it doesn't compile with python3 and opencv. I tried everything I can think of but I am running out of ideas. Any ideas? edit: Python doesn't give an error when I am working under python3 environment anymore but I still have the same error when I try to run my code in the terminal. What I am trying to run: python3 main.py Any ideas why I have this problem or how I can fix it?
type: AnsweredQuestion

http://stackoverflow.com/a/46809526
type: Answer
accepted answer of: http://stackoverflow.com/q/46809445
has body: You could store lat, lon and timestamp in a dict: dic_loc = [] def make_timestamped_loc(La, Lng, TS): new_loc = {} new_loc['latitude'] = La new_loc['longitude'] = Lng new_loc['timestamp'] = int(TS) dic_loc.append(new_loc) The sorting could be done like this: newlist = sorted(dic_loc, key=lambda k: k['timestamp'])
has comment: http://stackoverflow.com/comment/80566847
has comment: http://stackoverflow.com/comment/80574166
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46809445
score: 0
has comment: http://stackoverflow.com/comment/80595357
has comment: http://stackoverflow.com/comment/80566265

http://stackoverflow.com/comment/80558223
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46805108
score: 0
has text: Ok, I read a tutorial about Django & Ajax. I'll try this on my free time. Thanks treegarden & neuhaus :)

http://stackoverflow.com/q/46810931
has title: How to install tkinter on python3.6 - reconfigure?
has comment: http://stackoverflow.com/comment/80570730
has body: I'm operating in a somewhat fresh Centos7 environment and it did not appear to ship with tkinter. Python3.6 runs fine, but import tkinter does not find any module. I downloaded ActiveTcl, but the next step according to "option 3" here: http://www.tkdocs.com/tutorial/install.html is to download, configure, and install python. Is there a way I can point my existing python 3.6 environment to find the version of Tcl? Alternatively, any easier way to get tkinter so I can use matplotlib would be great.
has answer: http://stackoverflow.com/a/46814072
type: Question
has comment: http://stackoverflow.com/comment/80575159
answer count: 1
has comment: http://stackoverflow.com/comment/80570517
has comment: http://stackoverflow.com/comment/80577435
score: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/40878944
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80574433
type: UnansweredQuestion
tagged with: centos7
linked to: http://stackoverflow.com/q/40878944

http://stackoverflow.com/a/46821740
upvote count: 1
answers question: http://stackoverflow.com/q/46820254
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46820254
has comment: http://stackoverflow.com/comment/80592515
type: Answer
has comment: http://stackoverflow.com/comment/80592369
downvote count: 0
has body: This depends on whether you have a vertex buffer bound or not. The last parameter pointer in gl*Pointer() is either. No Vertex Buffer Bound: It's the address to the vertices Vertex Buffer Bound: It's a relative offset in relation to the address of the buffer You can utilize ctypes for this. import ctypes buffer_offset = ctypes.c_void_p float_size = ctypes.sizeof(ctypes.c_float) Assuming you have a vertex buffer bound, then you'd simply do: glVertexPointer(3, GL_FLOAT, 12, buffer_offset(0)) glColorPointer(3, GLFLOAT, 12, buffer_offset(float_size * 3)) If you are just using that array and nothing else, then I would assume you could just get the address and equally offset it. glVertexPointer(3, GL_FLOAT, 12, buffer_offset(vertices.ctypes.data)) glColorPointer(3, GLFLOAT, 12, buffer_offset(vertices.ctypes.data + float_size * 3)) But I have to admit, I've never had the need for this in Python, so I can't confirm it.
score: 1

http://stackoverflow.com/q/46752598
has title: Unable to Install Pylint in windows - python?
favorite count: 0
accepted answer: http://stackoverflow.com/a/46752630
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: pip
type: Question
has answer: http://stackoverflow.com/a/46752630
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/80450966
answer count: 1
downvote count: 0
has body: I am new to python, I installed python on windows in the following directory C:\Program Files\Python36, I am using vscode as IDE when I trying to run the following command in integrated terminal "C:\Program Files\Python36\python" -m pip install pylint Exception: Traceback (most recent call last): File "c:\program files\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files\python36\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files\python36\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36\lib\site-packages\pip\utils__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'c:\program files\python36\Lib\site-packages\colorama' How can i resolve this issue?

http://stackoverflow.com/q/46823861
tagged with: list
upvote count: 3
has comment: http://stackoverflow.com/comment/80595121
has comment: http://stackoverflow.com/comment/80595271
has answer: http://stackoverflow.com/a/46823933
type: Question
has title: python to update dict values in list
has answer: http://stackoverflow.com/a/46824509
downvote count: 0
tagged with: python-2.7
answer count: 3
possible better answer: http://stackoverflow.com/a/46824509
has answer: http://stackoverflow.com/a/46824168
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80596946
favorite count: 0
has comment: http://stackoverflow.com/comment/80596547
has body: I have a list with two element (key-value pair)in it. Both element has same keys in it. however few values are different, shown as below. alist = [{u'a': u'x', u'b': u'y', u'c': u'z'}, {u'a': u'x', u'b': u'm', u'c': u'n'}] I want to update new data to alist from available in dictionary, which is update from user input, shown below. a_dict = {'a': ['user_input_x'], 'b': ['user_input_y', 'user_input_m'], 'c': ['user_input_z', 'user_input_n']} Resultant alist should look like this, ans_alist = [{u'a': u'user_input_x', u'b': u'user_input_y', u'c': u'user_input_z'}, {u'a': u'user_input_x', u'b': u'user_input_m', u'c': u'user_input_n'}] I was trying out few things, below is the snippet, however since it's dict, code is updating all the keys, with same values, for i in range(0, 2): for key in alist: key['a'] = a_dict['a'][i] key['b'] = a_dict['b'][i] key['c'] = a_dict['b'][i] print alist ans_alist = [{u'a': ['user_input_x'], u'b': 'user_input_y', u'c': 'user_input_n'}, {u'a': ['user_input_x'], u'b': 'user_input_y', u'c': 'user_input_n'}] appreciate your help.
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/46824168

http://stackoverflow.com/comment/80452261
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46750654
has text: That's pretty much what I'm doing. However, I found that the problem is really jackd itself and not python. I'll update my question accordingly.
score: 0

http://stackoverflow.com/a/46862695
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46799511
downvote count: 0
answers question: http://stackoverflow.com/q/46799511
type: AcceptedAnswer
has body: It looks that you are trying to use spark 2.X with library from spark 1.5... Fix your --packages option passing valid library version. You can get the possible versions directly from the maven repository.
type: Answer

http://stackoverflow.com/comment/80677080
has text: I guess i'm just not obsessed with one-liners or *looks*. Besides you specifically asked for a something other than a *one-liner* - `...not a single liner solution ...`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46864404
type: AnswerComment

http://stackoverflow.com/q/46889366
has comment: http://stackoverflow.com/comment/80726088
type: Question
has title: 404 Page not found in Django, even though regular expression is correct
has comment: http://stackoverflow.com/comment/80726301
score: 0
has body: I have the following URL in my Django project: url(r'^result/edit/(?P&lt;pk&gt;\d+)/$', views.edit_result, name='edit_result') Unfortunately, even when I manually input http://127.0.0.1:8000/result/edit/2/, it gives back a "page not found", and the view function is not called. The view function can be seen below: def edit_result(request, pk): result = get_object_or_404(Result, pk=pk) group = Group.objects.filter(pk=pk) results = Result.objects.filter(group=group) context = { 'pending_results': results, 'groups': group } return render(request, 'resultregistration/editresult.html', context) Strangely, it works perfectly fine with: http://127.0.0.1:8000/result/edit/1/ (so with 1), but not with 2, even though both objects with primary keys are present in the database. Does anyone know why the view function is not called, even though the regular expression is (I assume) correct? Thank you!
answer count: 1
tagged with: url
has answer: http://stackoverflow.com/a/46889787
accepted answer: http://stackoverflow.com/a/46889787
has comment: http://stackoverflow.com/comment/80726215
tagged with: django
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80726012

http://stackoverflow.com/a/46782145
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46782083
score: 1
upvote count: 1
has body: Building off of @COLDSPEED's comment, if you want a list of 20 number different random numbers between -500 and 500. You can use a while loop to build a set of the random numbers, then convert it to a list. import random rand_set = set() while len(rand_set) &lt; 20: x = random.randint(-500,500) if x not in rand_set: rand_set.add(x) rand_list = list(rand_set)

http://stackoverflow.com/q/46756686
type: Question
has comment: http://stackoverflow.com/comment/80458738
has body: How can I call a specific list with items in a dictionary? I want to use the key name, and output Richmond, in the station list. A tutorial I was using is outdated, so the best I could manage was this loop that printed the keys and items: for key, value in data.items(): print(key, value) That revealed the two outermost keys (?xml and root), but there are nested dictionaries I would like to access. What I would like: for item in data['station'] print(item['name']) &gt;&gt;&gt; Richmond Instead I get KeyError with station. Seeing as how ?xml and root are the keys identified with the loop, I'm presuming I need a nested loop, first going through the root key, and then accessing station, and then using the key name to print Richmond. The API result: { "?xml": { "@version": "1.0", "@encoding": "utf-8" }, "root": { "@id": "1", "uri": { "#cdata-section": "http://api.bart.gov/api/etd.aspx?cmd=etd&amp;orig=RICH&amp;json=y" }, "date": "10/14/2017", "time": "07:50:17 PM PDT", "station": [{ "name": "Richmond", "abbr": "RICH", "etd": [{ "destination": "Warm Springs", "abbreviation": "WARM", "limited": "0", "estimate": [{ "minutes": "4", "platform": "2", "direction": "South", "length": "6", "color": "ORANGE", "hexcolor": "#ff9933", "bikeflag": "1", "delay": "0" }, { "minutes": "24", "platform": "2", "direction": "South", "length": "6", "color": "ORANGE", "hexcolor": "#ff9933", "bikeflag": "1", "delay": "0" }] }] }], "message": "" } }
score: 0
has title: KeyError with Python dictionary from API
has comment: http://stackoverflow.com/comment/80458836
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80458787
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80458809
tagged with: python
tagged with: dictionary
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/80458699

http://stackoverflow.com/comment/80649973
comment on: http://stackoverflow.com/a/46837973
type: Comment
has text: @al.zatv. Yes, I admit I didn't test anything and it was mostly just a hunch. Anyway, I have added a fully working example to my answer. Can you please test it?
score: 0
type: AnswerComment

http://stackoverflow.com/q/46803077
type: Question
has comment: http://stackoverflow.com/comment/80552801
has body: I'm new to web crawling and want to learn how to use beautifulsoup to integrate it on a mini project. I was following thenewboston tutorial on beautifulsoup on his youtube channel then got stuck trying to crawl off of Reddit. I want to crawl titles and links on each of the NBA news on Reddit/r/nba but didn't have any success. Only thing that return in the terminal was "Process finished with exit code 0". I have a feeling it was to do with my selections? Any guidance and help would be greatly appreciated. This is the original code, didn't work: import requests from bs4 import BeautifulSoup def spider(max_pages): page = 1 while page &lt;= max_pages: url = 'https://reddit.com/r/nba' + str(page) source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") for link in soup.find_all('a', {'class': 'title'}): href = link.get('href') print(href) page += 1 spider(1) I tried doing this way but that didn't solve the problem: import requests from bs4 import BeautifulSoup def spider(max_pages): page = 1 while page &lt;= max_pages: url = 'https://www.reddit.com/r/nba/' + str(page) source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") for link in soup.findAll('a', {'class': 'title'}): href = "https://www.reddit.com/" + link.get('href') title = link.string print(href) print(title) page += 1 spider(1)
score: 0
has answer: http://stackoverflow.com/a/46804868
answer count: 1
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/80552979
has comment: http://stackoverflow.com/comment/80591255
tagged with: python
has comment: http://stackoverflow.com/comment/80591323
has comment: http://stackoverflow.com/comment/80552865
type: UnansweredQuestion
has title: Unable to crawl Reddit's NBA page
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/80588582

http://stackoverflow.com/a/46802435
has body: This should work I think for i in range(5): print("*",end="") for a in range(i): print(".",end="") print("*"*(i+1))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46802371

http://stackoverflow.com/q/46899812
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/22216076
has body: I want to write root's title value to the excel column A, my code: from openpyxl import Workbook import os path = "C:/path_to_folder" #word = '&lt;option value="1.2.0-b.1" key="#SSPVersion#"/&gt;' os.chdir(path) #change directroy to application notes folder titlelist = [] for root, dirs, files in os.walk(path): title = str(root.split("/")[-1]) titlelist.append(title) wb = Workbook() ws = wb.active r=2 for t in titlelist: ws.cell(row=r, column = 1).value = str(t) r += 1 wb.save("row_creation_loop.xlsx") This does not work...always shows Error : traceback(most recent call last): ws[column_cell+str(row+2)] = stri(i) self[key].value = value self._bind_value(value) value = self.check_string(value) value = unicode(value, self.encoding) unicodeDecodeError: 'utf8' codec can't decode byte 0*92 in position 17: invalid start byte
score: -1
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/46900717
tagged with: excel
has comment: http://stackoverflow.com/comment/80748121
type: Question
has comment: http://stackoverflow.com/comment/80747085
has title: Iterate write row value to excel python, what's wrong with my code?
upvote count: 0
accepted answer: http://stackoverflow.com/a/46900717
answer count: 1

http://stackoverflow.com/comment/80633649
score: 0
type: Comment
type: QuestionComment
has text: yes. It produces same results, i.e. all requirements satisfied
comment on: http://stackoverflow.com/q/46842995

http://stackoverflow.com/comment/80530162
score: 0
comment on: http://stackoverflow.com/q/46791742
type: Comment
type: QuestionComment
has text: What do you mean with "binary file"? How does such a file look like?

http://stackoverflow.com/a/46834730
type: Answer
accepted answer of: http://stackoverflow.com/q/46834214
has body: Incase want to know.. A Pythonic 1 liner solution x = ('"','!','?',',') y = input('Write your essay here.') len([i for i in y if i in x])
answers question: http://stackoverflow.com/q/46834214
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80657901
type: QuestionComment
has text: and yes, i am using python2
comment on: http://stackoverflow.com/q/46855071
score: 0
type: Comment

http://stackoverflow.com/comment/80732478
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46891054
has text: i am updating my findings - with your answers direction.

http://stackoverflow.com/comment/80493933
score: 2
comment on: http://stackoverflow.com/q/46774025
has text: I don't get? You want to remove all non-prime numbers ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80586359
type: QuestionComment
has text: I can't because its a concept of a different file
score: 0
comment on: http://stackoverflow.com/q/46818539
type: Comment

http://stackoverflow.com/a/60367421
score: 0
type: Answer
has body: I think you need to preprocess your dataset. You can replace the Nan value with some meaningful values. some useful answer can be seen here- numpy array: replace nan values with average of columns
answers question: http://stackoverflow.com/q/46805647

http://stackoverflow.com/a/47014179
has comment: http://stackoverflow.com/comment/80974744
has comment: http://stackoverflow.com/comment/80977300
has comment: http://stackoverflow.com/comment/80974785
has comment: http://stackoverflow.com/comment/80975182
has comment: http://stackoverflow.com/comment/80974652
has comment: http://stackoverflow.com/comment/80974819
score: 0
has body: I have done this a hundred times. It is tempting to name a package the same thing at multiple levels, but resist! I tend to have __main__.py in my packages these days, which helps solve the problem that you are having. I suspect you are having a namespace issue. Try renaming your package or the internal file called cli.py. Be sure to refactor any imports that are attempting to use these. Also, change your function name to something besides cli. Same issue. ├── cli &lt;- rename this to 'my_app' or something else │ ├── __init__.py │ ├── aws │ │ ├── __init__.py │ │ ├── policy.py │ │ └── role.py │ ├── cli.py &lt;- or maybe it is easier to rename this │ └── commands │ ├── __init__.py │ └── cmd_dump.py
has comment: http://stackoverflow.com/comment/80975149
answers question: http://stackoverflow.com/q/46889031
has comment: http://stackoverflow.com/comment/80975037
type: Answer

http://stackoverflow.com/comment/80587412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46819590
score: 0
has text: Guess you can't really do it without iterating over all versions. But is there a way to get the versions if they have a delete marker on them?

http://stackoverflow.com/comment/80494341
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46774295
has text: It just points towards the actual dictionary wherever it is, maybe try `ob = dict(self.order_book)`
score: 0

http://stackoverflow.com/comment/127601013
score: 2
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/72213678
has text: Note that there's nothing deprecated about plotting a series in seaborn. The deprecation warning is only about whether `x` and `y` are implicit (deprecated) or explicit (supported), so the accepted answer is still fully supported as long as we specify `x` and `y` explicitly: `sns.barplot(x=head.index, y=head.values)`

http://stackoverflow.com/q/46855983
type: Question
answer count: 1
tagged with: python
has body: Okay, I've been trying all day to solve this, to no avail... I am working with downloading and analysing RNA-sequencing data, and my analysis incorporates public datasets that come in two flavours: single-end reads and paired-end reads. In essence, every raw file that my workflow start to work on can either be a single file named {sample}.fastq.gz or two files, named {sample}_1.fastq.gz and {sample}_2.fastq.gz, respectively. I have all the samples and their read layouts (and some other info) in a metadata file which I parse with pandas into a dataframe. I need to be able to give parameters to my scripts (here simply abstracted to touch {output}) in order for them to perform their function depending on the read layout (they are all bash scripts using command line software like sratools and STAR). What I want to achieve is something along the following snakemake pseudocode: # Metadata in a pandas dataframe metadata = data.frame(SAMPLES, LAYOUTS, ...) # Function for retrieving metadata def get_metadata(sample, column): result = metadata.loc[metadata['sample'] == sample][column].values[0] return result # Rules rule all: input: expand('{sample}.bam', sample = SAMPLES) rule: download: output: '{sample}.fastq.gz' for 'SINGLE' in metadata[LAYOUT], '{sample}_1.fastq.gz' for 'PAIRED' in metadata[LAYOUT] params: layout = lambda wildcards: get_metadata(wildcards.sample, layout_col) shell: 'touch {output}' rule align: input: '{sample}.fastq.gz' for 'SINGLE' in metadata[LAYOUT], '{sample}_1.fastq.gz' for 'PAIRED' in metadata[LAYOUT] params: layout = lambda wildcards: get_metadata(wildcards.sample, layout_col) output: '{sample}.bam' shell: 'touch {output}' In all code variations I have tried so far I either create ambiguous rules, create single-end reads for paired-end IDs (and vice versa) or it all just fails. I have come up with two very unsatisfactory solutions: Have two entirely separate workflows, one working on the single-end inputs and the other for the paired-end, requirin…
has title: Snakemake: merging inputs with different suffixes to same-suffix output
type: UnansweredQuestion
score: 0
tagged with: snakemake
has answer: http://stackoverflow.com/a/46858035

http://stackoverflow.com/comment/80669684
comment on: http://stackoverflow.com/q/46861134
score: 1
has text: See here. http://thepythonguru.com/python-strings/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80576613
comment on: http://stackoverflow.com/q/46813660
score: 0
type: Comment
type: QuestionComment
has text: What is `xxx` inside the `find_all` method? And could you show us the relevant part of the HTML source?

http://stackoverflow.com/comment/80531240
has text: I am using putty on windows to connect my raspberry pi. I am making a car which will move forward while 'w' key is pressed. But unfortunately there is no such way in shh or terminal to tell that a keyboard key is released. So I will make a python program on windows via pyCharm or python IDLE(which suits better) to send shh text string of what is going on and according to that my pi will decide what to do . Now tell me how to send text strings from python console to ssh on windows
comment on: http://stackoverflow.com/q/46791194
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46982798
upvote count: 1
has body: I installed scipy in windows 10 from the whl file from http://www.lfd.uci.edu/~gohlke/pythonlibs/ through pip install command in python3.6.
score: 1
accepted answer of: http://stackoverflow.com/q/46844135
answers question: http://stackoverflow.com/q/46844135
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/46753630
score: 3
upvote count: 3
has body: First create boolean mask by chained conditions with &amp; with functions isnull and notnull. Then is more possible solutions for add 1 - with mask, loc or numpy.where: mask = raw_data['a'].notnull() &amp; raw_data['b'].isnull() raw_data['b'] = raw_data['b'].mask(mask, 1) Or: raw_data.loc[mask, 'b'] = 1 Or: raw_data['b'] = np.where(mask, 1,raw_data['b']) Sample: raw_data = pd.DataFrame({ 'a': [1,np.nan, np.nan], 'b': [np.nan, np.nan,2] }) print (raw_data) a b 0 1.0 NaN 1 NaN NaN 2 NaN 2.0 mask = raw_data['a'].notnull() &amp; raw_data['b'].isnull() print (mask) 0 True 1 False 2 False dtype: bool raw_data.loc[mask, 'b'] = 1 print (raw_data) a b 0 1.0 1.0 1 NaN NaN 2 NaN 2.0 EDIT: If want use custom function (really slow if more data) need apply with axis=1 for processing by rows: def condition(x): if pd.notnull(x.a) and pd.isnull(x.b): return 1 else: return x.b raw_data['b'] = raw_data.apply(condition, axis=1) print (raw_data) a b 0 1.0 1.0 1 NaN NaN 2 NaN 2.0
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46753605
type: Answer
answers question: http://stackoverflow.com/q/46753605

http://stackoverflow.com/q/46761159
tagged with: string
tagged with: pypy
favorite count: 0
tagged with: python
score: 2
upvote count: 2
type: Question
has body: I'm trying to embed a Python function in C using PyPy and cffi. I'm following this guide from the PyPy documentation. The problem is, all the examples I've found operate on ints, and my function takes a string and returns a string. I can't seem to figure out how to embed this function in C, as C doesn't seem to really have strings, rather making do with arrays of chars. Here's what I've tried: # interface.py import cffi ffi = cffi.FFI() ffi.cdef(''' struct API { char (*generate_cool_page)(char url[]); }; ''') ... @ffi.callback("char[] (char[])") def generate_cool_page(url): # do some processing with BS4 return str(soup) def fill_api(ptr): global api api = ffi.cast("struct API*", ptr) api.generate_cool_page = generate_cool_page -- // c_tests.c #include "PyPy.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct API { char (*generate_cool_page)(char url[]); }; struct API api; /* global var */ int initialize_api(void) { static char source[] = "import sys; sys.path.insert(0, '.'); " "import interface; interface.fill_api(c_argument)"; int res; rpython_startup_code(); res = pypy_setup_home(NULL, 1); if (res) { fprintf(stderr, "Error setting pypy home!\n"); return -1; } res = pypy_execute_source_ptr(source, &amp;api); if (res) { fprintf(stderr, "Error calling pypy_execute_source_ptr!\n"); return -1; } return 0; } int main(void) { if (initialize_api() &lt; 0) return 1; printf(api.generate_cool_page("https://example.com")); return 0; } When I run gcc -I/opt/pypy3/include -Wno-write-strings c_tests.c -L/opt/pypy3/bin -lpypy3-c -g -o c_tests and then run ./c_tests, I get this error: debug: OperationError: debug: operror-type: CDefError debug: operror-value: cannot render the type &lt;char()(char *)&gt;: it is a function type, not a pointer-to-function type Error calling pypy_execute_source_ptr! I don't have a ton of experience with C and I feel like I'm misrepresenting the string argument/return value. How do I do this properly? Thanks for your help!
type: AnsweredQuestion
tagged with: python-cffi
accepted answer: http://stackoverflow.com/a/46766406
tagged with: http://stackoverflow.com/tag/c
linked to: http://stackoverflow.com/q/5110706
linked to: http://stackoverflow.com/q/63870021
has answer: http://stackoverflow.com/a/46766406
downvote count: 0
answer count: 1
has title: How can I embed a Python function that returns a string in C using cffi?

http://stackoverflow.com/a/46903891
score: 5
has body: You're modifying the list as you iterate over it. You could just use list comprehension to make both lists but i'd look into why you have a multi-typed list in the first place non_ints = [not isinstance(a, int) for a in list_d] ints = [isinstance(a, int) for a in list_d] or as a single interation version non_ints = [] ints = [] for a in list_d: if isinstance(a, int): ints.append(a) else: non_ints.append(a)
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46903841

http://stackoverflow.com/q/46792488
has title: Passing User object in celery using django
upvote count: 3
tagged with: celery
type: Question
has body: I'm currently editing the save method in one of my models, so that I can save who changed an object or created a new one. Currently, its working fine when its ran in the main thread, but the save method is also used in different tasks through Celery. And when the save method is ran in a task get user returns None. To get a user i'm currently using django-curser since this model is being used in different apps inside my Django project. Is there a way to send the current user to celery? I've been told to use a context manager or a wrapper but im not sure how. My save method is: def save(self, *args, **kwargs): from models import Log log_entry = Log() log_entry.object_id = self.id log_entry.object_repr = self user = CuserMiddleware.get_user() log_entry.user = user log_entry.content_type_id = ContentType.objects.get_for_model(self).id log_entry.save() Thanks.
has comment: http://stackoverflow.com/comment/80533151
score: 3
answer count: 1
has answer: http://stackoverflow.com/a/46793923
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46793923
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80532835
type: AnsweredQuestion

http://stackoverflow.com/q/46805200
has answer: http://stackoverflow.com/a/46805285
accepted answer: http://stackoverflow.com/a/46805285
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80557436
tagged with: unit-testing
type: Question
has body: I'm attempting to write unit tests for a program that relies on module-level data(a JSON file). So, I was thinking I would set up a test JSON file using the setUpClass classmethod and then tear it down after the tests have been run. The issue I have is that the set up of the module-level JSON returns a value which is required by other functions of the program which I also intend to test. Here is an example of what I mean: import unittest import myProg class TestProg(unittest.TestCase): @classmethod def setUpClass(cls): # initialize() creates the JSON file myProg.initialize() f = myProg.initialize_storage() return f def test_prog_func(self): myProg.prog_func("test_key", "test_value", f) f is the item which is required by the rest of my functions. this code does not work. I'm looking for a way to allow me to "return f" from the setUpClass to be used throughout the test.
has title: Can unittest's setUpClass classmethod return a value to be used throughout the other tests?
tagged with: class
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80719141
type: AnswerComment
comment on: http://stackoverflow.com/a/46885719
type: Comment
score: 2
has text: @NM: to word it differently, for `LHS + RHS`, for `not issubclass(type(RHS), type(LHS))`, `LHS.__add__(RHS)` is called first, and if that doesn't exist or returns `NotImplemented` *only then* is `RHS.__radd__(LHS)` tried. The subclass exception is there to make it possible to subclass existing types and 'capture' the operator hook.

http://stackoverflow.com/q/46871302
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: 1
has title: Logits and labels must be same size
has comment: http://stackoverflow.com/comment/80690232
has comment: http://stackoverflow.com/comment/80692935
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/80690108
has comment: http://stackoverflow.com/comment/80692371
tagged with: neural-network
has body: I'm trying to create a neural network that takes 13 features as input from multiple csv files one at a time and measure accuracy after each iteration. Here is my code snippet: import tensorflow as tf import numpy as np from tensorflow.contrib.layers import fully_connected import os import pandas as pd n_inputs = 13 n_hidden1 = 30 n_hidden2 = 10 n_outputs = 2 learning_rate = 0.01 n_epochs = 40 batch_size = 1 patient_id = os.listdir('./subset_numerical') output = pd.read_csv('output.csv') sepsis_pat = output['output'].tolist() X = tf.placeholder(tf.float32, shape=[None, n_inputs], name="X") y = tf.placeholder(tf.int64, shape=[None], name="y") def data_processor(n): id = pd.read_csv('./subset_numerical/'+patient_id[n]) id_input = np.array([id['VALUE'].tolist()]) for s in sepsis_pat: if str(s) == str(patient_id[n].split('.')[0]): a = 1 try: if a == 1: a = 0 return [id_input, np.array([1])] except: return [id_input, np.array([0])] def test_set(): id_combined = [] out = [] for p in range(300, len(patient_id)): try: id1 = pd.read_csv('./subset_numerical/' + patient_id[p]) id_input1 = np.array(id1['VALUE'].tolist()) id_combined.append(id_input1) for s in sepsis_pat: if str(s) == str(patient_id[p].split('.')[0]): a = 1 try: if a == 1: a = 0 out.append([1, 0]) except: out.append([0, 1]) except: pass return [np.array(id_combined), np.array(out)] # Declaration of hidden layers and calculation of loss goes here # Construction phase begins with tf.name_scope("dnn"): hidden1 = fully_connected(X, n_hidden1, scope="hidden1") hidden2 = fully_connected(hidden1, n_hidden2, scope="hidden2") logits = fully_connected(hidden2, n_outputs, scope="outputs", activation_fn=None) # We will apply softmax here later # Calculating loss with tf.name_scope("loss"): xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits) loss = tf.reduce_mean(xentropy, name="loss") # Training with gradient descent optimizer with tf.name_scope("train"): optimizer = tf.train.GradientDescentOptimizer(…
has answer: http://stackoverflow.com/a/46872109
has answer: http://stackoverflow.com/a/46873088
has comment: http://stackoverflow.com/comment/80690074
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/46794284
upvote count: 1
has body: I think this should do the job : with open(os.path.expanduser('~FOLDER\\numbers.txt'), 'r') as res: for line in res: var['Number ': line] More info here
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46794017

http://stackoverflow.com/comment/80724874
comment on: http://stackoverflow.com/q/46888359
type: Comment
score: 0
has text: Does your a.sh have execute permissions on it (chmod 755 a.sh)?
type: QuestionComment

http://stackoverflow.com/a/46776045
type: Answer
has body: Use pandas groupby and aggregate it by sum (use Dated as column name, instead of the reserved Date): df.groupby(['Dated']).sum()
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/46775668
accepted answer of: http://stackoverflow.com/q/46775668
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/a/46766297
score: 0
answers question: http://stackoverflow.com/q/46763300
has comment: http://stackoverflow.com/comment/80480722
has body: I made this script. In router_cfg I stored the output you provided. r = re.compile('(?:(vpls\w+)\s)?(sdp [\w\.]+)\s(?:(backup)\s)?(lsp [\w-]+)') for line in r.findall(router_cfg): if line[0]: vpls = line[0] print ' : '.join([vpls, line[1],line[3],line[2]]) If there is something you don't understand just ask.
type: Answer
has comment: http://stackoverflow.com/comment/80480374
has comment: http://stackoverflow.com/comment/80481017

http://stackoverflow.com/a/46757864
type: AcceptedAnswer
score: 0
type: Answer
has body: By default Python takes input as string , so you need to convert it as int And you need to return something from function or convertscore(line) will return null always. Below will work in python 2.7. Please check def convertscore(score): grade = "" if score &gt;=101: grade = "Score is over 100%. Are you sure this is right? \n" grade += "A" elif score &gt;=90: grade = "A" elif score &gt;=80 &lt;=89: grade = "B" elif score &gt;=70 &lt;=79: grade = "C" elif score &gt;= 60 &lt;=69: grade = "D" elif score &gt;=0 &lt;=59: grade = "F" elif score &lt; 0: grade = "Score cannot be less than zero." else: grade = "Unable to convert score." return grade print("This program creates a file of letter grades from a file of scores on a 100-point scale.") #print() #get the file names infileName = input("What file are the raw scores in? ") outfileName = input("What file should the letter grades go in? ") #open the files infile = open(infileName, 'r') outfile = open(outfileName, 'w') #process each line of the output file for line in infile: #write to output file outfile.write(convertscore(int(line))) outfile.write("\n") #close both files infile.close() outfile.close() #print() print("Letter grades were saved to", outfileName)
accepted answer of: http://stackoverflow.com/q/46757531
answers question: http://stackoverflow.com/q/46757531
has comment: http://stackoverflow.com/comment/80484193

http://stackoverflow.com/comment/82330332
has text: If this worked for you, please mark it as the correct answer with the green arrow! :)
type: Comment
comment on: http://stackoverflow.com/a/46897530
score: 0
type: AnswerComment

http://stackoverflow.com/q/46774291
has comment: http://stackoverflow.com/comment/80506656
has title: BeautifulSoup - different result lengths
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has body: from url = 'https://www.example.com/MOVxxxx/YYYY-MM-DD' i am using loop on the page with range (the xxx = ID MOV) & (date) for page1 in mov_pages: for page2 in date_pages: response = get('https://www.example.com + page1 + '/' + page2) page_html = BeautifulSoup(response.text, 'html.parser') containers_1 = page_html.find_all('ul', class_='showtime-lists') containers_2 = page_html.find_all('div', class_='day') the html structure like this: ... <format="2D" movie="3247" time="12.00" ... <format="2D" movie="3247" time="13.30" ... ... and in another structure (same page) .. .. ... My purpose is to create dataframe from lists with format like this: date time movie 2017-10-14 12.00 3247 2017-10-14 13.30 3247 2017-10-14 12.00 3252 ... 2017-10-15 2017-10-15 ... ... ... the problem is : * the structure given different lengths My best trial : * I can create the df with time&movie correctly but not the date (because the date didnt have the same length) My Code : #extract movie & time was similar way movie = [] for container in containers_1: idx = container['movie'] movie.append(idx) #extract date date_id = [] for each in containers_2: date_idx = each.a['date'] date_id.append(date_idx) OUTPUT : movie&time had same length but not with date
tagged with: python
has comment: http://stackoverflow.com/comment/80513490
tagged with: list
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: web-scraping
upvote count: 1
type: Question

http://stackoverflow.com/comment/80455919
comment on: http://stackoverflow.com/q/46755129
has text: Why are you converting your coordinates to strings?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/46891585
has comment: http://stackoverflow.com/comment/80731847
downvote count: 0
has comment: http://stackoverflow.com/comment/80731413
score: 1
type: Answer
has body: Option 1: nmap switches You could accomplish that only using nmap options. From the nmap(1) man page: PORT SPECIFICATION AND SCAN ORDER: -p &lt;port ranges&gt;: Only scan specified ports Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9 Option 2: python loop You should reimplement your method to accept a port as well: def get_nmap(options,ip,port): command = "nmap" + "-p" + str(port) + " " + options + "" + ip process = os.popen(command) result = str(process.read()) return result And then call it in a loop: for port in range(0, 65535): print(get_nmap('', ip, port)) Note: -F won't work with a specific port range, since it defines: -F: Fast mode - Scan fewer ports than the default scan
has comment: http://stackoverflow.com/comment/80732348
has comment: http://stackoverflow.com/comment/80731698
upvote count: 1
has comment: http://stackoverflow.com/comment/80731023
answers question: http://stackoverflow.com/q/46891422

http://stackoverflow.com/q/46840037
has comment: http://stackoverflow.com/comment/80628325
tagged with: deep-learning
has body: I have tensorflow-gpu 1.2.1 and keras on ubuntu 16.04. I am not able to perform: from kears.utils import multi_gpu_model Has anyone had success with multi_gpu_model as described in their documentation's FAQ section? I have a 4 GPU machine with 4 GeForce GTX 1080 Ti cards and want to use all of them. Here's the error I get: import keras.utils.multi_gpu_model --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-7-0174878249b1&gt; in &lt;module&gt;() ----&gt; 1 import keras.utils.multi_gpu_model 2 ModuleNotFoundError: No module named 'keras.utils.multi_gpu_model' I can import keras and keras.utils successfully.
tagged with: neural-network
has comment: http://stackoverflow.com/comment/80631232
has comment: http://stackoverflow.com/comment/80628270
tagged with: keras
has title: Cannot import multi_gpu_model from keras.utils
has answer: http://stackoverflow.com/a/70183412
favorite count: 0
has comment: http://stackoverflow.com/comment/80631281
has answer: http://stackoverflow.com/a/46849171
answer count: 5
tagged with: gpu
type: UnansweredQuestion
tagged with: python
upvote count: 11
has answer: http://stackoverflow.com/a/66470693
has comment: http://stackoverflow.com/comment/80628242
has comment: http://stackoverflow.com/comment/80628369
has answer: http://stackoverflow.com/a/58543573
has answer: http://stackoverflow.com/a/46857914
downvote count: 1
type: Question
score: 10

http://stackoverflow.com/a/46762264
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46762216
has body: There’s no need to turn the string into a list, since it’s already an iterable. Instead, just do something like this: numbers = input(‘Enter numbers: ‘) total = 0 for char in numbers: total += int(char) print(total) This goes through each character in the string, turns it into an integer, and adds it to the total.

http://stackoverflow.com/comment/80750097
comment on: http://stackoverflow.com/a/46901641
type: Comment
score: 1
has text: Please don't name-shadow built-ins; you've done it twice here, for `input` and `sorted`.
type: AnswerComment

http://stackoverflow.com/comment/80452264
type: Comment
type: QuestionComment
has text: If someone's answer does/is what you need, do not forget to check it as correct. This is how things work on SO.
comment on: http://stackoverflow.com/q/46752943
score: 0

http://stackoverflow.com/comment/80588587
type: Comment
has text: @anupsabraham riiight ok. Edited
score: 0
comment on: http://stackoverflow.com/a/46820381
type: AnswerComment

regression
tags question: http://stackoverflow.com/q/46749402
tags question: http://stackoverflow.com/q/46755340
tag name: regression
type: Tag
tags question: http://stackoverflow.com/q/46790654
tags question: http://stackoverflow.com/q/46752742
tags question: http://stackoverflow.com/q/46820317
tags question: http://stackoverflow.com/q/46861158
tags question: http://stackoverflow.com/q/46899217

http://stackoverflow.com/comment/80641621
type: QuestionComment
comment on: http://stackoverflow.com/q/46846794
has text: Thanks for pointing me this. In my opinion, setting a password or not doesn't change anything to the security level because in both case I will be able to reset it via email. If I have to set a password in order to reset it why shouldn't be able to reset it directly ?
score: 0
type: Comment

http://stackoverflow.com/q/46804602
has comment: http://stackoverflow.com/comment/80557305
type: Question
tagged with: python-3.4
has answer: http://stackoverflow.com/a/46805163
tagged with: pyserial
has body: I get a nameError when using Serial. I believe that i am not importing serial properly. from serial import * serialPort = Serial("COM3", 9600) i've installed pyserial through pip. Am i doing something wrong? Has anyone else experienced this error?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80598431
tagged with: python
upvote count: 2
type: UnansweredQuestion
has title: Error importing from pyserial
has comment: http://stackoverflow.com/comment/80556226
has comment: http://stackoverflow.com/comment/80556194
downvote count: 1
linked to: http://stackoverflow.com/q/19728535
has comment: http://stackoverflow.com/comment/80557229
score: 1

http://stackoverflow.com/comment/80576600
type: Comment
score: 0
type: AnswerComment
has text: @dner print statements are you friend here, you should try printing phrases before and after the split, and then you can see if you can replicate this in the repl (e.g. ipython).
comment on: http://stackoverflow.com/a/46796913

http://stackoverflow.com/comment/80745631
type: AnswerComment
comment on: http://stackoverflow.com/a/46894228
type: Comment
has text: 1. Did you install app, changed field, make migrations? in which line do you have this error?
score: 0

http://stackoverflow.com/comment/80491763
comment on: http://stackoverflow.com/a/46772919
type: Comment
score: 0
type: AnswerComment
has text: because your script was also replacing quotes

http://stackoverflow.com/q/46831801
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/46884227
score: 2
accepted answer: http://stackoverflow.com/a/46884227
type: AnsweredQuestion
downvote count: 0
tagged with: app-engine-flexible
type: Question
has body: I run a flexible service for heavy load on Google App Engine Python Flexible Environment. I run PSQ workers to handle tasks through Pub/Sub. This is all fine and dandy as long as I work with single-threaded workers. On single threaded workers, if I instantiate a datastore client like so: from google.cloud import datastore _client = datastore.Client(project='project-name-kept-private') ... and retrieve an entity: entity = _client.get(_client.key('EntityKind', 1234)) ... it works fine. However, once I do this exact same thing in a multi-threaded worker, it freezes on the last line: entity = _client.get(_client.key('EntityKind', 1234)) I know it fails exactly on this line because I user logging.error before and after that specific line like so: import logging logging.error('entity test1') entity = _client.get(_client.key('EntityKind', 1234)) logging.error('entity test2') The line entity test1 and entity test2 both appear in the logs on a single-threaded worker, but only entity test1 gets printed on a multi-threaded worker. It never finishes the task – it just gets stuck on that line. Any advice or pointers in the right the direction would be of great help. I've been struggling with this issues for quite some time now.
upvote count: 2
has title: Google Cloud Python Flexible Environment Multithreaded database worker freezes
answer count: 1
tagged with: google-cloud-pubsub
favorite count: 0
tagged with: google-app-engine

http://stackoverflow.com/comment/80652171
type: QuestionComment
has text: That example doesn't suffer from `a`'s assignment being delayed; you just shouldn't call `do()` before setting it.
comment on: http://stackoverflow.com/q/46828089
score: 0
type: Comment

http://stackoverflow.com/q/46823540
has comment: http://stackoverflow.com/comment/80594475
has comment: http://stackoverflow.com/comment/80594621
has title: How to create multi iterator and conditions in a for loop in python?
has answer: http://stackoverflow.com/a/46823634
accepted answer: http://stackoverflow.com/a/46823690
has comment: http://stackoverflow.com/comment/80594667
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/46823690
tagged with: python
has answer: http://stackoverflow.com/a/46823695
score: 2
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/46823593
downvote count: 0
has comment: http://stackoverflow.com/comment/80594517
has answer: http://stackoverflow.com/a/46823593
has body: How can I make a for loop with multiple conditions in python similar to other languages? for ( i = 0, j=10; i&lt;10 &amp;&amp; j&gt;0; i++, j-- ) or a bit more complex for ( i = 0, j=10; i&lt;10 &amp;&amp; j&gt;0 &amp;&amp; flag; i+=3, j+=2 ) for ( i = 0, j=10; i&lt;10 &amp;&amp; j&gt;0 &amp;&amp; i&lt;j; i+=3, j+=2 )
type: Question
upvote count: 2
tagged with: iterator
tagged with: for-loop

http://stackoverflow.com/comment/80694670
type: Comment
type: QuestionComment
score: 1
has text: ?? I did not ask you any question, you must be mistaken!
comment on: http://stackoverflow.com/q/46873390

http://stackoverflow.com/q/46762597
downvote count: 1
has comment: http://stackoverflow.com/comment/80472730
favorite count: 0
has body: Here's my data id 123246512378 632746378456 378256364036 159204652855 327445634589 I want to make data that consist of data that consist dual three consecutive numbers like 123246512378, 3274456|34589 is reduced id 632746378456 378256364036 159204652855
has comment: http://stackoverflow.com/comment/80481301
linked to: http://stackoverflow.com/q/46556587
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80474256
has title: How to eliminate data that consist dual three consecutive numbers in python?
has answer: http://stackoverflow.com/a/46762900
has answer: http://stackoverflow.com/a/46764490
has comment: http://stackoverflow.com/comment/80510765
has comment: http://stackoverflow.com/comment/80484386
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/80481001
tagged with: dataframe
tagged with: numpy
score: 0
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/80631041
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46841280
has text: Yeah, I noticed that. But I still have no idea how to fix the problem. Could you give me more specific modification? Thanks

http://stackoverflow.com/a/46872705
answers question: http://stackoverflow.com/q/46872472
upvote count: 1
type: Answer
has body: Since you only have one secret key, your only resort is to re-encrypt the entire database. The proper way is to first not use django's SECRET_KEY for database tasks (even django doesn't use it for things like user passwords) and implement a key-rotation algorithm for your sensitive data. django-fernet-fields provides this function out of the box; however it assumes you are rotating keys as best practice and not as consequence of a compromise. Best-practice key rotation relies on "encryption at use" where a secret is unencrypted with the old key and re-encrypted with the new key upon use. Eventually your most used secrets are re-encrypted and you can do an audit to invalidate or force the re-encryption of the remaining entries.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/46872472
type: AcceptedAnswer

http://stackoverflow.com/q/46878201
tagged with: python
tagged with: conv-neural-network
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/80727852
has title: Python (tensorflow) - Dropout Regularization accuracy results
score: 1
has answer: http://stackoverflow.com/a/46890358
type: Question
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: neural-network
favorite count: 0
has body: I'm trying to complete a code for a classification problem (images classification) in python environment. I built a 5 layers NN with a defined number of neurons, using the gradient descent optimizer from tensorflow library. The first 'complete' code brought to an high level of accuracy, but since an overfitting problem had shown, I just decided to introduce a procedure of dropout regularization. At the end of the first run everything appeared as good, with a Train Accuracy:1.0 and a Test Accuracy:0.9606 after training the model over 1000 iterations. Few seconds later, I decided to re-ran the code, and as you can see by the following two images, something went wrong. Prediction accuracy through dropout regularization - FAIL , Cost function through dropout regularization - FAIL .The simulation stopped before of the last defined iteration without giving me any output warning! Running the same code, how can it be possible? Has anyone had this kind of problem before? Is it a problem of the cross entropy function computation or how can a NN accuracy decay to zero from such an high accuracy level instantaneously?
has comment: http://stackoverflow.com/comment/80722919

http://stackoverflow.com/q/46890371
answer count: 1
accepted answer: http://stackoverflow.com/a/46895932
tagged with: python
has answer: http://stackoverflow.com/a/46895932
has body: I wrote the following script to create a taylor diagram using SkillMetrics, an open-source Python library for calculating model predictions against observations. The script I wrote was: import skill_metrics as sm # Arrange datasets in array stats1 = np.array([ref,m1]) stats2 = np.array([ref,m2]) stats3 = np.array([ref,m3]) # calculating statistics taylor_stats1 = sm.taylor_statistics(stats1[0],stats1[1]) taylor_stats2 = sm.taylor_statistics(stats2[0],stats2[1]) taylor_stats3 = sm.taylor_statistics(stats3[0],stats3[1]) # Store statistics in arrays sdev = np.array([taylor_stats1['sdev'][0], taylor_stats1['sdev'][1], taylor_stats2['sdev'][1], taylor_stats3['sdev'][1]]) crmsd = np.array([taylor_stats1['crmsd'][0], taylor_stats1['crmsd'][1], taylor_stats2['crmsd'][1], taylor_stats3['crmsd'][1]]) ccoef = np.array([taylor_stats1['ccoef'][0], taylor_stats1['ccoef'][1], taylor_stats2['ccoef'][1], taylor_stats3['ccoef'][1]]) which produces: sdev = array([ 0.02556107, 0.06264893, 0.06264893, 0.06264893]) crmsd = array([ 0. , 0.04918169, 0.04824091, 0.05082715]) ccoef = array([ 1. , 0.67423927, 0.68388202, 0.64162831]) I then ran the following to create the taylor diagram: sm.taylor_diagram(sdev,crmsd,ccoef) However, I then received this error: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (1,)
type: AnsweredQuestion
tagged with: matplotlib
type: Question
tagged with: numpy
score: 0
has title: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (1,)

http://stackoverflow.com/comment/80748116
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46898404
score: 0
has text: You should be able to type into the console, unless Sublime executes Python with stdin redirected. In that case try using CMD's `start` command to force running Python with a new console: `"cmd": ["start", "Sublime Python Shell", "D:\\Python36\\python.exe", "-i", "$file"]` plus `"shell": true`. Setting the console window title to "Sublime Python Shell" allows the console settings for just this window to be saved under "HKCU\Console\Sublime Python Shell", or whatever title you use.

http://stackoverflow.com/comment/80526230
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46788765
type: Comment
has text: When I do that I'm getting a TypeError stating that I can''t pickle lock objects as I was when I previously tried using Pickle

http://stackoverflow.com/comment/80641779
type: AnswerComment
type: Comment
has text: I dont think that will be an issue, for our current problem. Please confirm that dict_scan_data has some value or not.
comment on: http://stackoverflow.com/a/46843735
score: 0

http://stackoverflow.com/comment/80755476
has text: Thanks for the comment! So I suppose that having snippets from the same document would also work in this case as they have access to the same styles, references etc.? What I tried to do for now is copy the complete xml schema of the table I want to insert and appending it to the main document which would work similarly to deepcopying it I suppose (but thanks for the suggestion I will look into it).
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46897992

http://stackoverflow.com/comment/80662736
type: Comment
type: QuestionComment
has text: [This answer](https://stackoverflow.com/a/34238688/8747) has a decent explanation.
score: 0
comment on: http://stackoverflow.com/q/46857500

http://stackoverflow.com/q/46822892
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/67895994
type: Question
linked to: http://stackoverflow.com/q/11637045
tagged with: python
answer count: 2
linked to: http://stackoverflow.com/q/3086973
upvote count: 1
accepted answer: http://stackoverflow.com/a/46827006
tagged with: mat-file
has title: How can I convert complex .mat file to csv using python
has comment: http://stackoverflow.com/comment/80605653
has answer: http://stackoverflow.com/a/67895994
has answer: http://stackoverflow.com/a/46827006
type: AnsweredQuestion
has body: I am trying to convert a .mat file to csv using python. The code I am using is import scipy.io import numpy as np data = scipy.io.loadmat("wiki.mat") for i in data: if '__' not in i and 'readme' not in i: np.savetxt(("file.csv"),data[i],delimiter=',') When ever I run this code, I get error as follows: Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; np.savetxt(("file.csv"),data[i],delimiter=',') File "/Library/Python/2.7/site-packages/numpy/lib/npyio.py", line 1258, in savetxt % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('[('dob', 'O'), ('photo_taken', 'O'), ('full_path', 'O'), ('gender', 'O'), ('name', 'O'), ('face_location', 'O'), ('face_score', 'O'), ('second_face_score', 'O')]') and format specifier ('%.18e') I am trying to convert the .mat file from this link: https://data.vision.ee.ethz.ch/cvl/rrothe/imdb-wiki/static/imdb_meta.tar Please help me out with some working solution!
has comment: http://stackoverflow.com/comment/80600922

http://stackoverflow.com/q/46885795
has body: So I am writing a simple dice game, where two players throw two dices and summ up their scores untill one hits the total score of 100. The problem I am facing is, when one of the players hits 100, the game allows another throw, how do I stop it? import random a=random.randint(1,6) b=random.randint(1,6) c=random.randint(1,6) d=random.randint(1,6) ta=0 tb=0 print("Vai vēlaties mest?") y=input("y/n:") if y == "y": print("Jūs uzmetāt:") print (a,b,"|", a+b+ta) print("Pretinieks uzmeta:") print (c,d,"|", c+d+tb) else: print ("Jūs zaudējāt") while ta&lt;=100 and tb&lt;=100: ta+=a+b tb+=c+d a=random.randint(1,6) b=random.randint(1,6) c=random.randint(1,6) d=random.randint(1,6) print("Vai vēlaties mest?") y=input("y/n:") if y == "y": print("Jūs uzmetāt:") print (a,b,"|", a+b+ta,) print("Pretinieks uzmeta:") print (c,d,"|", c+d+tb) if y=="n": print ("Jūs zaudējāt") elif ta&gt;=100: print("Jūs uzvarējāt") elif tb&gt;=100: print("Jūs zaudējāt") And yes I know this can probably be written a lot shorter and better, but this is what is asked of us in school, so only the commands you see here are allowed
has title: Dice game giving one extra turn
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
downvote count: 3
tagged with: python
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/80719040
has answer: http://stackoverflow.com/a/46885850
score: -2

http://stackoverflow.com/a/77482541
answers question: http://stackoverflow.com/q/46781563
has body: the minimum header for python request, as I tested, is: request_headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', 'Referer': 'https://www.nba.com/', # 'Accept': 'application/json, text/plain, */*', # 'Accept-Encoding': 'gzip, deflate, br', # 'Host': 'stats.nba.com', # 'Accept-Language': 'en-US,en;q=0.9', # 'Connection': 'keep-alive' } then, run it: response = requests.get(url, headers = request_headers)
score: 0
type: Answer

http://stackoverflow.com/a/46854113
has body: To get the right size, you must use the idealWidth() method of document(), but this will only be correct when the item is visible so you should apply it when the widget is visible, so you should call the show() method that this change is applied, in addition to calling it every time the text changes. To get the correct height, use the size() method of QTextDocument() class Box(QTextBrowser): def __init__(self, parent=None): QTextBrowser.__init__(self, parent) self.setContentsMargins(0, 0, 0, 0) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) cstring = """ QTextBrowser { border: 0; background-color: #&lt;----&gt;; margin: 0px; padding-left:0; padding-top:0; padding-bottom:0; padding-right:0; } """ ncol = randint(300000, 999999) cstring = cstring.replace('&lt;----&gt;', str(ncol)) self.setStyleSheet(cstring) self.document().contentsChange.connect(lambda: self.customGeometry()) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.setContentsMargins(0, 0, 0, 0) def customGeometry(self): if self.isVisible(): self.setFixedWidth(self.document().idealWidth()) self.setFixedHeight(self.document().size().height()) def showEvent(self, event): self.customGeometry() QTextBrowser.showEvent(self, event) class MainFrame(QScrollArea): def __init__(self, parent=None): QScrollArea.__init__(self, parent) container = QFrame(self) layout = QGridLayout(container) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.show() text = ''' &lt;table border="0" cellspacing="0" cellpadding="5" style="background-color: rgba(119, 212, 212, 0.7);"&gt; &lt;tr&gt; &lt;td width="100"&gt; bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla &lt;/td&gt; &lt;tr&gt; &lt;tr&gt; &lt;td&gt; bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla &lt;/td&gt; &lt;tr&gt; &lt;/table&gt; ''' for row in range(5): for col in range(10): box = Box(container) box.setText(t…
has comment: http://stackoverflow.com/comment/80657456
answers question: http://stackoverflow.com/q/46851971
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80656302
type: Answer
has comment: http://stackoverflow.com/comment/80656089
has comment: http://stackoverflow.com/comment/80655997
score: 2
has comment: http://stackoverflow.com/comment/80671171
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46851971

http://stackoverflow.com/comment/80607712
has text: i even tried this with re.sub as an anonymous function but it didnt work :( data['full_text'] = data['full_text'].apply(lambda x: re.sub(r'\\(?=\")','"',x))
type: AnswerComment
comment on: http://stackoverflow.com/a/46822056
score: 0
type: Comment

http://stackoverflow.com/a/46834777
answers question: http://stackoverflow.com/q/46833936
has comment: http://stackoverflow.com/comment/80618033
has comment: http://stackoverflow.com/comment/80618276
has comment: http://stackoverflow.com/comment/80618058
type: Answer
has comment: http://stackoverflow.com/comment/80618212
has body: I think handing it a callback which prints to a single filehandle will result in jumbled results The solution is to populate a Queue in your callback with the result and then fetch them later. Queues are thread-safe so you don't have to worry about the jumbled results you're talking about. from queue import Queue results = Queue() def callback(result): results.put(result) later item = results.get()
has comment: http://stackoverflow.com/comment/80619304
has comment: http://stackoverflow.com/comment/80617850
has comment: http://stackoverflow.com/comment/80617636
score: 0

http://stackoverflow.com/comment/80707923
type: Comment
type: QuestionComment
has text: use `modulo` (`%`) instead
score: 0
comment on: http://stackoverflow.com/q/46880365

http://stackoverflow.com/a/46879954
has comment: http://stackoverflow.com/comment/80708284
accepted answer of: http://stackoverflow.com/q/46879683
has body: bill=0 for i in range(item_cart): scan1=random.choice(random.choice(list_of_lists)) if scan1 in ["twix", "pineapple",....]: bill+=1 print("here are your items") print("total: {}".format(bill))
answers question: http://stackoverflow.com/q/46879683
type: Answer
has comment: http://stackoverflow.com/comment/80714151
has comment: http://stackoverflow.com/comment/80710936
has comment: http://stackoverflow.com/comment/80710873
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/80748659
comment on: http://stackoverflow.com/a/46900729
score: 0
type: AnswerComment
type: Comment
has text: it looks like at some point the library is trying to access an attribute within your `CreateUser` class that does not exist, `name`.. You need to make sure to implement all necessary attributes and methods in your `CreateUser` class in order for the api to use it successfully. Unfortunately, I am unfamiliar with the library so I cannot tell you exactly what needs to be implemented

http://stackoverflow.com/a/67786308
answers question: http://stackoverflow.com/q/46861760
downvote count: 0
type: Answer
upvote count: 1
has body: Your indexing could be modified as: imgMosaic[:28, :40, :] First 28 row element, first 40 column elements and all elements in the last axis. imgMosaic[:28, :40, :].shape &gt;&gt;&gt; (28,40,3)
score: 1

http://stackoverflow.com/q/46895876
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/53217217
downvote count: 1
type: Question
upvote count: 0
score: -1
tagged with: spark-submit
has title: spark-submit with python entry points
answer count: 2
tagged with: entry-point
tagged with: apache-spark
has answer: http://stackoverflow.com/a/46906076
has body: I have a script wordcount.py I used setuptools to create an entry point, named wordcount, so now I can call the command from anywhere in the system. I am trying to execute it via spark-submit (command: spark-submit wordcount) but it is failing with the following error: Error: Cannot load main class from JAR file:/usr/local/bin/wordcount Run with --help for usage help or --verbose for debug output However the exact same command works fine when I provide the path to the python script (command: spark-submit /home/ubuntu/wordcount.py) Content of wordcount.py import sys from operator import add from pyspark.sql import SparkSession def main(args=None): if len(sys.argv) != 2: print("Usage: wordcount &lt;file&gt;", file=sys.stderr) exit(-1) spark = SparkSession\ .builder\ .appName("PythonWordCount")\ .getOrCreate() lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0]) counts = lines.flatMap(lambda x: x.split(' ')) \ .map(lambda x: (x, 1)) \ .reduceByKey(add) output = counts.collect() for (word, count) in output: print("%s: %i" % (word, count)) spark.stop() if __name__ == "__main__": main() Do you know if there is a way to bypass this? Thanks a lot in advance.

http://stackoverflow.com/comment/80744796
score: 0
has text: @sayedgouda I managed to write it after all! It took a while, but should work now!
type: AnswerComment
comment on: http://stackoverflow.com/a/46896757
type: Comment

http://stackoverflow.com/a/46890758
upvote count: 1
downvote count: 0
has body: Just to put @Chris_Rands's excellent comment into an answer: The simplest way is to turn the list of vowels into a set and compare the letters in word.lower() against it using any(): vowels = set("aeiou") def e_silaba(word): return any(x in vowels for x in word.lower()) If you want to make sure the word is not entirely composed of vowels you can use this solution: vowels = set("aeiou") def e_silaba(word): if all(x in vowels for x in word.lower()): return False else: return any(x in vowels for x in word.lower()) This will exclude "a" and "i" which actually are words though. As one last example, if you only want to check that condition for words of at least two characters, use this: vowels = set("aeiou") def e_silaba(word): if len(word) &gt; 1 and all(x in vowels for x in word.lower()): return False else: return any(x in vowels for x in word.lower()) Hopefully this is enough to illustrate how you could add more conditions.
score: 1
answers question: http://stackoverflow.com/q/46889206
type: Answer

http://stackoverflow.com/comment/80583429
score: 0
type: AnswerComment
has text: Beat me by a minute! For what it's worth, you could also use df.ix[::7]
type: Comment
comment on: http://stackoverflow.com/a/46818000

http://stackoverflow.com/q/46819212
has answer: http://stackoverflow.com/a/46820701
has title: Error in R: The h5py Python package is required to save and load models
type: UnansweredQuestion
score: 6
type: Question
has body: I am using R 3.4.2. I am following example from decryptr package library(decryptr) # Download captchas captcha &lt;- download_tjmg(dest = 'img') keras_tjmg &lt;- decryptrModels::read_model('tjmg') Last line of code produce an error Error in keras::load_model_hdf5(file_path) : The h5py Python package is required to save and load models I have tried to reinstall h5py package from terminal. I have also installed keras package. I can import h5py package in pyrthon, but Rstudio doesn't recognize it somehow.
answer count: 2
has comment: http://stackoverflow.com/comment/85086902
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/64648966
tagged with: h5py
tagged with: python
upvote count: 6

http://stackoverflow.com/q/46837947
score: 5
tagged with: pyqt
downvote count: 0
answer count: 1
has title: How to create an abstract base class in python which derived from QObject
favorite count: 0
tagged with: python
has body: I'm trying to create an abstract base class for an interface, but I need it to derive from QObject for signals and slots. My class definition looks like this: import abc from PyQt5.QtCore import QObject class interface_class(abc.ABC, QObject): pass It fails with: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Any ideas? thanks
type: UnansweredQuestion
tagged with: pyqt5
has answer: http://stackoverflow.com/a/46855490
type: Question
linked to: http://stackoverflow.com/q/28720217
upvote count: 5

http://stackoverflow.com/q/46766530
tagged with: find
possible better answer: http://stackoverflow.com/a/46766621
answer count: 3
has comment: http://stackoverflow.com/comment/80478422
downvote count: 0
has answer: http://stackoverflow.com/a/46766599
has comment: http://stackoverflow.com/comment/80478585
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/80478406
score: 13
tagged with: python
has title: Python: split a string by the position of a character
upvote count: 13
has answer: http://stackoverflow.com/a/69989272
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46766599
has comment: http://stackoverflow.com/comment/80478391
type: Question
has answer: http://stackoverflow.com/a/46766621
has body: How can I split a string by the position of a word? My data looks like this: test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear LoreLoreLore,Greetings from Amsterdam!We have received your wonderful comments and wanted to thank you for sharing your positive experience with us. We are so thankful that you have selected the Andaz Amsterdam for your special all-girls weekend getaway. Please come and see us again in the near future and let our team pamper you and your girlfriends!!Thanks again!Anna MaryAndaz Amsterdam -Guest RelationsReport response as inappropriateThank you. We appreciate your input.This response is the subjective opinion of the management representative' I need this output: responder = 'annamarypeterson, Guest relations Manager' date = 'Responded 1 week ago' response = 'Dear ....' #without 'This response is the subjective opinion of the management representative' I know that the find.() function gives the position of a word, and I want to use this position to tell Python where to split it. For example: splitat = test.find('ago')+3 What function can I use to split with an integer? The split() function does not work with an int.
tagged with: split

http://stackoverflow.com/comment/80518123
comment on: http://stackoverflow.com/q/46785504
type: Comment
type: QuestionComment
score: 0
has text: It's basically infinity, unless you tell us what are the restrictions and limits of the coordinate system plus more information about the units and numbers.

http://stackoverflow.com/q/46827310
tagged with: pycharm
upvote count: 1
has title: PyCharm: "No module named configobj" when under RemoteDebugServer
type: Question
tagged with: pydev
has comment: http://stackoverflow.com/comment/80605516
downvote count: 0
answer count: 1
score: 1
has body: I can debug my scripts in local interpreter mode in Pycharm, but when a remote debugging environment for python is configured via: import pydevd add pycharm-debug-egg in path etc I get No module named configobj. Module Configobj is installed in all my local python environments, so the question is: which python interpreter/environment is used when runnng under PYDEVD? Where should I install configobj?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46831003

http://stackoverflow.com/comment/80824266
score: 0
type: AnswerComment
type: Comment
has text: @Paul_H (How do you ping some who has a space in between their username?). Hi. I just have a simple question. Is there a way to add titles to the two main subplots? `Image set 1' to the left, `Image set 2` to the right subplot. Thank you so much.
comment on: http://stackoverflow.com/a/46902866

http://stackoverflow.com/comment/80548781
comment on: http://stackoverflow.com/a/46800957
type: Comment
score: 0
type: AnswerComment
has text: What will be the role of loss value here?

http://stackoverflow.com/q/46847696
type: Question
has title: convert unicode to UTF8 string
has comment: http://stackoverflow.com/comment/80642659
has comment: http://stackoverflow.com/comment/80642666
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46847781
type: UnansweredQuestion
tagged with: python
has body: I need to convert what I think is a unicode string from selenium to a readable UTF8 string (there is a u in the beginning of the string) But what if the string already is UTF8 encoded? Then the multibyte chars will be double encoded td.text.encode('utf-8').strip()
tagged with: selenium

http://stackoverflow.com/q/46831130
has answer: http://stackoverflow.com/a/46831224
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46831219
upvote count: 1
tagged with: python
has title: Add dataframe vector to dataframe table
score: 1
tagged with: dataframe
type: Question
answer count: 2
downvote count: 0
tagged with: pandas
has body: This should be obvious but I cannot make it work. I have a pandas dataframe A with column and index names: A = pd.DataFrame([[10, 20], [4, 5], [20, 30]], columns = ['col1', 'col2'], index = ['row1', 'row2', 'row3']) col1 col2 row1 10 20 row2 4 5 row3 20 30 Then I have another dataframe B with only one row (without name, so default 0) and same column names as A B = pd.DataFrame([[100, 200]], columns = ['col1', 'col2']) col1 col2 0 100 200 I want to add A+B so I obtain a new dataframe C: col1 col2 row1 110 220 row2 104 205 row3 120 230 The most obvious thing would be to do: A + B col1 col2 row1 NaN NaN row2 NaN NaN row3 NaN NaN 0 NaN NaN Then I tried A.sum(B) TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed Am I missing something? numpy arrays will do the job super easily, what's wrong with dataframes? I know the index names don't match, but I want to apply the vector B to all rows of A.

http://stackoverflow.com/q/46884763
score: 0
has title: Whats the meaning of the model default params?
answer count: 3
has answer: http://stackoverflow.com/a/46884847
has comment: http://stackoverflow.com/comment/80716793
has comment: http://stackoverflow.com/comment/80716838
has comment: http://stackoverflow.com/comment/80716881
has answer: http://stackoverflow.com/a/46884829
tagged with: django
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46884829
has body: When I read a project, there I saw the params for create the field: class Task(models.Model): title = models.CharField('标题', max_length=100) description = models.TextField('描述') completed = models.BooleanField('是否完成', default=False) create_date = models.DateTimeField('创建时间', auto_now_add=True) Such as: title = models.CharField('标题', max_length=100) I don't understand the 标题 here has what function.
type: Question
has answer: http://stackoverflow.com/a/46884831
accepted answer: http://stackoverflow.com/a/46884831

http://stackoverflow.com/comment/80688589
type: Comment
comment on: http://stackoverflow.com/q/46870368
type: QuestionComment
has text: go into "/usr/local/lib/python2.7/dist-packages/requests/init.py" around line 60 and 68 it will tell you which version of `urllib3` and `chardet` you need for `requests`
score: 0

http://stackoverflow.com/q/46824441
accepted answer: http://stackoverflow.com/a/46824598
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have a dataframe with columns like this for example (as 1 being any values to simplify things here: ID App R1 Pear R1 Oro R1 App R2 Pear R2 Oro R2 App R3 Pear R3 Oro R3 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 I would like to rearrange the columns like this: ID App R1 App R2 App R3 Pear R1 Pear R2 Pear R3 Oro R1 Oro R2 Oro R3 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 I have tried: df.columns = [['ID'] + ['App R{}'.format(r+1)] + ['Pear R{}'.format(r+1)] + ['Matched fragment ions R{}'.format(r+1)] + ['Oro R{}'.format(r+1)] for r in range(len(files))] n.b: The number r of App, Pear and Oro will depend on the number r of csv I start with However, no success so far. Thank you if you can help me solve this problem.
tagged with: python
has title: Rearrange columns by name and number in Pandas dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46824598
score: 1
possible better answer: http://stackoverflow.com/a/46824512
upvote count: 1
has answer: http://stackoverflow.com/a/46824512
type: Question
has comment: http://stackoverflow.com/comment/80596415

group-by
tags question: http://stackoverflow.com/q/46778541
tags question: http://stackoverflow.com/q/46799588
tags question: http://stackoverflow.com/q/46892103
tags question: http://stackoverflow.com/q/46880050
tags question: http://stackoverflow.com/q/46892392
tags question: http://stackoverflow.com/q/46752253
tags question: http://stackoverflow.com/q/46891001
tags question: http://stackoverflow.com/q/46904575
tag name: group-by
tags question: http://stackoverflow.com/q/46762052
tags question: http://stackoverflow.com/q/46839032
type: Tag
tags question: http://stackoverflow.com/q/46777564
tags question: http://stackoverflow.com/q/46789055
tags question: http://stackoverflow.com/q/46861899
tags question: http://stackoverflow.com/q/46806947

http://stackoverflow.com/comment/80473805
type: QuestionComment
has text: Nope, there isn't any.
comment on: http://stackoverflow.com/q/46764211
score: 0
type: Comment

http://stackoverflow.com/comment/80674306
score: 0
type: Comment
type: QuestionComment
has text: I can't reproduce the error. I only replaced the image and the `settings` stuff and it works correctly for me. Please add the relevant variables from the `settings` module as well. Perhaps something is wrong with the image. Do you get any error messages?
comment on: http://stackoverflow.com/q/46863143

http://stackoverflow.com/q/46789023
tagged with: python
possible better answer: http://stackoverflow.com/a/46792381
has answer: http://stackoverflow.com/a/46792381
type: AnsweredQuestion
score: 1
has body: I've fetched the data from CSV file which contains data from 1981 to 1999 but I want to fetch the data from 1981 to 1992, but i don't know how to implement between query in a dataframe. Here are some of my code..... CSV File Link Python Pandas Code col_names = ['Country','Cause','Deaths1','Sex','Year'] return_data=pd.read_csv("test.csv",low_memory=False,usecols=col_names); temp_return=return_data[return_data['Country']==4184].groupby('Cause').max() efg=temp_return.iloc[1:21] returnCount=efg[efg.columns.difference(['Sex','Country','Year'])] returnCount The upper code fetched all years data... help me to solve the problem
type: Question
has title: How to display all the data which is groupby "Cause" from 1981 to 1992 in python pandas?
has answer: http://stackoverflow.com/a/46790171
accepted answer: http://stackoverflow.com/a/46790171
upvote count: 2
answer count: 2
tagged with: pandas
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv

pymc3
tags question: http://stackoverflow.com/q/46835123
type: Tag
tag name: pymc3

http://stackoverflow.com/q/46844231
favorite count: 0
has body: With Python 3, I want to read an XML web page and save it in my local drive. Also, if the file already exist, it must overwrite it. I tested some script like : import urllib.request xml = urllib.request.urlopen('URL') data = xml.read() file = open("file.xml","wb") file.writelines(data) file.close() But I have an error : TypeError: a bytes-like object is required, not 'int'
tagged with: python
accepted answer: http://stackoverflow.com/a/46844517
type: AnsweredQuestion
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/46844471
has answer: http://stackoverflow.com/a/46844517
has title: Open an XML file through URL and save it
has answer: http://stackoverflow.com/a/46844471
type: Question
has comment: http://stackoverflow.com/comment/80636372
tagged with: python-3.6
upvote count: 2
answer count: 2

http://stackoverflow.com/a/46791750
type: Answer
downvote count: 0
has body: This is basically a duplicate of String comparison in Python: is vs. == You just didnt know it. == and is check two different things. == asks are these two thing the same value. is asks are these two things the same thing i.e. the same object. a[:] copies the list creating a new list with the same value. thus a == a[:] &gt;&gt; True a is a[:] &gt;&gt; False
score: 2
answers question: http://stackoverflow.com/q/46791642
upvote count: 2

http://stackoverflow.com/comment/80531730
score: 2
has text: Is the existing database configured to auto-assign the primary key?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46789423

http://stackoverflow.com/q/46839761
favorite count: 0
tagged with: kafka-producer-api
tagged with: python
has answer: http://stackoverflow.com/a/46843145
accepted answer: http://stackoverflow.com/a/46843145
type: AnsweredQuestion
downvote count: 0
score: 1
has title: confluent-python kafka producer send callback message.offset() returns 0
linked to: http://stackoverflow.com/q/44732214
type: Question
tagged with: apache-kafka
has body: The Producer.send callback provides a message object. message.offset() often returns 0 in what seems to be a bug. This is using: confluent-kafka python library version 0.11.0 librdkafka: stable 0.11.0 (bottled), HEAD. Installed via Mac OS Homebrew The following simple test program: import confluent_kafka import timeit def delivery_callback(error, message): print("delivery_callback. error={}. message={}".format(error, message)) print("message.topic={}".format(message.topic())) print("message.timestamp={}".format(message.timestamp())) print("message.key={}".format(message.key())) print("message.value={}".format(message.value())) print("message.partition={}".format(message.partition())) print("message.offset={}".format(message.offset())) def produce_string_messages(kafka_producer, topic_name, num_messages): start_time = timeit.default_timer() for i in range(num_messages): kafka_producer.produce(topic_name, value="cf-k test. v{}".format(i), on_delivery=delivery_callback) elapsed = timeit.default_timer() - start_time print("completed producing messages. They are queued for delivery. elapsed={}. elapsed/msg={}".format(elapsed, elapsed / num_messages)) if __name__ == "__main__": print("starting") conf = { 'bootstrap.servers': "kafka-broker-1:9092" } kafka_producer = confluent_kafka.Producer(conf) print("opened KafkaProducer") produce_string_messages(kafka_producer, "my-string-topic", 3) print("flushing...") kafka_producer.flush() print("exiting") produces: starting opened KafkaProducer completed producing messages. They are queued for delivery. elapsed=0.000994920730591. elapsed/msg=0.00033164024353 flushing... delivery_callback. error=None. message=&lt;cimpl.Message object at 0x10f986ec0&gt; message.topic=my-string-topic message.timestamp=(1, 1508451238822L) message.key=None message.value=cf-k test. v0 message.partition=0 message.offset=0 delivery_callback. error=None. message=&lt;cimpl.Message object at 0x10f986ec0&gt; message.topic=my-string-topic message.timestamp=(1, …
upvote count: 1
answer count: 1

http://stackoverflow.com/a/46845843
has comment: http://stackoverflow.com/comment/80639255
answers question: http://stackoverflow.com/q/46845807
type: Answer
upvote count: 1
has body: You can use shift i.e s = pd.Series([1,1,1,0,2,3,2,4,2]) mask = (s == s.shift().bfill()) or Thanks @Zero mask = s.diff().bfill().eq(0) print tuple(mask) (True, True, True, False, False, False, False, False, False) In case you have sequence at the end comparing two masks would be helpful i.e n = pd.Series([1,1,1,0,2,3,2,4,2,2]) mask = (n==n.shift(-1).ffill()) | (n==n.shift().bfill()) tuple(mask) (True, True, True, False, False, False, False, False, True, True)
score: 1
has comment: http://stackoverflow.com/comment/80678615
has comment: http://stackoverflow.com/comment/80678603
downvote count: 0

http://stackoverflow.com/a/75872031
upvote count: 1
score: 1
downvote count: 0
has body: Make sure you cd back into the repo file after creating your virtual environment to store project. In my case, I created, cd into the folder, then forgot to cd back into the repo file. I struggled with all the options of solutions I found here till I carefully looked at my commands and had to cd back. That way I install requirements.txt still using this: pip install -r requirements.txt
answers question: http://stackoverflow.com/q/46854451
type: Answer

http://stackoverflow.com/a/69290201
answers question: http://stackoverflow.com/q/46819590
score: 0
has body: The rest of the answers all miss something. Either using the Prefix parameter, or deleting delete markers, or handling errors... s3 = boto3.client('s3') response = s3.list_object_versions(Bucket=bucket_name, Prefix=key) objects_to_delete = [] # Note that we do not use pagination because we assume the file has less than max versions (something like 300) # Note that we also traverse delete markers. for obj in itertools.chain(response.get("Versions", []), response.get("DeleteMarkers", [])): # NOTE: This is super stupid, but AWS has no API for list_object_versions for a single object, only with prefix. # So other objects who share the same prefix (e.g "blaze/a.txt" and "bla.json" will also be listed when asking for "bla"). # So we need to be careful here if obj["Key"] != key: break objects_to_delete.append({"Key": obj["Key"], 'VersionId': obj['VersionId']}) if len(objects_to_delete) == 0: raise FileNotFoundError(f'File {key} not found at bucket {bucket_name}') deletion_response = s3.delete_objects(Bucket=bucket_name, Delete={"Objects": objects_to_delete, "Quiet": False}) errors = deletion_response.get("Errors", []) if len(errors) > 0: raise Exception(f'Failed deleting file {key} from bucket {bucket_name}. Result: {deletion_response}')
type: Answer

http://stackoverflow.com/q/46790177
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46800854
type: Question
tagged with: chilkat
score: 0
has title: Upload zip files to a SFTP server using chilkat python
tagged with: sftp
answer count: 1
has body: I am using the following script to upload a zip file on a SFTP server. Though I see the file on server, but it always shows that it's 0 Kb #Code to upload file to a SFTP server abc.com import chilkat sftp = chilkat.CkSFtp() success = sftp.UnlockComponent("Anything trial") puttyKey = chilkat.CkSshKey() ppkText = puttyKey.loadText("xyz.ppk") success = puttyKey.FromPuttyPrivateKey(ppkText) sshHostname = "abc.com" sshPort = 22 success = sftp.Connect(sshHostname,sshPort) sftp.AuthenticatePwPk("username", "password", puttyKey) success = sftp.InitializeSftp() filename = "file.zip" handle = sftp.openFile(filename ,"writeOnly","createTruncate") success = sftp.UploadFile(handle,"file.zip") success = sftp.CloseHandle(handle)

http://stackoverflow.com/q/46827696
tagged with: python
type: UnansweredQuestion
has body: I have developed a python script to subscribe a WebSocket and retrieve the output stream. The output is position bus with X / Y info and the output is a json. This a snippet of code: websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://xxxxxx/subscribe", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) Now I would like to show this real-time data into a web map as Leaflet. Or another framework. I can do this? Any idea or example? Thanks
tagged with: leaflet
has title: Python output websocket on Map
linked to: http://stackoverflow.com/q/28570930
type: Question
answer count: 1
tagged with: websocket
score: 0
has answer: http://stackoverflow.com/a/46827809

http://stackoverflow.com/a/46749096
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/46748976
upvote count: 0
has body: There are several ways to do that, but here is one trivial solution that counts the number of instances of a word, but do not take e.g. punctation into account: from collections import Counter s = "This is true. This is false." c = Counter(s.split(' ')) print(c['This']) # Prints "2"
type: Answer

http://stackoverflow.com/a/52289152
score: 2
upvote count: 2
has body: To round the column values to the nearest integer, you can group on a list comprehension that rounds each column (barring the first which is TimeStamp) to the nearest whole number and then takes the integer: &gt;&gt;&gt; (df .set_index('TimeStamp') .groupby([int(round(col, 0)) for col in df.columns[1:].astype(float)], axis=1) .mean()) 382 383 384 TimeStamp 10:28:00 0.012405 0.012448 0.012362 10:30:00 0.012405 0.012414 0.012431 10:32:00 0.055138 0.055931 0.056310 10:34:00 0.055655 0.056655 0.056948 10:36:00 0.055681 0.056810 0.057362
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46760083

http://stackoverflow.com/q/46759911
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80465402
tagged with: list
has comment: http://stackoverflow.com/comment/80465306
has answer: http://stackoverflow.com/a/46760262
has comment: http://stackoverflow.com/comment/80465315
has answer: http://stackoverflow.com/a/46760196
type: Question
has comment: http://stackoverflow.com/comment/80465304
has title: Finding max and min indices in lists in Python
accepted answer: http://stackoverflow.com/a/46760262
has comment: http://stackoverflow.com/comment/80465323
score: 0
has comment: http://stackoverflow.com/comment/80465337
answer count: 3
has comment: http://stackoverflow.com/comment/80465246
tagged with: max
possible better answer: http://stackoverflow.com/a/46759953
has comment: http://stackoverflow.com/comment/80465363
has body: I have a list that looks like: trial_lst = [0.5, 3, 6, 40, 90, 130.8, 129, 111, 8, 9, 0.01, 9, 40, 90, 130.1, 112, 108, 90, 77, 68, 0.9, 8, 40, 90, 92, 130.4] The list represents a series of experiments, each with a minimum and a maximum index. For example, in the list above, the minimum and maximum would be as follows: Experiment 1: Min: 0.5 Max: 130.8 Experiment 2: Min: 0.01 Max: 130.1 Experiment 3: Min: 0.9 Max: 103.4 I obtained the values for each experiment above because I know that each experiment starts at around zero (such as 0.4, 0.001, 0.009, etc.) and ends at around 130 (130, 131.2, 130.009, etc.). You can imagine a nozzle turning on and off. When it turns on, the pressure rises and as it's turned off, the pressure dips. I am trying to calculate the minimum and maximum values for each experiment. What I've tried so far is iterating through the list to first mark each index as max, but I can't seem to get that right. Here is my code. Any suggestions on how I can change it? for idx, item in enumerate(trial_lst): if idx &gt; 0: prev = trial_lst[idx-1] curr = item if prev &gt; curr: result.append((curr, "max")) else: result.append((curr, "")) I am looking for a manual way to do this, no libraries.
has answer: http://stackoverflow.com/a/46759953

http://stackoverflow.com/q/46813151
score: 2
has comment: http://stackoverflow.com/comment/80574421
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80573658
has comment: http://stackoverflow.com/comment/80573938
type: Question
tagged with: numpy
has body: Hi I am trying to generate a list of elements q by using below mentioned code. newlist=[] coords=pn['point.coords'][z&gt;=0.001950] points=range(27000) for q in points: if pn['point.coords'][q] in coords: newlist.append(q) Here pn['point.coords'] is a list of x ,y ,z coordinates of points and I want to make a new list of those points in which z&gt;= 0.001950. Total limit of x,y,z is from 0 to 0.002. Code is running slow. Is there any faster way to get this new list?
has comment: http://stackoverflow.com/comment/80573865
has title: Any suggestion to generate newlist.append(q) list faster than current method?
downvote count: 0
has comment: http://stackoverflow.com/comment/80573817
upvote count: 2
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/80574624
has comment: http://stackoverflow.com/comment/80573972
has comment: http://stackoverflow.com/comment/80573458
has comment: http://stackoverflow.com/comment/80573403
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46815037
accepted answer: http://stackoverflow.com/a/46815037
tagged with: python

http://stackoverflow.com/q/46815115
upvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/46815244
tagged with: python
has answer: http://stackoverflow.com/a/46815244
score: -1
has body: I am new to python and programming in general. I was trying to encode and decode a message, but this mistake occurs. What does it mean? How to fix it? Def main(): Mes=input(" enter the message to encode"). Key= int(input(" enter the key"). Print(chr(ord(chr)+key) for chr in mes) main()
has answer: http://stackoverflow.com/a/46815161
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/80578118
accepted answer: http://stackoverflow.com/a/46815161
has title: Str object is not callable. Encode and decode message
has comment: http://stackoverflow.com/comment/80577625
has comment: http://stackoverflow.com/comment/80577881
has comment: http://stackoverflow.com/comment/80578011
type: AnsweredQuestion

http://stackoverflow.com/q/46771727
tagged with: dataframe
has answer: http://stackoverflow.com/a/46772486
type: Question
accepted answer: http://stackoverflow.com/a/46771772
possible better answer: http://stackoverflow.com/a/46771786
has answer: http://stackoverflow.com/a/46771786
answer count: 3
tagged with: pandas
has title: Insert index in Dataframe
tagged with: python
has body: This is my dataframe df : df = pd.DataFrame({'a': [0.671399,0.446172,0.614758], 'b' : [ 0.101208 ,-0.243316 ,0.075793], 'c':[-0.181532 ,0.051767, -0.451460]}) a b c 0 0.671399 0.101208 -0.181532 1 0.446172 -0.243316 0.051767 2 0.614758 0.075793 -0.451460 I wanted to add 1 more column with more index so I tried this: df['e'] = pd.Series(data = [-0.335485, -1.166658, -0.385571,-1.166658 ],index=[0,1,2,3]) But the result is not adding index = 3 row. a b c e 0 0.671399 0.101208 -0.181532 -0.335485 1 0.446172 -0.243316 0.051767 -1.166658 2 0.614758 0.075793 -0.451460 -0.385571
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/46771772
downvote count: 1
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/80709412
comment on: http://stackoverflow.com/q/46880968
score: 0
type: Comment
type: QuestionComment
has text: @Shadow: you were the first to respond - please write an answer so that I can accept it.

http://stackoverflow.com/comment/80691080
score: 0
has text: add your example to the post please
comment on: http://stackoverflow.com/q/46871958
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80830068
has text: the code above reads in the file correctly. "open(r"C:\pyscripts\1.csv") as in_file" opens a second file object for reading the input file
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46857992
type: Comment

http://stackoverflow.com/a/46795687
has body: there are functions for converting 24h to 12h time : Load the string into a datetime object via strptime(), then dump via strftime() in the desired format: from datetime import datetime d = datetime.now().strftime("%Y-%m-%d %H:%M:%S") d # d is a string '2016-04-28 07:46:32' datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S %p") '2016-04-28 07:46:32 AM' Note that the %I here is a 12-hour clock Conversion of 24 hours date/time to 12 hours format and vice-versa if you want to use your solution you can add leading zeros to integrs like in How to add Trailing zeroes to an integer : numbers = [1, 19, 255] numbers = [int('{:&lt;03}'.format(number)) for number in numbers] you can print leading zeros like in Display number with leading zeros
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46795601

http://stackoverflow.com/q/46823662
tagged with: iteration
has body: I usually do this: [worker.do_work() for worker in workers] This has the advantage of being very readable and contained in a single line, but the problem of creating an object (a list) which I do not need, which means garbage collection is unnecessarily triggered. The obvious alternative: for worker in workers: worker.do_work() Is also quite readable, but uses two lines. Is there a single-line way of achieving the same result, without creating unnecessary objects?
favorite count: 0
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/80594666
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80594627
tagged with: loops
has comment: http://stackoverflow.com/comment/80595503
type: Question
possible better answer: http://stackoverflow.com/a/46823720
has comment: http://stackoverflow.com/comment/80594655
has comment: http://stackoverflow.com/comment/80594953
has answer: http://stackoverflow.com/a/46823752
accepted answer: http://stackoverflow.com/a/46823752
has answer: http://stackoverflow.com/a/46823720
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/80594824
answer count: 2
has title: Walk a list without creating unneeded object
downvote count: 3
has comment: http://stackoverflow.com/comment/80594679

http://stackoverflow.com/comment/80694116
type: Comment
type: QuestionComment
has text: It might help to see the script(s) causing the error.
comment on: http://stackoverflow.com/q/46873532
score: 0

http://stackoverflow.com/comment/82843789
score: 0
type: Comment
has text: why does dot.toLocalMatrix().toArray() produce 4 x 4 array size instead of 3 x 3 as there are three labels (1,2,3)?
type: AnswerComment
comment on: http://stackoverflow.com/a/46764347

http://stackoverflow.com/q/46784908
type: UnansweredQuestion
tagged with: python
has body: I try to run a dockerized pants build for a scala project and it fails with an error message "error in cryptography setup command: Invalid environment marker: python_version &lt; '3' ". I haven't manually specified anything to install cryptography. In the documentation of cryptography I could see that it happens either because of pip or setuptools is out of date. I tried to update this as well. But in case of pants I'm not very sure where should I specify this also. I specified this in pants file and in thidparty "requirements.txt" file. But no difference . It was working fine but suddenly it failed one day. I use the following versions of Ubuntu -14.04 python -2.7.4 pants -1.0.0 (tried upgrading to 1.1.0 but no difference)
score: 0
has title: Fails to install cryptography when a pants build is run
type: Question
tagged with: pants
has comment: http://stackoverflow.com/comment/80518611
has comment: http://stackoverflow.com/comment/80520103
has comment: http://stackoverflow.com/comment/80520809
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80516154
answer count: 1
has answer: http://stackoverflow.com/a/47027841

http://stackoverflow.com/a/46842536
type: Answer
accepted answer of: http://stackoverflow.com/q/46842508
upvote count: 2
has comment: http://stackoverflow.com/comment/80633652
has comment: http://stackoverflow.com/comment/80633045
has comment: http://stackoverflow.com/comment/80632971
has comment: http://stackoverflow.com/comment/80632786
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You're looking for: data['Raw'] = pd.to_datetime(data['Raw']) Raw is a column, and data['Raw'] returns a series, you want to work with that (not its index). Once you're done with that, I'd recommend interpolation with df.resample: data = data.set_index('Raw').resample('1min').mean() If you still want to use interpolate, you could use .agg(interpolate) instead. Since you want to retain the original Raw column, you could instead use: data = data.assign(RawDt=pd.to_datetime(data.Raw))\ .groupby(pd.Grouper(key='RawDt', freq='1min'))\ .agg({'DataValue' : 'mean', 'Raw' : 'first'}).reset_index(drop=True)
has comment: http://stackoverflow.com/comment/80633557
answers question: http://stackoverflow.com/q/46842508
has comment: http://stackoverflow.com/comment/80632765

http://stackoverflow.com/q/46778824
tagged with: gmail
has comment: http://stackoverflow.com/comment/80541045
has comment: http://stackoverflow.com/comment/80828175
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80541027
tagged with: imaplib
has comment: http://stackoverflow.com/comment/80504370
has comment: http://stackoverflow.com/comment/80546551
type: Question
has title: Getting a Gmail email as a string - also how do I obtain an image from the email
tagged with: email-attachments
has body: I have retrieved the body of an email in Gmail using the following code. I now want to search it and pick out certain parts of the body text using something similar to the find command you use on strings. E.G. DVRName = email_message[email_message.find("ALARM NAME(NUM):" +1:email_message.find("Report")-1] When I try this it produces an error: AttributeError: 'Message' object has no attribute 'find' I assume this is because either I am using find incorrectly or the email data is not a string? This code produces the email along with a lot of garbled code. import imaplib import datetime from datetime import timezone from email.parser import HeaderParser timezone = ('gmt') mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('f*****m', 'f******3') mail.list() # Out: list of "folders" aka labels in gmail. mail.select("inbox") # connect to inbox. result, data = mail.search(None, "All") ids = data[0] # data is a list. id_list = ids.split() # ids is a space separated string latest_email_id = id_list[-1] # get the latest # fetch the email body (RFC822) for the given ID result, data = mail.fetch(latest_email_id, ("(UID BODY[TEXT])")) raw_email = data[0][1] # here's the body, which is raw text of the whole email # including headers and alternate payloads raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) print (email_message) One more thing can I retrieve the Subject, date etc separately?
tagged with: email
tagged with: python
has comment: http://stackoverflow.com/comment/80542412

http://stackoverflow.com/q/46848343
tagged with: python
tagged with: python-3.x
has body: I am working with Python "Pattern.en" package that gives me the subject, object and other details about a particular sentence. But I want to store this output into another variable or a Dataframe for further processing which I am not able to do so. Any inputs on this will be helpful. Sample code is mentioned below for reference. from pattern.en import parse from pattern.en import pprint import pandas as pd input = parse('I want to go to the Restaurant as I am hungry very much') print(input) I/PRP/B-NP/O want/VBP/B-VP/O to/TO/I-VP/O go/VB/I-VP/O to/TO/O/O the/DT/B-NP/O Restaurant/NNP/I-NP/O as/IN/B-PP/B-PNP I/PRP/B-NP/I-PNP am/VBP/B-VP/O hungry/JJ/B-ADJP/O very/RB/I-ADJP/O much/JJ/I-ADJP/O pprint(input) WORD TAG CHUNK ROLE ID PNP LEMMA I PRP NP - - - - want VBP VP - - - - to TO VP ^ - - - - go VB VP ^ - - - - to TO - - - - - the DT NP - - - - Restaurant NNP NP ^ - - - - as IN PP - - PNP - I PRP NP - - PNP - am VBP VP - - - - hungry JJ ADJP - - - - very RB ADJP ^ - - - - much JJ ADJP ^ - - - - Please note the output of both print and pprint statements. I am trying to store either one of them into a variable. It would be better if I can store the output of pprint statement into a Dataframe as it is printing in tabular format. But when I try to do so I encounter the error mentioned below df = pd.DataFrame(input) ValueError: DataFrame constructor not properly called!
has comment: http://stackoverflow.com/comment/80644555
score: -3
downvote count: 3
has answer: http://stackoverflow.com/a/46850965
type: AnsweredQuestion
has title: Pattern table to Pandas DataFrame
tagged with: linguistics
type: Question
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46850965
favorite count: 0
has comment: http://stackoverflow.com/comment/80645942
tagged with: pandas

http://stackoverflow.com/a/46798352
has body: There's nothing wrong with pd.to_datetime. It's possible you have erroneous dates. Try specifying a format, and errors='coerce so invalid formats are converted to NaT. df['Bed Census Date'] = pd.to_datetime(df['Bed Census Date'].str.strip(), format='%Y-%m-%d', errors='coerce') Now, expanding on my comment, filter, sort, and get the first 10 items using head: x = df[df['Facility ID'] == facility_id]\ .sort_values('Available Residential Beds', ascending=False).head(10) return x['Bed Census Date']
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46797259
answers question: http://stackoverflow.com/q/46797259
score: 1

http://stackoverflow.com/a/46780886
accepted answer of: http://stackoverflow.com/q/46780638
answers question: http://stackoverflow.com/q/46780638
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: unwrap does a proper SSL shutdown. Such shutdown is similar to the FIN handshake at the end of the TCP connection, only at the SSL/TLS layer. How this shutdown is done in C depends on the specific SSL/TLS stack you are using. But for OpenSSL the function you need to use is SSL_shutdown.

typeerror
tags question: http://stackoverflow.com/q/46757531
tags question: http://stackoverflow.com/q/46859609
tags question: http://stackoverflow.com/q/46748983
tag name: typeerror
tags question: http://stackoverflow.com/q/46760966
tags question: http://stackoverflow.com/q/46752283
type: Tag
tags question: http://stackoverflow.com/q/46834364

http://stackoverflow.com/a/46858289
has comment: http://stackoverflow.com/comment/80664301
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46858276
has comment: http://stackoverflow.com/comment/80664249
answers question: http://stackoverflow.com/q/46858276
type: Answer
has comment: http://stackoverflow.com/comment/80664234
downvote count: 0
has body: Python's much loved EAFP approach with exception handling would be my way of doing it. try: print(ar[i][j]) # i -&gt; row index, j -&gt; col index except IndexError: print('Error!') Another way, also known as the LYBL approach, would be using if checks: if i &lt; len(ar) and j &lt; len(ar[i]): print(ar[i][j]) And here's the "one liner" version (that kills readability, but you seem to want): print(ar[i][j] if i &lt; len(ar) and j &lt; len(ar[i]) else "Error") What is the EAFP principle in Python? LBYL vs EAFP in Java? (the same concept applies to almost any language.)
score: 7
has comment: http://stackoverflow.com/comment/80664209

http://stackoverflow.com/q/46836555
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80620885
score: 5
tagged with: python
answer count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/80620821
has title: Why there are __version__ strings in some modules of Python standard library?
has answer: http://stackoverflow.com/a/46837183
downvote count: 1
has body: By accident I noticed that both csv and re modules of python standard library have their .__version__ attribute: &gt;&gt;&gt; import re, csv &gt;&gt;&gt; re.__version__ '2.2.1' &gt;&gt;&gt; csv.__version__ '1.0' It surprises me as they are part of the standard library, so I would expect their version to be defined by sys.version (and sys.version_info). I have noticed the values of the attributes are same for both Python 2.7.13 and 3.6.1, despite the modules have changed. Are they just a kind of "code fossils" or are they somehow meaningful and programmers should pay attention to their values?
type: UnansweredQuestion
tagged with: python-2.7
type: Question
has comment: http://stackoverflow.com/comment/80620902
tagged with: version
tagged with: standard-library
has comment: http://stackoverflow.com/comment/80620720
favorite count: 0

http://stackoverflow.com/q/46834439
answer count: 2
has title: Processing one column text by index to several new columns based on specific word in text
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46835010
has body: I have a problem with pandas code and after trying to search for an answer for hours and hours I finally gave up and came here for help! My dataframe, which is created from larger excel file, consist of specific observations that are at the same time defined as the index. Now I have one column where these observations have provided text answers, and most of these observations have provided several responses. Here is an example of my output. Org Data1 x aaa x aaa x bbb y aaa z ccc z ddd z ddd What I want to achieve is this: Org One Two Three Four x 1 1 0 0 y 1 0 0 0 z 0 0 1 1 Data1 column is deleted and new columns correspond text answers like this: "One" = aaa, "Two" = bbb, "Three" = ccc, and "Four" = ddd. The idea is to group everything together by the index "Org", and create new columns based on the "Data1" columns answers. So in example as the "Org" x has responded in "Data1" to aaa twice and bbb once, the code would create a new column "One" and "Two" and with true or false function place either 1 or 0 to this new column. The idea is also to ignore responses that have been given more than once, but I guess with true or false function this is not an issue and there is no need to drop duplicates (?). Note that the answers are not in any specific order and in total I have about 10000 rows, I use loc to select specific "Org":s already, which I am interested in. This is what I have tried so far: df = pd.read_excel("location\test.xlsx", sheetname="Sheet1", index_col="Org").loc[["x", "y", "z"], ["Data1"]] df["One"] = np.where(df["Data1"].str.contains["aaa"], "1", "0") By also doing df["Two"], df["Three"] etc. and finally deleting the Data1 column, and processing the results further by using groupby and sum I am able to get to my final result. However then I have columns with "2" or "3" instead of the "1", which I am looking for. Obviously this is not a huge task to process further but I have been trying to come up with a better solution than groupby and sum, since it w…
tagged with: python
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46834926
type: Question
accepted answer: http://stackoverflow.com/a/46834926
has answer: http://stackoverflow.com/a/46835010
score: 0

http://stackoverflow.com/a/46774304
answers question: http://stackoverflow.com/q/46774105
has comment: http://stackoverflow.com/comment/80494668
has comment: http://stackoverflow.com/comment/80498129
score: 0
has comment: http://stackoverflow.com/comment/80495062
type: Answer
has comment: http://stackoverflow.com/comment/80494575
has body: Not sure I understand what you are trying to achieve, as your example input does not really match your output, but I think you can just use a list comprehension to construct the result, checking whether those items are in the years, months and weeks lists, and adding a 1 or 0 respectively: &gt;&gt;&gt; year = (('Fanklin Grand Isle', '5560', 1), ('Windham', '3457', 1)) &gt;&gt;&gt; month = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1)) &gt;&gt;&gt; week = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1)) &gt;&gt;&gt; [(x[0], x[1], int(x in year), int(x in month), int(x in week)) for x in set(year + week + month)] [('Chittendon', '3367', 0, 1, 1), ('Windham', '3457', 1, 0, 0), ('Fanklin Grand Isle', '5560', 1, 1, 1)] If those counts can actually be different from 1, you should first create a few dictionaries mapping the cities to their respective year/month/week counts, and then use a similar list comprehension as above: &gt;&gt;&gt; year_counts = {(name, code): count for (name, code, count) in year} &gt;&gt;&gt; month_counts = {(name, code): count for (name, code, count) in month} &gt;&gt;&gt; week_counts = {(name, code): count for (name, code, count) in week} &gt;&gt;&gt; all_cities = [(name, code) for (name, code, count) in set(year + month + week)] &gt;&gt;&gt; [(x[0], x[1], year_counts.get(x, 0), month_counts.get(x, 0), week_counts.get(x, 0)) for x in all_cities] [('Chittendon', '3367', 0, 1, 1), ('Windham', '3457', 1, 0, 0), ('Fanklin Grand Isle', '5560', 1, 1, 1)]
has comment: http://stackoverflow.com/comment/80495027
has comment: http://stackoverflow.com/comment/80494806
has comment: http://stackoverflow.com/comment/80494395
has comment: http://stackoverflow.com/comment/80494507
has comment: http://stackoverflow.com/comment/80494486

http://stackoverflow.com/q/46811416
has comment: http://stackoverflow.com/comment/80570067
tagged with: bokeh
type: Question
has title: Python: using dictionary as input with bokeh library
score: 0
tagged with: pandas
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50735807
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80578932
has body: Context Say I have a dictionary: d = {‘2012': [50, 62], '2013': [53, 55], '2014': [51,52]...}, ... where keys are years and values are lists of values (eg. [female employees, male employees]). Question How can a stacked bar chart (with years on x-axis) with bokeh be created using this dictionary? Or - how else could this data be used to make this possible?

http://stackoverflow.com/a/46922307
accepted answer of: http://stackoverflow.com/q/46870809
answers question: http://stackoverflow.com/q/46870809
has body: Try this: SITE_ROOT = app.root_path json_data = open(os.path.join(SITE_ROOT, "static", "getinfo.json"), "r") Whether this works or not, figure out where the debugger is in your IDE and set a breakpoint on that line, so that you can follow the object's state and identify where the breakdown is. Once you have that specific info, much easier to post it and get an answer on here.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/46905576
has comment: http://stackoverflow.com/comment/80758852
has comment: http://stackoverflow.com/comment/80759162
type: Question
has comment: http://stackoverflow.com/comment/80758171
has comment: http://stackoverflow.com/comment/80758109
has comment: http://stackoverflow.com/comment/80759186
tagged with: dataframe
has body: I have a dataframe indexed by datetime. I want to filter out rows based on the difference between their index and the index of the previous row. So, if my criteria is "remove all rows that are over one hour late than the previous row", the second row in the example below should be removed: 2005-07-15 17:00:00 2005-07-17 18:00:00 While in the following case, both rows stay: 2005-07-17 23:00:00 2005-07-18 00:00:00
accepted answer: http://stackoverflow.com/a/46906115
has comment: http://stackoverflow.com/comment/80758212
has comment: http://stackoverflow.com/comment/80758921
tagged with: pandas
downvote count: 0
answer count: 1
has title: Filtering pandas dataframe by difference of adjacent rows
favorite count: 0
tagged with: python-3.x
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46906115
upvote count: 3
has comment: http://stackoverflow.com/comment/80758742

http://stackoverflow.com/comment/80506002
type: Comment
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/46779898
has text: It's likely that your text editor silently does the right thing and encodes your file as UTF-8, because it's clever enough to figure out what `# coding: utf-8` means in a Python file. Take a hex editor and look at the actual bytes in the file.

http://stackoverflow.com/a/46898989
type: Answer
accepted answer of: http://stackoverflow.com/q/46898464
upvote count: 1
score: 1
has body: looks like you need to add empty order_by() by the default-ordering-or-order-by in the result query can be added extra fields to the group by. try it: Market.objects.values('slug').annotate(Max('active')).order_by()
answers question: http://stackoverflow.com/q/46898464
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46819070
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/46819477
has body: Hey guys I am new to python I’m in year 11 so I’m still learning I wrote a code that loops the questions of asking what the useres name is their age and year group and then prints out a username containing their first 3 letters of their name and their year group then age ? I was wondering how I could write all of these usernames into a file I use a for loop to repeat the question 5 times to ask 5 different users and now I want to know how to store their user names into a file I know how to store an input but not this type of problem
has comment: http://stackoverflow.com/comment/80586458
type: UnansweredQuestion
score: -3
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80585548
type: Question
has comment: http://stackoverflow.com/comment/80585656
tagged with: python
has title: Writing a loop to a file

http://stackoverflow.com/q/46761357
has comment: http://stackoverflow.com/comment/80469258
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80468380
has comment: http://stackoverflow.com/comment/80468364
score: 2
has comment: http://stackoverflow.com/comment/80468760
has comment: http://stackoverflow.com/comment/80468320
has comment: http://stackoverflow.com/comment/80468381
upvote count: 2
has answer: http://stackoverflow.com/a/46764031
type: Question
has comment: http://stackoverflow.com/comment/80469238
has comment: http://stackoverflow.com/comment/80468299
has comment: http://stackoverflow.com/comment/80468459
has body: How can I do factorial based on the multiply function? Thats what I have and the problem I'm running into is it gives me 0 instead of 5 != 120. EDIT NEWEEST: how can I fix the double factorial to give me the right number? if I do 5, it should give me 5!!= 15 but it gives me 12 why is that? SOURCE CODE def multiply(num1,num2): sum_of_multiplication= 0 for i in range(num2): sum_of_multiplication = add(sum_of_multiplication,num1) return sum_of_multiplication def factorial(num1): factorial_num = num1 for i in range(1,num1): num1 = multiply(factorial_num,num1) print(factorial_num) print(str(num1) + "!= " + str(factorial_num)) def double_factorial(num1): double_factorial_num = 2 for i in range(1,num1-2): double_factorial_num = multiply(double_factorial_num, i) print(double_factorial_num) print(str(num1) + "!!= " + str(double_factorial_num)) double_factorial = double_factorial(int(input("please enter your intger:")))
answer count: 2
has answer: http://stackoverflow.com/a/46761367
has comment: http://stackoverflow.com/comment/80469366
downvote count: 0
has comment: http://stackoverflow.com/comment/80470402
has comment: http://stackoverflow.com/comment/80469253
favorite count: 0
tagged with: python-3.x
has title: How to do factorial using multiplication based on another function that has two parameters

http://stackoverflow.com/q/46853629
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 9
has comment: http://stackoverflow.com/comment/80655597
has answer: http://stackoverflow.com/a/46854081
accepted answer: http://stackoverflow.com/a/46854081
has body: I've looked around for a little while now and can't seem to find anything that even touches on the differences. As the title states, I'm trying to find out what difference getting your data via url path parameters like /content/7 then using regex in your urls.py, and getting them from query params like /content?num=7 using request.GET.get() actually makes. What are the pros and cons of each, and are there any scenarios where one would clearly be a better choice than the other? Also, from what I can tell, the (Django's) preferred method seems to be using url path params with regex. Is there any reason for this, other than potentially cleaner URLs? Any additional information pertinent to the topic is welcome.
has title: URL path parameters vs query parameters in Django
answer count: 1
favorite count: 0
upvote count: 9

http://stackoverflow.com/q/46769705
has title: Doc2Vec from gensim to deeplearning4j
favorite count: 0
has comment: http://stackoverflow.com/comment/88067132
tagged with: deeplearning4j
tagged with: python
tagged with: gensim
score: 2
downvote count: 0
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: java
upvote count: 2
has body: Is there any way to load doc2vec model saved using gensim into deeplearning4j's ParagraphVectors? My gensim model is valid - I am able to load it using gensim with no problems. When I call WordVectorSerializer.readParagraphVectors on my model from Java it throws exception: Exception in thread "main" java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:219) at java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:149) at java.util.zip.ZipFile.&lt;init&gt;(ZipFile.java:163) at org.deeplearning4j.models.embeddings.loader.WordVectorSerializer.readWord2Vec(WordVectorSerializer.java:889) at org.deeplearning4j.models.embeddings.loader.WordVectorSerializer.readParagraphVectors(WordVectorSerializer.java:825) at pl.org.opi.main.main(main.java:17) Upon debugging the code, I noticed that deeplearning4j expects a zip file with multiple txt files and a single json file inside of it. Is there a way to convert the gensim model to the zip expected by deeplearning4j or is there a dedicated method for this in dl4j API (couldn't find any using examples and javadoc)?
tagged with: doc2vec

http://stackoverflow.com/a/46790955
answers question: http://stackoverflow.com/q/46790718
has comment: http://stackoverflow.com/comment/80562907
has comment: http://stackoverflow.com/comment/80563454
score: 1
has comment: http://stackoverflow.com/comment/80534361
has comment: http://stackoverflow.com/comment/80555236
accepted answer of: http://stackoverflow.com/q/46790718
has comment: http://stackoverflow.com/comment/80562449
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80531731
has comment: http://stackoverflow.com/comment/80563669
type: Answer
has comment: http://stackoverflow.com/comment/80564060
has body: list(zip()) allows to traspose a set of sequences: time = [100, 1] y1 = [110, 2] l = list(zip(time, y1)) print(l) # [(100, 110), (1, 2)] time = l[0] # (100, 110) y1 = l[1] # (1, 2) They are tuples that you can use as lists or you can transform them to lists: time = list(l[0]) # [100, 110] y1 = list(l[1]) # [1, 2] If you want to get them straight into the opposite form you could swap the reading part: import csv import matplotlib.pyplot as plt filename = r"C:\Users\name\Desktop\sampledata.csv" with open(filename, newline='') as file: reader = csv.reader(file) # header = next(reader) time = [] y1 = [] for row in reader: time.append( float(row[0]) ) y1.append( float(row[1]) ) plt.plot(time,y1) plt.show()
has comment: http://stackoverflow.com/comment/80555977
has comment: http://stackoverflow.com/comment/80555094
downvote count: 0
has comment: http://stackoverflow.com/comment/80562960
has comment: http://stackoverflow.com/comment/80531027
has comment: http://stackoverflow.com/comment/80563079

http://stackoverflow.com/q/46857779
has body: I keep getting this error: 31, in &lt;module&gt; check_store[(abcd[int(num)])] = (com_que_store[int(num)]) TypeError: list indices must be integers or slices, not str It looks like the error is when I am trying to access the index of one of my lists. I've looked everywhere and I can't find/make a solution. Can anyone help? Here is the code I am running to get the above error: import random from random import randint from time import sleep as s run = True num = 0 diff = int(input('1-3')) que_1 = 'wright 1' que_2 = 'wrong 2' que_3 = 'wrong 3' que_4 = 'wrong 4' que_store = [que_2, que_3, que_4] com_que_store = [que_1] check_store = [] abcd = ['A', 'B', 'C', 'D'] for i in range(diff): r = randint(0,(2 - num)) print(que_store[r]) com_que_store.append(que_store[r]) que_store.pop(r) num = num + 1 print(com_que_store) random.shuffle(com_que_store) print('\n\n\n') print(com_que_store) num = 0 num = int(num) for value in com_que_store: print(abcd[num], com_que_store[num]) check_store[(abcd[int(num)])] = (com_que_store[int(num)]) num = num + 1 print(com_que_store)
has comment: http://stackoverflow.com/comment/80663191
accepted answer: http://stackoverflow.com/a/46858019
score: -3
has comment: http://stackoverflow.com/comment/80663236
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46858019
has title: TypeError: list indices must be integers or slices, not str #num is set as a int
upvote count: 1
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/80663291
answer count: 1
favorite count: 0

http://stackoverflow.com/q/46783297
tagged with: pandas-groupby
linked to: http://stackoverflow.com/q/26205922
tagged with: multiple-columns
type: UnansweredQuestion
tagged with: python
has body: Let's say I have the following dataframe: State Type Denominator payment1 payment2 payment3 State1 A 40 1000 8000 1000 State1 A 50 5000 4000 5000 State1 B 70 6000 5000 600 State1 B 30 4000 7000 5000 State1 C 50 1000 5000 8000 State2 A 60 5000 7000 4000 State2 A 40 600 5000 5000 State2 B 50 400 6000 7000 State2 C 80 8000 4000 1000 State2 C 40 4000 8000 5000 State3 A 60 5000 4000 600 State3 A 50 7000 5000 400 State3 B 70 5000 7000 5000 State3 B 20 6000 4000 7000 State3 C 50 2000 7000 1000 I would like to calculate weighted average for the 3 payment columns grouped by State and Type using the denominator as the weight. On R, I would successfully use this: health2=health%&gt;%group_by(State, Type)%&gt;%summarise(payment1mean=weighted.mean(payment1, Denominator),payment2mean=weighted.mean(payment2, Denominator),payment3mean=weighted.mean(payment3, Denominator)) How would I be able to do the same on Python? I tried something like the following but didn't work. paycolumns=['payment1','payment2','payment3'] datagrouped=data.groupby(['State','Type'],as_index=False)[paycolumns].apply(lambda x: np.average(x, weights=data.Denominator)
answer count: 0
has comment: http://stackoverflow.com/comment/80513556
tagged with: weighted
has comment: http://stackoverflow.com/comment/80513571
duplicate of: http://stackoverflow.com/q/26205922
type: Question
has title: Python calculate weighted average of multiple columns grouped by multiple columns
tagged with: weighted-average
score: 0
linked to: http://stackoverflow.com/q/33574908

http://stackoverflow.com/q/46791191
linked to: http://stackoverflow.com/q/32745541
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46791811
tagged with: scikit-learn
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/46791811
has body: Package versions: numpy: 1.13.3 sklearn: 0.19.0 scipy: 0.19.1 I have a dense matrix svd_matrix svd_matrix.shape &gt;&gt;&gt; (30000,50) I want to train this on the scikit TSNE implementation using 'cosine' as the metric tsne = sklearn.manifold.TSNE(n_components=2, random_state=0, metric='cosine') matrix_2d = tsne.fit_transform(svd_matrix) &gt;&gt;&gt; ValueError: Metric 'cosine' not valid for algorithm 'ball_tree' However I get the error above. I was training this model last week and it worked fine, but I have updated my package versions in the meantime, but I don't think this would cause an issue? Anyway, package versions are above. algorithm isn't an argument for manifold.TSNE, so I can't give 'brute' as an argument as suggested here Can anyone suggest what is going wrong here and how I can fix this? Thank you
score: 2
type: AnsweredQuestion
has title: ValueError: Metric 'cosine' not valid for algorithm 'ball_tree' when using sklearn TSNE
type: Question

http://stackoverflow.com/a/46863027
answers question: http://stackoverflow.com/q/46862849
has body: Since you obtain string try this to use split '.' in your methods i.e : if string.split('.')[-1] == '0': string = string.split('.')[0] Full Program : num = input() numlist = num.split(",") def even(list): string = "" for number in list : number = float(number) if number %2 == 0: string += "~"+str(number) if string.split('.')[-1] == '0': string = string.split('.')[0] return(string) def odd(list): string = "" for number in list: number = float(number) if number %2 != 0: string += "~"+str(number) if string.split('.')[-1] == '0': string = string.split('.')[0] return(string) print ("even numbers :" ,even(numlist)) print ("odd numbers :" ,odd(numlist)) Sample output : 5,5.6 even numbers : odd numbers : ~5~5.6 Note : Modulus should not be used over floats. Here it considers only integral part not the decimal.
score: 0
type: Answer

http://stackoverflow.com/a/47064119
type: Answer
has body: There are Name objects. These are basically the strings in your file before anything is done to them. To get what they will possibly be, you must .infer() them. This turns something like the word in file "basestring" into a astroid class-ish object basestring (well, actually it returns a generator ... but broad strokes here). Then, given these astroid class-ish objects, you must "instantiate" the class to an astroid instance-ish object. Finally (the important part), node.locals.items() is a dictionary of {name: list of instance-ish objects}. Updating that dictionary lets you set the inferred types. So my broad-strokes code from above would turn into this: from astroid import MANAGER from astroid import nodes, node_classes def transform_myClass(node): updater = {} for key, value in node.locals.items(): val = value[0] try: s = val.statement().value if s.func.name != 'ArgumentObj': continue except AttributeError: continue # Collect all the inferred types in this list typeList = [] for child in s.get_children(): if not isinstance(child, node_classes.Keyword): continue # What I needed to do was here: # Infer the child classes, and return the instantiated class if child.arg == 'allowedTypes': for tc in child.value.get_children(): for cls in tc.infer(): typeList.append(cls.instantiate_class()) updater[key] = typeList # Finally, I needed to update the locals # which sets the inferred types of the class members node.locals.update(updater) MANAGER.register_transform(nodes.ClassDef, transform_myClass)
answers question: http://stackoverflow.com/q/46801978
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46801978

http://stackoverflow.com/comment/80558379
type: Comment
score: 0
has text: I have added my IP to the ALLOWD_HOSTS, currently, it's working but may stop working after few hours like before! Let's See! Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/46803814

http://stackoverflow.com/comment/80470507
score: 0
has text: Yes, it can be whatever you like, although weird things can happen if you use a variable name you've used elsewhere. If nothing else, this will confuse programmers.
type: Comment
comment on: http://stackoverflow.com/a/46762536
type: AnswerComment

http://stackoverflow.com/comment/80552175
comment on: http://stackoverflow.com/q/46802586
score: 0
has text: @DavidZ Yes. That's true.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80538961
type: AnswerComment
has text: This is for python 3.6. I have done similar mocking in more complex systems and everything worked fine. If you use 2.7.x then mock needs to be installed first and you'd need to import mock instead of unittest.mock.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46779161

http://stackoverflow.com/comment/80690232
score: 0
type: Comment
type: QuestionComment
has text: You can find it here : https://pastebin.com/yNTqfjnj
comment on: http://stackoverflow.com/q/46871302

http://stackoverflow.com/q/46789568
has comment: http://stackoverflow.com/comment/80526001
has comment: http://stackoverflow.com/comment/80526020
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46790691
accepted answer: http://stackoverflow.com/a/46790691
type: Question
upvote count: 1
has body: I need to use the program called ogg123 for converting input ogg file to wav. My ogg is on S3 - so I need to download it first and transcode after that. But I think that will be faster to transcode sound on the fly - without writing to the disk source ogg file - using process substitution. From bash I want to do this: ogg123 -d wav &lt;(./test.py) -f out.wav In Python, for binary output, I tried: os.write sys.stdout.buffer.write fp = os.fdopen(sys.stdout.fileno(), 'wb'); fp.write For example: #!/usr/bin/env python3 import os import boto3 s3_client = boto3.client('s3') os.write(1, s3_client.get_object( Bucket='my-bucket-name', Key='file.ogg' )['Body'].read() ) ./test.py in all cases print visually valid data. For example: xxd &lt;(./test.py) | head print: 00000000: 4f67 6753 0002 0000 0000 0000 0000 0000 OggS............ 00000010: 0000 0000 0000 5664 269e 011e 0176 6f72 ......Vd&amp;....vor 00000020: 6269 7300 0000 0001 2256 0000 0000 0000 bis....."V...... 00000030: 058a 0000 0000 0000 a901 4f67 6753 0000 ..........OggS.. 00000040: 0000 0000 0000 0000 0000 0000 0100 0000 ................ 00000050: 5096 ab47 0e16 ffff ffff ffff ffff ffff P..G............ 00000060: ffff c503 766f 7262 6973 0600 0000 6666 ....vorbis....ff 00000070: 6d70 6567 0000 0000 0105 766f 7262 6973 mpeg......vorbis 00000080: 2242 4356 0100 4000 0018 4210 2a05 ad63 "BCV..@...B.*..c 00000090: 8e3a c815 218c 19a2 a042 ca29 c71d 42d0 .:..!....B.)..B. But all these variants generates the same error from ogg123: Error opening /dev/fd/63 using the oggvorbis module. The file may be corrupted. I tried the same file locally - file is correct: $ ogg123 -d wav file.ogg -f out.wav Audio Device: WAV file output Playing: file.ogg Ogg Vorbis stream: 1 channel, 22050 Hz Done. What can you recommend?
favorite count: 0
tagged with: vorbis
tagged with: linux
answer count: 1
tagged with: ogg
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80525945
has comment: http://stackoverflow.com/comment/80526552
tagged with: python
has title: Python: how to write binary data to the stdout so that bash script can use process substitution?

http://stackoverflow.com/a/54773334
downvote count: 0
answers question: http://stackoverflow.com/q/46806318
has body: Have the exact same problem. Use scipy.io.wavfile.read(path) instead.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/80746236
has text: Why do you just `pass` in KeyboardInterrupt? I use KeyboardInterrupt for my termination code.
comment on: http://stackoverflow.com/q/46899021
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/46823593
answers question: http://stackoverflow.com/q/46823540
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/80598764
score: 2
has comment: http://stackoverflow.com/comment/80594600
has body: In principle the following might be what you want: for i, j in zip(i_list, j_list): ....
has comment: http://stackoverflow.com/comment/80594528

http://stackoverflow.com/comment/80730083
has text: I think `pir` solution is much better, so use it ;)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46891129

http://stackoverflow.com/comment/108651893
score: 2
type: Comment
has text: I currently do this but it adds the same page to the browser history, so when you click back you will return to the same page. Any ideas on how to resolve this?
comment on: http://stackoverflow.com/a/46826069
type: AnswerComment

http://stackoverflow.com/a/46900693
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80748487
accepted answer of: http://stackoverflow.com/q/46900659
type: Answer
has comment: http://stackoverflow.com/comment/80748437
upvote count: 3
has body: Use apply + str.join: df.apply(lambda x: ', '.join(x.dropna()), 1).replace('', np.nan) 0 a, f 1 b 2 u 3 c, i 4 NaN dtype: object The final replace call handles your np.nan requirement.
has comment: http://stackoverflow.com/comment/80748457
has comment: http://stackoverflow.com/comment/80749180
score: 3
answers question: http://stackoverflow.com/q/46900659

http://stackoverflow.com/comment/80740586
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46896712
has text: i have already tried that i got, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

http://stackoverflow.com/comment/80634013
type: Comment
has text: Your answer was helpful! I'll check out your package as well. Thank you for responding : )
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46843120

http://stackoverflow.com/comment/80699665
type: QuestionComment
has text: [link] : http://blog.ethanrosenthal.com/2015/11/02/intro-to-collaborative-filtering/. I have made some edits to this link, but nothing significant to the problem I'm facing.
comment on: http://stackoverflow.com/q/46876355
score: 0
type: Comment

http://stackoverflow.com/comment/80676117
type: QuestionComment
has text: Is it always the _first 4_?
comment on: http://stackoverflow.com/q/46864338
score: 0
type: Comment

http://stackoverflow.com/q/46831363
has answer: http://stackoverflow.com/a/46846124
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46846124
score: 1
type: Question
answer count: 1
has title: HTTP Error 404: Not Found Seaborn FacetGrid
tagged with: pandas
upvote count: 1
tagged with: python
favorite count: 0
downvote count: 0
tagged with: seaborn
has body: I have the following data frame that I want to plot in FacetGrid using Seaborn library. projectId sentDate correspondenceId Year Month 0 10417 2001-09-25 8710 2001 9 1 10417 2001-10-01 9173 2001 10 2 10417 2001-10-05 9676 2001 10 3 10417 2001-10-24 11487 2001 10 4 10417 2001-10-29 11872 2001 10 I am using the following code to plot it data_plot = sns.load_dataset("new_df") f = sns.FacetGrid(data_plot, col="Year", col_wrap=4, size=1.5) f = f.map(plt.plot, "Month", "correspondenceId.count()", marker=".") But I am getting an error --&gt; 650 raise HTTPError(req.full_url, code, msg, hdrs, fp) 651 652 class HTTPRedirectHandler(BaseHandler): HTTPError: HTTP Error 404: Not Found My library is up to date. I am new to programming so I still do a lot of trial and error while coding to get the correct output. Any ideas how to resolve this issue?.

http://stackoverflow.com/comment/80572165
has text: Duplicate of https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46812447

character-encoding
tags question: http://stackoverflow.com/q/46863280
tags question: http://stackoverflow.com/q/46763250
tags question: http://stackoverflow.com/q/46781371
tags question: http://stackoverflow.com/q/46762528
tag name: character-encoding
tags question: http://stackoverflow.com/q/46832127
type: Tag
tags question: http://stackoverflow.com/q/46842098
tags question: http://stackoverflow.com/q/46865565
tags question: http://stackoverflow.com/q/46769520
tags question: http://stackoverflow.com/q/46839127

http://stackoverflow.com/comment/80733695
type: AnswerComment
has text: @Adirio If it becomes very complex, so does the your if statements.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46890687

http://stackoverflow.com/a/46815983
answers question: http://stackoverflow.com/q/46814792
has comment: http://stackoverflow.com/comment/80613268
score: 0
type: Answer
has body: You have a few problems. First, your regex as it stands will match both Andi and Anke, because .*nd* is essentially saying "match 0 or more non-line-break characters, an n character, and 0 or more d characters". Second, using a loop doesn't take advantage of Panda's capabilities. Instead, I'd suggest using np.where() and str.contains() to perform your function in a faster and more concise fashion. Using the sample dataframe: df = pd.DataFrame({'Author': ['Andi', 'Tomasius', 'Anke'], 'valid': [0, 0, 0]}) The following code will give you what you want: df['valid'] = np.where(df.Author.str.contains('nd'), 1, 0) If your query is more complicated and you need a regular expression (as per your comment), you can use that too: p = re.compile(r'(?:as)|(?:nd)') df['valid'] = np.where(df.Author.str.contains(p), 1, 0)
has comment: http://stackoverflow.com/comment/80598514

http://stackoverflow.com/q/46897854
type: AnsweredQuestion
score: 2
has title: Python escape '$' character in variable name
tagged with: swagger
type: Question
accepted answer: http://stackoverflow.com/a/46897982
tagged with: bravado
upvote count: 2
has answer: http://stackoverflow.com/a/46897982
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm using bravado, which has created functions for me to call based on a swagger definition. The swagger definition contains query parameters prefixed with $. I.e. client.pet.get_pets($limit=10). Problem is, I can't use $limit=10 because it throws a syntax error. Is there a way to escape this in python?
tagged with: python

http://stackoverflow.com/comment/80672054
has text: An editor called 'spyder' (comes with Anaconda) can do something like this. But I just recognized, that the file is executed in an IPython-Console. I'll work around a little bit. Thank you for your answer.
score: 0
comment on: http://stackoverflow.com/q/46862000
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80466126
has text: Thanks, do you have an example of how to use the `Azure Active Directory authentication`? How can I do this? What do I pass into `batch.BatchServiceClient( credentials, base_url=_BATCH_ACCOUNT_URL)`?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46760328

http://stackoverflow.com/comment/80843080
score: 0
type: AnswerComment
type: Comment
has text: Thanks for the help everyone
comment on: http://stackoverflow.com/a/46831307

http://stackoverflow.com/comment/80752012
type: Comment
type: QuestionComment
has text: Are you handling cycles? What does `traverse_nodes` do? I don't see any recursive calls to `select_node`
comment on: http://stackoverflow.com/q/46902467
score: 0

http://stackoverflow.com/comment/80739937
comment on: http://stackoverflow.com/q/46896347
has text: Are `Redditor` objects hashable?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/46817359
has comment: http://stackoverflow.com/comment/105141066
upvote count: 5
tagged with: python-2.7
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/10192758
has title: whl is not a supported wheel on this platform
type: UnansweredQuestion
tagged with: python-wheel
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/80583991
has comment: http://stackoverflow.com/comment/80583959
has comment: http://stackoverflow.com/comment/80584046
has comment: http://stackoverflow.com/comment/80625801
tagged with: pip
has answer: http://stackoverflow.com/a/46839079
type: Question
has body: I am new to python, and am trying to install some modules/packages using .whl file. The system does not have access to the internet so everything is local. I'm running RHEL 6.9 64bit 2.6.32-696.10.1.el6.x86_64 Python is version 2.7.12 (altinstalled with 2.6) platform.architecture() ('64bit', 'ELF') I'm running pip 9.0.1 Attempt at installing numpy: # /usr/local/bin/pip2.7 install numpy-1.13.3-cp27-cp27m-manylinux1_x86_64.whl numpy-1.13.3-cp27-cp27m-manylinux1_x86_64.whl is not a supported wheel on this platform. So what am I missing?

http://stackoverflow.com/comment/80852857
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46866604
has text: I tried removing the "select one" option, then also the same problem. It will show latitude in the menu and menu will not drop down.
type: AnswerComment

http://stackoverflow.com/comment/80691671
type: Comment
comment on: http://stackoverflow.com/q/46872141
score: 1
has text: @ayhan I see, I would trust you to know more about it than me, so feel free to write an answer :-) I've deleted mine.
type: QuestionComment

http://stackoverflow.com/a/46926919
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80844455
downvote count: 0
answers question: http://stackoverflow.com/q/46882276
has body: Edit-1: No reload needed Thanks to @MartijnPieters helping me enhance the answer. There is no reload needed if we directly patch urllib3.connection. But requests package has some changes in the latest version, which made the original answer not work on some version of requests. Here is a updated version of the code, which handles all these things import requests try: assert requests.__version__ != "2.18.0" import requests.packages.urllib3.util.ssl_ as ssl_ import requests.packages.urllib3.connection as connection except (ImportError,AssertionError,AttributeError): import urllib3.util.ssl_ as ssl_ import urllib3.connection as connection print("Using " + requests.__version__) def _ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None): print('SHOULD BE PRINTED') return ssl_.ssl_wrap_socket(sock, keyfile=keyfile, certfile=certfile, cert_reqs=cert_reqs, ca_certs=ca_certs, server_hostname=server_hostname, ssl_version=ssl_version, ciphers=ciphers, ssl_context=ssl_context, ca_cert_dir=ca_cert_dir) connection.ssl_wrap_socket = _ssl_wrap_socket res = requests.get("https://www.google.com", verify=True) The code is also available on https://github.com/tarunlalwani/monkey-patch-ssl_wrap_socket Original Answer So two issues in your code. requests doesn't actually directly import urllib3. It does it through its own context using requests.packages So the socket you want to overwrite is requests.packages.urllib3.util.ssl_.ssl_wrap_socket Next if you look at connection.py from urllib3/connection.py from .util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, assert_fingerprint, ) This is a local import and it can't be overridden on first attempt as the code is loaded when we use import requests. You can easily confirm that by putting a breakpoint and checking the stack trace back to parent file. So for the monkey patch to work we need to reload th…
accepted answer of: http://stackoverflow.com/q/46882276
has comment: http://stackoverflow.com/comment/80833321
has comment: http://stackoverflow.com/comment/80844040
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/80847069
has comment: http://stackoverflow.com/comment/80844145
has comment: http://stackoverflow.com/comment/80844112
has comment: http://stackoverflow.com/comment/80845163
has comment: http://stackoverflow.com/comment/80843913
has comment: http://stackoverflow.com/comment/80844042
has comment: http://stackoverflow.com/comment/80885294
upvote count: 4

http://stackoverflow.com/q/46827087
downvote count: 1
accepted answer: http://stackoverflow.com/a/46827498
type: Question
has title: Join two csv files (1-N relation)
score: 0
tagged with: bash
answer count: 2
tagged with: awk
favorite count: 0
possible better answer: http://stackoverflow.com/a/46827518
has answer: http://stackoverflow.com/a/46827498
has answer: http://stackoverflow.com/a/46827518
has comment: http://stackoverflow.com/comment/80606696
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: The csv files are tab delimited file1.csv: id_album name date 001 Nevermind 24/09/1991 ... file2.csv: id_song id_album name 001 001 Smells Like Teen Spirit 002 001 In Bloom ... I would like to obtain this output.csv : id_album name date songs 001 Nevermind 24/09/1991 001,Smells Like Teen Spirit,002,In Bloom,... Do you see a way to do it in Bash (preferably) or Python ? I have a lot of records in my csv files (millions of lines). EDIT I tried join / sed / awk but was not able to manage the 1 to N relation
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80601543
tagged with: join
has comment: http://stackoverflow.com/comment/80602230
upvote count: 1

http://stackoverflow.com/q/46790718
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/46790955
tagged with: python-3.x
type: Question
score: 0
tagged with: python
answer count: 1
has title: Import of csv data rows and columns when specyfing delimiter
has answer: http://stackoverflow.com/a/46790955
has comment: http://stackoverflow.com/comment/80528157
has body: import csv import matplotlib.pyplot as plt filename = r"C:\Users\name\Desktop\sampledata.csv" with open(filename, newline='') as file: reader = csv.reader(file) header = next(reader) data = [] for row in reader: measured_time = float(row[0]) wv1 = float(row[1]) wv2 = float(row[2]) data.append([measured_time, wv1,wv2]) time=data[0] y1=data[1] plt.plot(time,y1) plt.show() Works just fine, but as this was a test before I work with the real data. Now the real data doesn't have a header and consists on only 2 columns. import csv import matplotlib.pyplot as plt filename = r"C:\Users\name\Desktop\real_data.csv" with open(filename, newline='') as file: reader = csv.reader(file,delimiter=';') data = [] for row in reader: measured_time = float(row[0]) wv1 = float(row[1]) data.append([measured_time, wv1]) time=data[0] y1=data[1] plt.plot(time,y1) plt.show() this yields time=[100,1] y1=[110,2] so basically just the first 2 rows while the first codeblock correctly extracts the columns time=[100 110 ...] y1=[1 2 ...] The same thing happens when I use import csv import matplotlib.pyplot as plt filename = r"C:\Users\name\Desktop\sampledata.csv" with open(filename, newline='') as file: reader = csv.reader(file) header = next(reader) data = [] for row in reader: measured_time = float(row[0]) wv1 = float(row[1]) data.append([measured_time, wv1]) time=data[0] y1=data[1] plt.plot(time,y1) plt.show() For now my workaround is data = np.array(data).astype("float") time=data[:,0] y1=data[:,1] Surely there has to be a better way, I'm just starting with Python. Data used: sample data Time,279 nm,306 nm 0,100,150 1,110,175 2,125,230 3,130,245 real data 3.986931e+002;0.000000e+000 4.021733e+002;0.000000e+000
has comment: http://stackoverflow.com/comment/80528047
has comment: http://stackoverflow.com/comment/80527768
has comment: http://stackoverflow.com/comment/80527910

http://stackoverflow.com/q/46821205
accepted answer: http://stackoverflow.com/a/46822961
tagged with: fluid-dynamics
tagged with: sympy
tagged with: python-3.6
has body: I am trying to plot streamlines and velocity potential for basic potential flows (uniform, source/sink, vortex, etc.) I am just starting out with python and so I'm a little confused. I am following this guide.. I can plot the streamlines for the flow around a cylinder using this function def cylinder_stream_function(U=1, R=1): r = sympy.sqrt(x**2 + y**2) theta = sympy.atan2(y, x) return U * (r - R**2 / r) * sympy.sin(theta) and it works. But when I change the return statement to return U * r * sympy.cos(theta) for uniform flow I get the following error Traceback (most recent call last): File "test.py", line 42, in &lt;module&gt; plot_streamlines(ax, u, v) File "test.py", line 32, in plot_streamlines ax.streamplot(X, Y, u(X, Y), v(X, Y), color='cornflowerblue') File "/usr/local/lib/python3.6/site-packages/matplotlib/__init__.py", line 1710, in inner return func(ax, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 4688, in streamplot integration_direction=integration_direction) File "/usr/local/lib/python3.6/site-packages/matplotlib/streamplot.py", line 136, in streamplot if (u.shape != grid.shape) or (v.shape != grid.shape): AttributeError: 'int' object has no attribute 'shape' I checked the type for the return object and it is &lt;class 'sympy.core.mul.Mul'&gt; with the first return statement and &lt;class 'sympy.core.symbol.Symbol'&gt; with the second one. Maybe this is related to why it doesn't work but I'm not sure how? I plot the streamlines with the following import numpy as np import matplotlib.pyplot as plt import sympy from sympy.abc import x, y def uniform_flow_stream_function(U=1): r = sympy.sqrt(x**2 + y**2) theta = sympy.atan2(y, x) return U * r * sympy.sin(theta) def velocity_field(psi): u = sympy.lambdify((x, y), psi.diff(y), 'numpy') v = sympy.lambdify((x, y), -psi.diff(x), 'numpy') return u, v def plot_streamlines(ax, u, v, xlim=(-4, 4), ylim=(-4, 4)): x0, x1 = xlim y0, y1 = ylim # create a grid of values …
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80589880
tagged with: python
has title: plotting streamlines with python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46822961
type: Question

http://stackoverflow.com/a/46875353
accepted answer of: http://stackoverflow.com/q/46875205
score: 0
has body: you tell django that your template dir is in post then you include the comment_block so django will lock in post/templates/comment_block.html but your file is not there its in post/template/post/comment_block.html so you need to include your file like this {% include 'post/comment_block.html'%}
type: Answer
answers question: http://stackoverflow.com/q/46875205
type: AcceptedAnswer

http://stackoverflow.com/q/46813776
has comment: http://stackoverflow.com/comment/80576008
has comment: http://stackoverflow.com/comment/80574712
has title: import inside a function: is memory reclaimed upon function exit?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/46815844
upvote count: 5
has comment: http://stackoverflow.com/comment/80576108
has comment: http://stackoverflow.com/comment/80574863
score: 4
linked to: http://stackoverflow.com/q/128478
tagged with: micropython
possible better answer: http://stackoverflow.com/a/47052498
has answer: http://stackoverflow.com/a/47052498
has comment: http://stackoverflow.com/comment/80575062
has body: Linked questions: python - import at top of file vs inside a function Should Python import statements always be at the top of a module? If an import statement is inside a function, will the memory occupied by it get reclaimed once the function exits? If yes, is the timing of the reclamation deterministic (or even -ish)? def func(): import os ... # function about to exit; will memory occupied by `os` be freed? If anyone has knowledge on the behavior of micropython on this topic, bonus points.
favorite count: 0
has comment: http://stackoverflow.com/comment/80575925
has comment: http://stackoverflow.com/comment/80575975
linked to: http://stackoverflow.com/q/46813425
tagged with: python
has answer: http://stackoverflow.com/a/46815844
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/46803518
upvote count: 1
has comment: http://stackoverflow.com/comment/80553943
has comment: http://stackoverflow.com/comment/80555794
has comment: http://stackoverflow.com/comment/80558931
has comment: http://stackoverflow.com/comment/80558267
has comment: http://stackoverflow.com/comment/80554936
downvote count: 0
has comment: http://stackoverflow.com/comment/80558622
answers question: http://stackoverflow.com/q/46803413
type: Answer
has comment: http://stackoverflow.com/comment/80558154
has body: Here's the problem: line_index = [x for x in range(len(content)) if "//" in content[x]] Although You defined line_index as int, You overwrite it with this list, thus error message that You can't concatenate int to list. Update: For getting indexes of lines containing // use following: file_info = open('compounds.dat', 'r') special_line_indexes = [] unique_line_index = 0 for i, line in enumerate(file_info.readlines()): if '//' in line: #extract line index for lines that contain // special_line_indexes.append(i + 1) elif 'InChIKey=HCZNPUHZYPPINM-AWEZNQCLSA-M' in line: # return index of line after // unique_line_index = i + 1
score: 1

http://stackoverflow.com/a/46772919
answers question: http://stackoverflow.com/q/46772698
has comment: http://stackoverflow.com/comment/80491763
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80518630
has body: You can do this by using backreferences in combination with re.sub: import re val1 = '[{&amp;quot;vmdId&amp;quot;:&amp;quot;Text1&amp;quot;,&amp;quot;vmdVersion&amp;quot;:&amp;quot;text2&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text3&amp;quot;},{&amp;quot;vmId&amp;quot;:&amp;quot;text4&amp;quot;,&amp;quot;vmVersion&amp;quot;:&amp;quot;text5&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text6&amp;quot;}]' ansstring = re.sub(r'(?&lt;=:&amp;quot;)([^(]*)', r'new\g&lt;1&gt;' , val1) print ansstring \g&lt;1&gt; is the text which is in the first (). EDIT Maybe a better approach would be to decode the string, change the data and encode it again. This should allow you to easier access the values. import sys # python2 version if sys.version_info[0] &lt; 3: import HTMLParser html = HTMLParser.HTMLParser() html_escape_table = { "&amp;": "&amp;amp;", '"': "&amp;quot;", "'": "&amp;apos;", "&gt;": "&amp;gt;", "&lt;": "&amp;lt;", } def html_escape(text): """Produce entities within text.""" return "".join(html_escape_table.get(c,c) for c in text) html.escape = html_escape else: import html import json val1 = '[{&amp;quot;vmdId&amp;quot;:&amp;quot;Text1&amp;quot;,&amp;quot;vmdVersion&amp;quot;:&amp;quot;text2&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text3&amp;quot;},{&amp;quot;vmId&amp;quot;:&amp;quot;text4&amp;quot;,&amp;quot;vmVersion&amp;quot;:&amp;quot;text5&amp;quot;,&amp;quot;vmId&amp;quot;:&amp;quot;text6&amp;quot;}]' print(val1) unescaped = html.unescape(val1) json_data = json.loads(unescaped) for d in json_data: d['vmId'] = 'new value' new_unescaped = json.dumps(json_data) new_val = html.escape(new_unescaped) print(new_val) I hope this helps.
has comment: http://stackoverflow.com/comment/80510796
has comment: http://stackoverflow.com/comment/80491753
has comment: http://stackoverflow.com/comment/80518164
upvote count: 2
has comment: http://stackoverflow.com/comment/80519700
has comment: http://stackoverflow.com/comment/80515531
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46772698

http://stackoverflow.com/a/46840423
answers question: http://stackoverflow.com/q/46839401
type: Answer
has body: Others have provided some good options so I figured I'd list something different you may choose to use: (reusing User's example) &gt;&gt;&gt; MyDict = {} &gt;&gt;&gt; MyDict["entry1"] = {'fields':{'ID': 123, 'name': 'test'},'otherfield': 'value' } &gt;&gt;&gt; MyDict["entry2"] = {'fields':{'ID': 456, 'name': 'test2'},'otherfield': 'value2' } &gt;&gt;&gt; for v in map(lambda x: x['ID'], filter(lambda x: isinstance(x, dict) and 'ID' in x, sum(map(lambda x:list(x.values()), list(MyDict.values())), []))): ... v ... 123 456 To explain this, moving from the innermost function outward: innermost map creates a list of N entries, where N is number of items in top level dict and each entry is a list of the values of each item in the dict format you've shown above. Thus, a list of list. Sum a list of list into a single list Filter list for dicts with 'ID' key Obtain only the 'ID' value from each such dict
score: 0

http://stackoverflow.com/q/46837373
has body: Using tkinter, I want to add the if statement in the GUI code where if a certain name gets chosen (by random) i want to display an image of the person chosen. For example, if Valkyrie gets chosen when picking defenders, i want her name and this photo to show up. Heres my code for my GUI: from tkinter import * import tkinter import tkinter as tk import random names = ['Sledge','Thatcher','Ash','Thermite','Twitch','Montagne','Glaz','Fuze','Blitz','IQ','Buck','Blackbeard','Capitão','Hibana'] name = ["Smoke","Mute","Castle","Pulse","Doc","Rook","Kapkan","Tachanka","Jäger","Bandit","Frost","Valkyrie","Caveira","Echo"] root = tkinter.Tk() def pickName(): nameLabel.configure(text=random.choice(names)) def pickName1(): nameLabel.configure(text=random.choice(name)) root.title("Operator Picker") root.geometry("1920x300") nameLabel = tkinter.Label(root, text="", font=('Helvetica', 32)) nameLabel.pack() Grid() pickButton1 = tkinter.Button(root, text="Pick Attack", command=pickName, height=100, width=100) pickButton1.pack(side=tkinter.LEFT) pickButton2 = tkinter.Button(root, text="Pick Defend", command=pickName1, height=100, width=100) pickButton2.pack(side=tkinter.RIGHT) root.mainloop() I tried to use an if statement, but there's no variable i can attach it to. All help appreciated, thanks!
upvote count: 1
type: Question
score: 1
downvote count: 0
tagged with: python-3.6
has title: How to add an image into GUI with an if statement
favorite count: 0
tagged with: python
tagged with: python-3.x
tagged with: tkinter
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/46758681
upvote count: 8
accepted answer of: http://stackoverflow.com/q/46758628
type: Answer
score: 8
has body: You can use a list comprehension: max_num = max(numbers) highest = [num for num in numbers if num == max_num]
answers question: http://stackoverflow.com/q/46758628
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80929012
type: Comment
has text: Thanks for the answer. I'm reading about 2000 files and there do seem to be 4 partitions (at least according to getNumPartitions)
comment on: http://stackoverflow.com/a/46931018
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80554036
has text: Indeed... if I run the VLOOKUP function of Excel it merges (ofcourse only the first occurence) the data of the two lists....
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46791336

http://stackoverflow.com/comment/80607713
type: Comment
comment on: http://stackoverflow.com/a/46829054
has text: Well, the article is very superficial, with couple hello-world level examples which don't hold water when applied to something more realistic... :/
score: 6
type: AnswerComment

http://stackoverflow.com/q/46755238
answer count: 4
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46755323
type: Question
possible better answer: http://stackoverflow.com/a/46755289
downvote count: 0
has answer: http://stackoverflow.com/a/46755323
has comment: http://stackoverflow.com/comment/80455950
has answer: http://stackoverflow.com/a/46755289
tagged with: while-loop
has title: while loop doesn't end even when the condition is right
favorite count: 0
has comment: http://stackoverflow.com/comment/80455894
has answer: http://stackoverflow.com/a/46755508
has answer: http://stackoverflow.com/a/46755350
has body: I am doing a login system. It asks the user to answer the question ('Do you already have an account? ') and while the answer isn't yes or no it should continue asking. print('Welcome to the quiz!') print('Do you already have an account? ') have_acc = input() while have_acc != ('Yes') or have_acc != ('No') or have_acc != ('yes') or have_acc != ('no'): print('Please enter Yes or No') have_acc = input() OUTPUT Welcome to the quiz! Do you already have an account? yes Please enter Yes or No no Please enter Yes or No Yes Please enter Yes or No No Please enter Yes or No
upvote count: 1
tagged with: python

http://stackoverflow.com/a/46768694
answers question: http://stackoverflow.com/q/46768655
accepted answer of: http://stackoverflow.com/q/46768655
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
score: 8
has body: I think you need size or count if dont need count NaNs with transform: cols = ['A','D','E'] df['A_D_E_count'] = df.groupby(cols)['A'].transform('size') print (df) A B C D E A_D_E_count 0 294 41981 37597 39875 33364 1 1 294 39776 37597 37572 39171 1 2 294 44658 49408 43713 49408 2 3 294 58615 52065 43713 49408 2 4 294 44811 51238 42926 49408 1

http://stackoverflow.com/q/46868738
type: Question
has title: Simple python cicle not working
downvote count: 4
accepted answer: http://stackoverflow.com/a/46868786
possible better answer: http://stackoverflow.com/a/46868784
has answer: http://stackoverflow.com/a/46868784
answer count: 3
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80684723
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/46868786
has answer: http://stackoverflow.com/a/46868765
type: AnsweredQuestion
has body: I'm trying to input several numbers and getting an output with the total sum and the counter for how many inputs until the input is the string "." but it just keeps adding the first input over and over again. What am I doing wrong? sum = 0 counter = 0 x = float(input()) while x!=".": sum = sum + x counter += 1 print ("sum:",sum) print ("counter:",counter)
has comment: http://stackoverflow.com/comment/80684826
upvote count: 1

http://stackoverflow.com/a/62125864
has comment: http://stackoverflow.com/comment/116248075
downvote count: 0
type: Answer
upvote count: 13
answers question: http://stackoverflow.com/q/46902357
has body: This command did the trick from @Aniket Sinha's answer above: pip install mysqlclient
score: 13

http://stackoverflow.com/a/46819009
answers question: http://stackoverflow.com/q/46818555
has comment: http://stackoverflow.com/comment/80589382
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80586336
has body: Use merge with default parameter how = 'inner' df.merge(dfnew, on = ['ticker', 'year', 'quarter']) You get ticker year quarter exec_lname jobposition eps calldate 0 XX 2009 3 A CEO x Mar 1 XX 2009 3 B CFO x Mar 2 XX 2009 4 A CEO y Apr 3 XX 2009 4 B CFO y Apr 4 YY 2007 1 C CEO z Feb 5 YY 2007 1 D CFO z Feb 6 YY 2007 2 C CEO a Jan 7 YY 2007 2 D CFO a Jan 8 ZZ 2008 3 F CEO b Dec 9 ZZ 2008 3 G CFO b Dec

http://stackoverflow.com/comment/80682475
comment on: http://stackoverflow.com/q/46855638
type: Comment
type: QuestionComment
has text: thank you man, it's different than NODEJS or Php with Apach ,
score: 0

http://stackoverflow.com/q/46808208
tagged with: excel
has title: make list of all the relevant data from excel
has comment: http://stackoverflow.com/comment/80575520
has body: HI guys! I'm trying to add some relevant information from my excel file using python. The picture above is an example of the excel file I have to deal with. Column A ; company number Column B ; customer name (customer of the company stated on column A on the same row) Column D ; report date I want to add all the customer names with the same company number and the same report date. For example, after processing data, It would be best to get the below data form. 313368 19931031 GEN MTR, FORD MTR 313368 19941031 FORD MTR, NEW VENT.., GKN AUTO.., GEN MTR 2134 19831031 GEN MTR, FORD MOTOR 2134 19841031 FORD MOTOR, GEN MTR 2134 19851031 FORD MOTOR 2134 19861031 GEN MTR, FORD MOTOR ... ... ... 61478 19801031 MCI COMM..., AM TEL &amp;..., INTL BUS Thanks for your help! Hope you have a great day!
type: Question
has comment: http://stackoverflow.com/comment/80567252
has comment: http://stackoverflow.com/comment/80563686
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/80563437
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80567341

http://stackoverflow.com/q/46842966
has answer: http://stackoverflow.com/a/46852106
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/46843416
favorite count: 0
tagged with: beautifulsoup
upvote count: 2
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
score: 2
type: Question
has comment: http://stackoverflow.com/comment/80645344
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80644715
has body: HTML: A A1 Apple Alien AI April B B1 Banana Babe Bamboo Berry I want to scrape the urls of Apple, Alien, AI and April, but not sure how to do it. My code below only scraped A's url which is "/nephrology?cat=879". How to let it scrape the url inside class' class "divider"? Because when I tried to use only class "divider", it will also extract Banana's and others url. But I don't need them. Thanks in advance! My code: for item in soup.find_all(attrs={'class':'dropdown menu-large'}): for link in item.find_all('a', {'title' : 'A'}): href=link.get('href') #it gets "/nephrology?cat=879"
has title: Python: Extract links in certain class' class

http://stackoverflow.com/a/53562301
has comment: http://stackoverflow.com/comment/94100305
answers question: http://stackoverflow.com/q/46795512
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/93998402
type: Answer
has comment: http://stackoverflow.com/comment/94017797
downvote count: 1
has body: Currently taking this class and figured this out. This is my contribution to all of us college peeps just trying to make it through, lol. MPL accepts this answer. input = open('rawdata','r') datum = int(input.readline()) input.close()

http://stackoverflow.com/comment/80624067
has text: Have you tried with only having one of the values as `1`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46837647
score: 0

http://stackoverflow.com/comment/80640663
type: Comment
type: QuestionComment
has text: There are many posts on this site about fast primality testing in Python. Did you look through them, and why do they not meet your needs?
score: 0
comment on: http://stackoverflow.com/q/46841968

http://stackoverflow.com/comment/80446299
has text: Okay thanks, I'll try that. Is there a reason it ends up saying the question again too? Or, is that because of the input?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46750071
score: 0

http://stackoverflow.com/q/46813140
answer count: 3
has title: Rearranging a string based on a specific requirement to return a list of strings
has answer: http://stackoverflow.com/a/46813302
has answer: http://stackoverflow.com/a/46813362
type: UnansweredQuestion
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/46813328
has body: Hi there so I am looking to build this python function with simple things like def, find etc. so far I know how to get the first part of the code. Given a string such as "HELLODOGMEMEPAPA", I will need to return a list that gives me three things: Everything before the word dog which i will denote as before_dog The word dog and three letters after it denoted as dog_3letters Everything after the dog_3letters which i will denote as everything_after The list will be in the form [before_dog,dog_3letters,everything_after]. So given a string such as "HELLODOGMEMEPAPA" I will need to return the list ["HELLO", "DOGMEM", "EPAPA"] or a string like "HEYWHATDOGDODOD" I will need to return ["HEYWHAT","DOGDOD","OD"]. This is what I have so far: def split_list(words): # declare the list lst = [] # find the first position first_pos=words.find("DOG") # find the first_pos first = words [0:first_pos] lst.append(first) return lst
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80573790

http://stackoverflow.com/comment/80513116
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46783230
has text: Welcome to stackoverflow. You have to inherit the save button first @Aravind Mano

http://stackoverflow.com/comment/80753451
type: QuestionComment
has text: This is rather unclear...
comment on: http://stackoverflow.com/q/46903438
score: 0
type: Comment

http://stackoverflow.com/comment/80667257
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46851134
has text: Thanks for explaining so wonderfully :-) Everything works fine but can I add those % signs later once my comparison task is finished back to those coloumns because I really need those. Thanks again for the solution.
score: 0

http://stackoverflow.com/comment/80556318
score: 0
comment on: http://stackoverflow.com/q/46800336
has text: yes, i thought, so no way to give a patch or another little program which can do that itself..
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80476462
type: AnswerComment
comment on: http://stackoverflow.com/a/46757690
score: 0
type: Comment
has text: thanks for you help it's great but I got the same issue as in other aproach, the first 77 values are good but after that all values are 0 or nan. idk why but it's happening with all solutions

http://stackoverflow.com/comment/104688122
has text: This is similar to the issue reported here https://github.com/joblib/joblib/issues/911 however I cannot reproduce it myself. Could someone experiencing this issue please report the full traceback information if you can reproduce it with joblib 0.14.0 or later?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46828371
score: 0

http://stackoverflow.com/q/46885496
tagged with: python
linked to: http://stackoverflow.com/q/9455111
answer count: 0
type: UnansweredQuestion
score: 0
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/9455111
has body: I am trying to define a set of functions outside of a class that I want to use. Then however I want to make these functions available as methods inside the class. Simple example: import numpy as np import matplotlib.pyplot as plt from matplotlib import pylab def my_plot(self): plt.clf() fig, ax = plt.subplots() ax.plot(self.timeline, self.sample, color = self.color) plt.show() class test(object): def __init__(self, color = 'black'): self.sample = np.random.normal(0, 1, 100) self.timeline = np.arange(1,101,1) self.color = color self.plot = my_plot Now when I call, my_test = test() my_test.plot() I get the error: my_plot() missing 1 required positional argument: 'self' However, my_test.plot(my_test) produces the expected result. According to what I understand, my_test.plot() is equivalent to plot(my_test) so I do not understand why I should write my_test.plot(my_test) here. Any help would be greatly appreciated.
tagged with: class
type: Question
has comment: http://stackoverflow.com/comment/80718393
has comment: http://stackoverflow.com/comment/80720083
favorite count: 0
has title: Python: defining function outside class
tagged with: python-3.x

http://stackoverflow.com/a/46876240
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46876099
upvote count: 1
has body: You should keep in mind that find_all function returns a list of soup objects by which you have filtered, in your case by a class. What you are next trying to do is: h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] soup.find_all('a', {'class': 'lien-jv topic-title'}) is a list and you are trying to access ['title'] which is wrong. so the best way to receive title from: titles = map(lambda soup_object: soup_object['title'], soup.find_all('a', {'class': 'lien-jv topic-title'}))

http://stackoverflow.com/q/46760008
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/46760044
type: Question
has body: I would like to retrieve a column from a csv file and make it an index in a dataframe. However, I realize that I might need to do another step beforehand. The csv looks like this; Date,Step,Order,Price 2011-01-10,Step,BUY,150 2011-01-10,Step,SELL,150 2011-01-13,Step,SELL,150 2011-01-13,Step1,BUY,400 2011-01-26,Step2,BUY,100 If I print the dataframe this is the output: Date Step Order Price 0 0 Step BUY 150 1 1 Step SELL 150 2 2 Step SELL 150 3 3 Step1 BUY 400 4 4 Step2 BUY 100 However, the output that I would like is to tell how many buys/sells per type of Step I have on each day. For example; The expected dataframe and output are: Date Num-Buy-Sell 2011-01-10 2 2011-01-13 2 2011-01-16 1 This is the code on how I'm retrieving the data frame; num_trasanctions_day = pd.read_csv(orders_file, parse_dates=True, sep=',', dayfirst=True) num_trasanctions_day['Transactions'] = orders.groupby(['Date', 'Order']) num_trasanctions_day['Date'] = num_trasanctions_day.index My first thought was to make date the index, but I guess I need to calculate how many sell/buys are there per date. Error KeyError: 'Order' Thanks
has title: Count instances of transactions per day pandas data frame
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46760044
tagged with: python
type: AnsweredQuestion

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/46877800
tags question: http://stackoverflow.com/q/46799041
tags question: http://stackoverflow.com/q/46834364

http://stackoverflow.com/comment/132317611
type: AnswerComment
has text: Yeah my default binary location is already correct. But it is not a different use case. It can be a use for many different user. So posted my answer as well coz the accepted answer was not working for me. When I passed 'firefox_binary = FirefoxBinary('/usr/bin/firefox/')' without the arguments, then it worked.
comment on: http://stackoverflow.com/a/74936519
type: Comment
score: 0

http://stackoverflow.com/a/46774778
downvote count: 1
type: Answer
has body: Using Eval() i am getting the result i exepcted. Posting answer below. But still i am not sure why exec() is not working. import json from pandas.io.json import json_normalize import sys def param(dfile): aString = "['widget']['image']~['widget']['window']~['widget']['text']" for nd_part in aString.split('~'): s = '{0}{1}'.format('dfile',nd_part) temp = eval(s) print(temp) if __name__ == "__main__": dfile = json.load(open("sample_json.json")) str_list = param(dfile) Result: {'src': 'Images/Sun.png', 'alignment': 'center', 'vOffset': 250, 'name': 'sun1', 'hOffset': 250} {'title': 'Sample Konfabulator Widget', 'height': 500, 'width': 500, 'name': 'main_window'} {'alignment': 'center', 'onMouseUp': 'sun1.opacity = (sun1.opacity / 100) * 90;', 'data': 'Click Here', 'hOffset': 250, 'size': 36, 'vOffset': 100, 'name': 'text1', 'style': 'bold'}
accepted answer of: http://stackoverflow.com/q/46774217
score: 1
answers question: http://stackoverflow.com/q/46774217
upvote count: 2
type: AcceptedAnswer

flask
tags question: http://stackoverflow.com/q/46858123
tags question: http://stackoverflow.com/q/46856005
tags question: http://stackoverflow.com/q/46792270
tags question: http://stackoverflow.com/q/46831044
tags question: http://stackoverflow.com/q/46822068
tags question: http://stackoverflow.com/q/46841928
tags question: http://stackoverflow.com/q/46797160
tags question: http://stackoverflow.com/q/46900804
tags question: http://stackoverflow.com/q/46863628
tags question: http://stackoverflow.com/q/46863565
tags question: http://stackoverflow.com/q/46893628
tags question: http://stackoverflow.com/q/46834447
tags question: http://stackoverflow.com/q/46898990
tags question: http://stackoverflow.com/q/46789102
tags question: http://stackoverflow.com/q/46777222
tags question: http://stackoverflow.com/q/46864673
tags question: http://stackoverflow.com/q/46875697
tags question: http://stackoverflow.com/q/46862431
tags question: http://stackoverflow.com/q/46830131
tags question: http://stackoverflow.com/q/46858325
tags question: http://stackoverflow.com/q/46837057
tags question: http://stackoverflow.com/q/46850706
tags question: http://stackoverflow.com/q/46806768
tags question: http://stackoverflow.com/q/46891634
tags question: http://stackoverflow.com/q/46828088
tags question: http://stackoverflow.com/q/46887127
tags question: http://stackoverflow.com/q/46793064
tags question: http://stackoverflow.com/q/46820042
tags question: http://stackoverflow.com/q/46876259
tags question: http://stackoverflow.com/q/46846762
tags question: http://stackoverflow.com/q/46762086
tags question: http://stackoverflow.com/q/46888093
tags question: http://stackoverflow.com/q/46795989
tags question: http://stackoverflow.com/q/46874464
tags question: http://stackoverflow.com/q/46870307
tags question: http://stackoverflow.com/q/46777158
tags question: http://stackoverflow.com/q/46860747
tags question: http://stackoverflow.com/q/46869890
tags question: http://stackoverflow.com/q/46784471
tags question: http://stackoverflow.com/q/46789423
type: Tag
tags question: http://stackoverflow.com/q/46872614
tags question: http://stackoverflow.com/q/46814753
tags question: http://stackoverflow.com/q/46765617
tags question: http://stackoverflow.com/q/46882954
tags question: http://stackoverflow.com/q/46826035
tags question: http://stackoverflow.com/q/46818700
tags question: http://stackoverflow.com/q/46816287
tags question: http://stackoverflow.com/q/46792087
tags question: http://stackoverflow.com/q/46897391
tags question: http://stackoverflow.com/q/46775801
tags question: http://stackoverflow.com/q/46779416
tags question: http://stackoverflow.com/q/46785507
tags question: http://stackoverflow.com/q/46792418
tags question: http://stackoverflow.com/q/46868730
tags question: http://stackoverflow.com/q/46846896
tags question: http://stackoverflow.com/q/46838598
tags question: http://stackoverflow.com/q/46850129
tags question: http://stackoverflow.com/q/46758066
tags question: http://stackoverflow.com/q/46817901
tags question: http://stackoverflow.com/q/46819254
tags question: http://stackoverflow.com/q/46836009
tags question: http://stackoverflow.com/q/46878848
tags question: http://stackoverflow.com/q/46835568
tags question: http://stackoverflow.com/q/46900676
tags question: http://stackoverflow.com/q/46847066
tags question: http://stackoverflow.com/q/46837567
tags question: http://stackoverflow.com/q/46756197
tags question: http://stackoverflow.com/q/46860447
tags question: http://stackoverflow.com/q/46879681
tags question: http://stackoverflow.com/q/46897417
tags question: http://stackoverflow.com/q/46805813
tags question: http://stackoverflow.com/q/46881411
tags question: http://stackoverflow.com/q/46750690
tags question: http://stackoverflow.com/q/46867659
tags question: http://stackoverflow.com/q/46872034
tags question: http://stackoverflow.com/q/46855071
tags question: http://stackoverflow.com/q/46905119
tags question: http://stackoverflow.com/q/46885025
tags question: http://stackoverflow.com/q/46761979

http://stackoverflow.com/comment/80461264
score: 1
has text: @endolith okay... so `InvalidResult = None` - and you're done? :p
comment on: http://stackoverflow.com/q/46757958
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46868137
tagged with: readfile
has answer: http://stackoverflow.com/a/46868572
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80694631
has title: Reading url from file Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80697844
score: 1
upvote count: 1
type: Question
has body: can not read the url in txt file I want to read and open the url addresses in txt one by one, and I want to get the title of the title with regex from the source of url addresses Error messages: Traceback (most recent call last): File "Mypy.py", line 14, in UrlsOpen = urllib2.urlopen(listSplit) File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 420, in open req.timeout = timeout AttributeError: 'list' object has no attribute 'timeout' Mypy.py #!/usr/bin/env python # -*- coding: utf-8 -*- import re import requests import urllib2 import threading UrlListFile = open("Url.txt","r") UrlListRead = UrlListFile.read() UrlListFile.close() listSplit = UrlListRead.split('\r\n') UrlsOpen = urllib2.urlopen(listSplit) ReadSource = UrlsOpen.read().decode('utf-8') regex = '&lt;title.*?&gt;(.+?)&lt;/title&gt;' comp = re.compile(regex) links = re.findall(comp,ReadSource) for i in links: SaveDataFiles = open("SaveDataMyFile.txt","w") SaveDataFiles.write(i) SaveDataFiles.close()
accepted answer: http://stackoverflow.com/a/46868572
has comment: http://stackoverflow.com/comment/80683626
answer count: 1
downvote count: 0

http://stackoverflow.com/q/46797259
upvote count: 1
has comment: http://stackoverflow.com/comment/80543561
favorite count: 0
has title: Pandas query using filter and sort, leading to unresolved errors
tagged with: python
has body: I am working on this problem for my coding class that is outlined in the doc strings. I would appreciate any help on optimizing my code as well as any explanations as to why I am receiving the following error despite resetting the index. import pandas as pd def beds_top_ten(df, facility_id): ''' INPUT: DataFrame, int OUTPUT: date Write a pandas query that returns the ten census dates with the highest number of available beds for the nursing home with the specified facility id REQUIREMENTS: Do a filter followed by a sort rather than a sort followed by a merge. ''' df = pd.read_csv('beds.csv', low_memory= False) df['Bed Census Date'] = pd.to_datetime(df['Bed Census Date']) df = df.filter(items =['Facility ID', 'Bed Census Date','Available Residential Beds']) df = df.sort_values(by =[ 'Facility ID', 'Available Residential Beds'], ascending= False) df_group_by_ten = df.groupby('Facility ID').head(10).reset_index(drop=True) dates = df_group_by_ten.loc[df_group_by_ten['Facility ID']==facility_id, 'Bed Census Date'] return dates this is what the table looks like after the first groupby: Facility ID Bed Census Date Available Residential Beds 336 19 2011-01-05 29 339 19 2010-12-15 28 330 19 2011-02-23 27 332 19 2011-02-02 27 333 19 2011-01-26 27 334 19 2011-01-19 27 335 19 2011-01-12 27 338 19 2010-12-22 27 341 19 2010-12-01 27 331 19 2011-02-09 26 16 17 2013-04-10 22 87 17 2011-11-09 19 30 17 2013-01-02 17 37 17 2012-11-07 17 47 17 2012-08-29 17 31 17 2012-12-26 16 56 17 2012-06-20 16 10 17 2013-05-22 15 27 17 2013-01-23 15 61 17 2012-05-16 15 And when I run from my command_line: In [15]: beds_top_ten('beds.csv',17) Out[15]: 16 2013-04-10 87 2011-11-09 30 2013-01-02 37 2012-11-07 47 2012-08-29 31 2012-12-26 56 2012-06-20 10 2013-05-22 27 2013-01-23 61 2012-05-16 Name: Bed Census Date, dtype: datetime64[ns] Yet when I run the same code on the online environment, I get the following error: /usr/local/lib/python2.7/unittest/suite.py:108: DtypeWarning: Columns (10,45) have mixe…
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: error-handling
possible better answer: http://stackoverflow.com/a/46798244
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46798352
accepted answer: http://stackoverflow.com/a/46798352
has answer: http://stackoverflow.com/a/46798244
has comment: http://stackoverflow.com/comment/80542817
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/80541439
tagged with: pandas

http://stackoverflow.com/comment/82004032
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46840976
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159954/discussion-between-matthew-berryman-and-sreehari-r).

http://stackoverflow.com/q/46848413
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/46854829
tagged with: python
type: AnsweredQuestion
tagged with: linear-regression
type: Question
tagged with: lasso-regression
has title: Access the regularization paths obtained from ElasticNetCV in sklearn
has answer: http://stackoverflow.com/a/46854829
score: 0
has body: I would like to get these plots: http://scikit-learn.org/stable/auto_examples/linear_model/plot_lasso_coordinate_descent_path.html from an elastic net I have already trained. The example does from sklearn.linear_model import lasso_path, enet_path from sklearn import datasets diabetes = datasets.load_diabetes() X = diabetes.data print("Computing regularization path using the elastic net...") alphas_enet, coefs_enet, _ = enet_path( X, y, eps=eps, l1_ratio=0.8, fit_intercept=False) which basically requires recomputing from X,y the whole model. Unfortunately, I do not have X,y. In the training I have used sklearn.linear_model.ElasticNetCV which returns: coef_ : array, shape (n_features,) | (n_targets, n_features) parameter vector (w in the cost function formula) mse_path_ : array, shape (n_l1_ratio, n_alpha, n_folds) Mean square error for the test set on each fold, varying l1_ratio and alpha. while I would need parameter vector varying l1_ratio and alpha. Can this be done without recomputation? It would be a tremendous waste of time as those coef_paths are actually calculated already

http://stackoverflow.com/q/46753638
accepted answer: http://stackoverflow.com/a/46757244
has body: I have automated a task which fills in a web form from a text file. This text file can grow quite big and using the send_keys() function in selenium + python3 takes quite a while. Is there a much faster alternative, much like how copy/paste works? This is how I'm using it in my script: reportFile = open(reportFilePath,'r') for line in reportFile.read(): messageElem.send_keys(line) reportFile.close() I have looked online and there are alternatives but only in JS. I am looking for a faster way of adding the text from the file specifically with python 3.
has title: Is there a faster alternative to Selenium's send_keys in python 3?
tagged with: sendkeys
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46757244
tagged with: python
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80452977
has comment: http://stackoverflow.com/comment/80456487
tagged with: selenium
tagged with: file
type: Question

http://stackoverflow.com/comment/80611638
type: AnswerComment
comment on: http://stackoverflow.com/a/46831513
type: Comment
has text: thanks sooooo much for the response! Can you look at the update I have? TIA
score: 0

http://stackoverflow.com/a/46805565
answers question: http://stackoverflow.com/q/46805462
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: On Unix systems, the folder separator is /, while on Windows systems, the separator is \. Unfortunately this \ is also an escape character in most programming languages and text based formats (including C, Python and many others). Strangely enough a / character is not allowed in windows paths. So Python on windows is designed to accept both / and \ as folder separator when dealing with the filesystem, for convenience. But the \ must be escaped by another \ (unless of course you use raw strings like r'backslashes are now normal characters \\\ !') Selenium, on the other hand, will write values into Firefox preferences, which, unlike Python, expects the appropriate kind of separator. That's why using forward slashes does not work in your example.
has comment: http://stackoverflow.com/comment/80559759
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/80558220
accepted answer of: http://stackoverflow.com/q/46805462

http://stackoverflow.com/comment/80666075
has text: https://github.com/kokjo/universalrop is one of the examples I was going off of. I sadly cannot comprehend the z3 part of it. It appears he is converting each state transition into a z3 constraint, but how he is telling z3 to pick and choose between them is beyond me.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46859001
score: 0

rest
tags question: http://stackoverflow.com/q/46872424
tags question: http://stackoverflow.com/q/46757761
tags question: http://stackoverflow.com/q/46897272
tags question: http://stackoverflow.com/q/46755042
tags question: http://stackoverflow.com/q/46860183
tags question: http://stackoverflow.com/q/46826501
tags question: http://stackoverflow.com/q/46827441
tags question: http://stackoverflow.com/q/46784976
type: Tag
tag name: rest
tags question: http://stackoverflow.com/q/46782261
tags question: http://stackoverflow.com/q/46874388
tags question: http://stackoverflow.com/q/46773770

http://stackoverflow.com/comment/80751567
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46902365
score: 0
has text: Possible duplicate of [How do I remove leading whitespace in Python?](https://stackoverflow.com/questions/959215/how-do-i-remove-leading-whitespace-in-python)

http://stackoverflow.com/q/46825760
tagged with: date
type: Question
downvote count: 0
tagged with: sorting
answer count: 2
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80599105
has answer: http://stackoverflow.com/a/46825947
has comment: http://stackoverflow.com/comment/80599157
has body: UPDATED QUESTION I am trying to sort the dates in two date columns of a csv using Python (and Pandas preferably). For the first one, I want to get the oldest date. For the second one, I want to get the most recent one. My code with a static list works fine: timestamps = ['08/04/2017', '08/09/2017', '08/03/2017'] sortedDates = timestamps.sort(key=lambda x: time.mktime(time.strptime(x,"%m/%d/%Y"))) 01) First I load the data for row in csv.reader(open('myFile.csv')): if row[4] == '56886': key = row[4] #key = (row[4], row[33][:4], row[4]) startDate = row[19] xxxxx[key] = xxxxx.setdefault(key, 0) + float(row[33]) 02) Then I am trying to sort the Start Date df = pandas.read_csv('Bionic.csv', parse_dates=['Start Date']) df2 = df.dropna(subset=["Start Date"]) df2['Start Date'].apply(lambda x: time.mktime(time.strptime(x,"%m/%d/%Y"))) print(df2) and I am getting this error: sys:1: DtypeWarning: Columns (10,51,60,68,74) have mixed types. Specify dtype option on import or set low_memory=False. 03) Then I tried this: df = pandas.read_csv('myFile.csv', parse_dates=['Start Date']) df = df.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x) and I am getting the same error. 04) When I try this, I am getting the "None" values as there are empty fields for this column: startDate = startDate.split() minStartDate = startDate.sort(key=lambda x: time.mktime(time.strptime(x,"%m/%d/%Y"))) print(minStartDate)
favorite count: 0
possible better answer: http://stackoverflow.com/a/46825905
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46825905
type: AnsweredQuestion
has title: Print the the oldest and newest date from a csv column - Sort csv by date
score: 1
accepted answer: http://stackoverflow.com/a/46825947

http://stackoverflow.com/comment/80637613
score: 1
comment on: http://stackoverflow.com/q/46824143
has text: Hi @DavidW. I tried that route, and I can get a compilable main .c file. However, the cythonize method still produces a non-standalone main.so file. If I compile the produced main.c it works. I'm dashing through the docs, but I don't know what I'm missing...
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80466867
comment on: http://stackoverflow.com/q/46760753
score: 0
type: Comment
has text: what is the string?
type: QuestionComment

http://stackoverflow.com/q/46824027
tagged with: postgresql
possible better answer: http://stackoverflow.com/a/58096999
has answer: http://stackoverflow.com/a/70695980
tagged with: django-import-export
has answer: http://stackoverflow.com/a/58096999
tagged with: python
upvote count: 4
has title: Django Import-Export Import Duplicate key value violates Error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80596139
downvote count: 0
has comment: http://stackoverflow.com/comment/80596999
has comment: http://stackoverflow.com/comment/80596919
has comment: http://stackoverflow.com/comment/80595857
tagged with: django
has comment: http://stackoverflow.com/comment/80595967
type: Question
has comment: http://stackoverflow.com/comment/80595567
has comment: http://stackoverflow.com/comment/80595818
has comment: http://stackoverflow.com/comment/80596146
has comment: http://stackoverflow.com/comment/80595799
tagged with: django-models
score: 4
accepted answer: http://stackoverflow.com/a/46842745
has comment: http://stackoverflow.com/comment/80596897
has body: I'm working on a project with Django 1.10, Python 3.6 and PostgreSQL as the database backend, in which I have a model called 'Article" and I need to import data from CSV files. I have imported my first CSV file successfully with the following fields: id, link &amp; category It's ID fields starts from 1 to 1960 then in next file, I have started ID field from 1961 to onward but it shows the following error: Line number: 1961 - duplicate key value violates unique constraint "article_article_pkey" DETAIL: Key (id)=(1961) already exists. Even when i see my Article model in Django admin it shows IDs from 1- 1960 Here's my models.py: class Article(models.Model): id = models.AutoField(primary_key=True) link = models.URLField(max_length=255) category = models.CharField(max_length=255, choices=Categories) Here's admin.py @admin.register(Article) class ArticleAdmin(ImportExportModelAdmin): resource_class = views.ArticleResource readonly_fields = ('id',)
linked to: http://stackoverflow.com/q/4678110
answer count: 3
has answer: http://stackoverflow.com/a/46842745
favorite count: 0

http://stackoverflow.com/q/46868702
has answer: http://stackoverflow.com/a/47373155
has comment: http://stackoverflow.com/comment/80792499
tagged with: aws-api-gateway
tagged with: amazon-web-services
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47373155
has title: Robot Framework - AWS API Gateway secured by IAM
has answer: http://stackoverflow.com/a/46921567
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/46921567
has body: Background I've been using Robot Framework and RequestsLibrary to write automated tests against RESTful endpoints I expose via AWS API Gateway. So I'm writing tests that look roughly like this: *** Settings *** Library Collections Library RequestsLibrary *** Test Cases *** Get Requests Create Session Sess https://&lt;api-gateway-url&gt; ${resp}= Get Request Sess /path/to/my/api?param=value Should Be Equal As Strings ${resp.status_code} 200 Dictionary Should Contain Value ${resp.json()} someValueIwantToVerify Now, I'm getting around to securing those API Gateway endpoints with IAM. Therefore requests need to be sig4 signed. The application that consumes these services is written in javascript, and uses aws-api-gateway-client to sign requests. Testing (manually) in Postman is also easy enough, using AWS Signature Authorization type. However, I'm struggling with figuring out a strategy for Robot Framework. Question(s) In the broadest sense, I'm wondering if anyone else is using Robot Framework to test IAM secured API Gateway endpoints. If so, how did you pull it off? More specifically: Is there an existing Robot Framework library that addresses this use case? If not, is writing my own library my only option? If I am stuck writing a library (this looks promising), what sorts of keywords would I define, and how would I use them?
tagged with: python-requests
type: Question
tagged with: robotframework

http://stackoverflow.com/q/46888213
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80753388
tagged with: airflow
has comment: http://stackoverflow.com/comment/80737041
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/80766723
favorite count: 0
has title: Task is not being scheduled as expected in Airflow
has comment: http://stackoverflow.com/comment/80735053
has comment: http://stackoverflow.com/comment/80778875
tagged with: python
tagged with: airflow-scheduler
has comment: http://stackoverflow.com/comment/80740611
score: 2
has body: Here's the hello-world dag python file defined: default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2017, 10, 23, 11, 25), 'email': ['airflow@airflow.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 0, 'retry_delay': timedelta(minutes=1), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, # 'end_date': datetime(2016, 1, 1), } dag = DAG('test_jason_1', default_args=default_args, schedule_interval="@daily") # t1, t2 and t3 are examples of tasks created by instantiating operators t1 = BashOperator( task_id='print_date', bash_command='echo "123" &amp;&amp; exit 1', dag=dag) Current datetime from command line (same machine as where Airflow is installed) is: [ec2-user@ip-10-0-0-XXX print_date]$ date Mon Oct 23 11:24:56 UTC 2017 but after 11:25:00, this job is still not scheduled accordingly. Could anyone help correct me if i'm wrong? Thanks! P.S. I changed schedule_interval to timedelta(minutes=5), and current time is 2017-10-23 12:36, then I could see the logs' time as in the right, which is confusing. Any explanations?
has comment: http://stackoverflow.com/comment/80736942
answer count: 0

http://stackoverflow.com/comment/80656819
type: Comment
comment on: http://stackoverflow.com/a/46854602
type: AnswerComment
score: 0
has text: Working Fine, Thank you sir :)

http://stackoverflow.com/q/46834732
has title: Convert pandas datetime column yyyy-mm-dd to YYYYMMDD
has comment: http://stackoverflow.com/comment/80617235
score: 15
tagged with: pandas
tagged with: datetime
possible better answer: http://stackoverflow.com/a/75910339
upvote count: 15
has answer: http://stackoverflow.com/a/75910339
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46834881
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80617137
has body: I have a dataframe with datetime column in the format yyyy-mm-dd. I would like to have it in integer format yyyymmdd. When I try: x=dates.apply(dt.datetime.strftime('%Y%m%d')).astype(int) I keep getting an error: TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str' This doesn't work if I try to pass an array. I know that if I pass just on element it will convert, but what is a more pythonic way to do it? I did try using lambda but that didn't work either.
downvote count: 0
has answer: http://stackoverflow.com/a/46834881
has comment: http://stackoverflow.com/comment/80617241
tagged with: dataframe
type: Question
answer count: 2

http://stackoverflow.com/comment/80717523
comment on: http://stackoverflow.com/q/46885031
type: Comment
has text: Why are you limited to brute force? Could you try using something like `scipy.optimize`?
score: 2
type: QuestionComment

http://stackoverflow.com/a/46906966
type: Answer
downvote count: 0
score: 1
has body: Changing the default element type will be available in Abaqus/CAE 2018. In the meantime, the following function can be added to the custom_v6.env. (C:\Program Files\Dassault Systemes\SimulationServices\V6R2017x\Abaqus\win_b64\SMA\site\custom_v6.env) def onCaeStartup(): import methodCallback from mesh import ElemType from job import ModelJobType ## Function to be called when an input file is written def checkElementType(callingObject, arguments, keywordArguments, userData): print 'Checking element types in the model' # Get the name of the job from the command a = str(callingObject).split("jobs['")[1] job = a.split("']")[0] model = mdb.jobs[job].model ra = mdb.models[model].rootAssembly # Query the Element Types in the assembly and display them elemType=[] for instance in ra.instances.keys(): for cell in ra.instances[instance].cells: if ra.getElementType(region=cell,elemShape=HEX).elemCode not in elemType: elemType.append(ra.getElementType(region=cell,elemShape=HEX).elemCode) print 'INSTANCE: '+instance +' = '+ ra.getElementType(region=cell,elemShape=HEX).elemCode # Define the callback. When the writeInput method is called on a ModelJobType object, the function checkElementType is executed. methodCallback.addCallback(ModelJobType, 'writeInput', checkElementType)
accepted answer of: http://stackoverflow.com/q/46889296
answers question: http://stackoverflow.com/q/46889296
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/80496030
type: QuestionComment
comment on: http://stackoverflow.com/q/46774696
type: Comment
score: 0
has text: What you've linked doesn't say that you are not allowed to use loops.

http://stackoverflow.com/comment/80743369
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46897852
has text: I'm sure it's a duplicate; I've seen some similar questions. But I'm pretty new at this, and the concepts are clicking, so a similar question is tough for me to completely follow. I'll check out some of the links posted.
type: Comment

http://stackoverflow.com/comment/80716540
has text: I will edit my post.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46884276

http://stackoverflow.com/comment/80682762
has text: I do not recommend anything. Probably you have to try out some combinations. My comment was meant for you to improve the question by stating in how far those suggested methods are or aren't helping.
comment on: http://stackoverflow.com/q/46867474
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46876092
has comment: http://stackoverflow.com/comment/80700618
type: Question
has answer: http://stackoverflow.com/a/46876377
has body: When I execute python myscript.py -i -i myfile.txt The output should be: info from file info from file So everytime it comes across a flag a peice of code is executed even if it is outputting the same data. At the moment it just prints: info from file parser = argparse.ArgumentParser() parser.add_argument('-i', help="info", action='store_true') parser.add_argument('filename', nargs='+') results = parser.parse_args() if results.i: print("info from file")
score: 0
answer count: 2
has title: Python: Handling multiple flags with argparse
tagged with: argparse
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46877280
tagged with: python

http://stackoverflow.com/comment/80678745
score: 0
type: Comment
type: QuestionComment
has text: I tried running, but the original intent to use apache was to retain the session. I am not the author of this python code, so I don't know why it doesn't complete all the tasks. So I will have to revert back to apache. I am going to try mod_reqtimeout parameters.
comment on: http://stackoverflow.com/q/46863628

http://stackoverflow.com/q/46865459
answer count: 1
has body: I want to create a function with two arguments which return some specific name from a Names column. The first argument is an existing dataframe and the second argument is name. I know how to pull specific values from rows but putting it in multi-argument functions is my issue: def returnDataForOneName(namesDF, name): for string in name: ?--&gt; return [string.values() for string in namesDF] I would like to test the function with one of my existing csv files: import pandas as pd datapath = 'C:\Users\namefile.csv' namesDF = pd.read_csv(datapath) newDF = returnDataForOneName(nameDF, 'Tim')
has answer: http://stackoverflow.com/a/46865493
type: UnansweredQuestion
tagged with: pandas
tagged with: function
has title: Python function to return column values from a dataframe
has comment: http://stackoverflow.com/comment/80678315
tagged with: python-3.x
type: Question
tagged with: python
score: 0

http://stackoverflow.com/q/46822985
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
has body: I have a python list objects that looks like this: {'word1':#, 'word2':#, 'word3':#, 'class':'pos'} {'word2':#, 'word4':#, 'word5':#, 'word6':#, 'class':'neg'} Where each row has a list of words and their word counts from lines in a file, and the last list item is always either pos (positive) or neg (negative). (This is for sentiment analysis). I'm trying to convert this to a dataframe, where each column is ALL the posible words from each row in the list. And each row has the word count for that item: df: row word1 word2 word3 word4 word5 word6 class 1 # # # 0 0 0 pos 2 0 # 0 # # # neg How do I go about that? I've tried directly converting it to a dataframe using df = pd.DataFrame(list) but I dont see the class column in my data and I get multiple columns for the same word.
type: AnsweredQuestion
has title: How to convert list of word counts into dataframe for sentiment analysis
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/46827880
accepted answer: http://stackoverflow.com/a/46827880
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/80593472

http://stackoverflow.com/comment/80616534
has text: Passing a string to `find` method searches for the tag whose name matches the string. So, when you call `each.find('title_box')`, you're trying to find a `title_box` tag. Are you sure that's what you want? If it's the value of a `class` attribute, you should use `each.find(attrs={'class': 'title_box'})`.
comment on: http://stackoverflow.com/q/46833212
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/80718280
comment on: http://stackoverflow.com/a/46885272
type: Comment
score: 0
type: AnswerComment
has text: I actually messed it up myself, it seems. I had it with `return False`, but now I would only get `[True, True, False, False]`, but this doesn't tell me *which* words, so I figured if I just returned the actual false elements only I could easily find them. It doesn't seem to work however..

http://stackoverflow.com/comment/80692788
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46867849
has text: Thank you..But your code is checking whether number of rows are equal or not..i need to compare contents of first 2 columns of both arrays and retrieve the matching indexes and i also need to loop through all the rows of array to compare.. Here are my sample arrays: array1=[''1","4","Lord of the Day of Judgment!''] array2=["1","4","مَالِكِ يَوْمِ الدِّينِ"]
score: 0

http://stackoverflow.com/comment/81032282
has text: What is the "entity"? It's not a .csv file, because it doesn't have comma-separated values. It looks like malformed XML. What function returns that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46794306

http://stackoverflow.com/a/46819514
has comment: http://stackoverflow.com/comment/80587555
has comment: http://stackoverflow.com/comment/80587574
answers question: http://stackoverflow.com/q/46819433
has comment: http://stackoverflow.com/comment/80586766
score: 0
type: Answer
has body: regex will work depending on if this is the only format the numbers are in. Also, do you know if the positive sign is shown or it only shows negative? If it does show positive... ([+-][\d]{3})&lt;\/b&gt; If it doesn't show positive use... ([+-]?[\d]{3})&lt;\/b&gt; http://regexr.com/3h08d You should be able to extract the contents inside the round brackets. Edit: you probably want to do something like below. This code will get each string from the list and then do a regex search on the string. It will append the result to the nums list. The result will be a 3 digit number with the sign in front, since it extracts the first group inside the round brackets. import re nums = [] for line in odds: result = re.search(('[+-][\d]{3})&lt;\/b&gt;',line) nums.append(result.group(1))) print (nums)
has comment: http://stackoverflow.com/comment/80586988

http://stackoverflow.com/comment/80533128
type: Comment
comment on: http://stackoverflow.com/a/46792879
type: AnswerComment
has text: @jezrael interesting... I'll sure spend some time testing :)
score: 0

http://stackoverflow.com/q/46818102
has comment: http://stackoverflow.com/comment/80583746
has comment: http://stackoverflow.com/comment/80584626
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80583686
has comment: http://stackoverflow.com/comment/80584029
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80585012
tagged with: python
has comment: http://stackoverflow.com/comment/80585153
answer count: 0
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/80583606
tagged with: pyqt5
downvote count: 1
type: Question
has title: Changing layout - widgets in PyQt5
has comment: http://stackoverflow.com/comment/80585241
has comment: http://stackoverflow.com/comment/80585217
has body: This is my first trial in PyQt5 (no previous experience in creating GUI in Python, but I have written a few programs using Python). My problem is changing window content after a button click. I have created my main class: class GUI(QMainWindow): def __init__(self): super().__init__() self.centralWidget = QStackedWidget() self.setCentralWidget(self.centralWidget) self.psuE3631A = E3631A() self.init_gui() def init_gui(self): self.initGUI = initGUI(self) self.setWindowTitle('Control panel - E3631A') self.centralWidget.addWidget(self.initGUI) self.show() def simple_gui(self): self.simpleGUI = simpleGUI(self) self.setWindowTitle('Control panel - E3631A') self.centralWidget.addWidget(self.simpleGUI) self.centralWidget.setCurrentWidget(self.simpleGUI) self.show() def advanced_gui(self): pass def close_window(self): print_comment("Exit application") self.close() and I am trying to switch beetwen initGUI and simpleGUI. simpleGUI: class simpleGUI(QWidget): def __init__(self, parent=None): super(simpleGUI, self).__init__(parent) print_comment("GUI in simple mode!") layout = QGridLayout() btn_close = QPushButton("&amp;Exit app", self) btn_close.clicked.connect(self.parent().close_window) layout.addWidget(btn_close, 0, 1) layout.addWidget(btn_close, 1, 1) layout.addWidget(btn_close, 2, 0) layout.addWidget(btn_close, 2, 2) self.setLayout(layout) initGUI: class initGUI(QWidget): def __init__(self, parent=None): super(initGUI, self).__init__(parent) self.psuE3631A = self.parent().psuE3631A print_comment("GUI initialize mode!") layout = QGridLayout() self.ComboBoxPorts = QComboBox(self) self.ComboBoxPorts.setToolTip("Select port to connect with device - only psu E3631A will be connected!") self.init_comboBoxPorts() self.scan_ports() lbl_version = QLabel("ver " + VERSION) lbl_version.setAlignment(Qt.AlignRight) btn_refresh = QPushButton("&amp;Refresh ports", self) btn_refresh.clicked.connect(self.refresh_port_list) self.btn_connect = QPushButton("&amp;Connect", self) self.btn_connect…
tagged with: pyqt

http://stackoverflow.com/comment/80605069
score: 0
type: Comment
type: AnswerComment
has text: @COLDSPEED Thanks for `sys.getrefcount`. The idea of `my_del` is basically a `del` that does not issue a NameError exception if the variable is unassigned. It is not really about how useful it is, it is more about how to implement it.
comment on: http://stackoverflow.com/a/46828651

http://stackoverflow.com/comment/80637499
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46804151
score: 0
has text: After a full 2 days of debugging, I think I figured out the issue. I had some ints mixed with floats somewhere, and it was killing off the gradient, setting them all to 0 apparently when the weights were set too small. This issue was so difficult to debug. I implemented gradient checking and even then, everything seemed fine for quite several iterations before an error showed up. Thanks for the help!

http://stackoverflow.com/a/46801251
type: Answer
has body: import cv2 import numpy as np img = None with open('digit_0.txt', 'r') as digit_stream: for row_data in digit_stream: row_data = row_data.replace('\n', '') row_img = np.zeros((1, len(row_data)), dtype=np.uint8) for idx, bit in enumerate(row_data): if bit == '1': row_img[0, idx] = 255 else: row_img[0, idx] = 0 if img is None: img = row_img else: img = np.vstack((img, row_img)) cv2.namedWindow('img', cv2.WINDOW_NORMAL) cv2.imshow('img', img) cv2.waitKey() Try this :)
answers question: http://stackoverflow.com/q/46800232
score: 0

http://stackoverflow.com/a/46750054
has body: A few things here. First of all, fix that indentation. Python is really specific about whitespace. Assuming you fix the indentation, you'll come into a couple of other issues. In your main method, you want to be calling c.add(d) (I think). You're probably running into an error on line 9, which is the error I think you're talking about. In the scope of your method, the variable a doesn't exist yet. self.a does, though. You probably mean to print self.a. As a side note, class names in Python should start with an uppercase letter. Numbers are allowed, but I'd really try and avoid them.
answers question: http://stackoverflow.com/q/46749969
type: Answer
score: 0

http://stackoverflow.com/comment/80457975
comment on: http://stackoverflow.com/q/46756326
score: 0
type: Comment
type: QuestionComment
has text: are you trying to change dates from `yyyy-mm-dd` to `yyyy-dd-mm`?

http://stackoverflow.com/q/46836564
downvote count: 0
tagged with: psutil
favorite count: 0
has title: Error importing psutil in PyCharm Google App Engine Project
tagged with: pycharm
has body: I have recently run into an import error with psutils in the types.py called from google.cloud.pubsub_v1 on a GAE standard project inside Pycharm. I messed around for a day trying to find away around it, but no go. psutil imports in python run from the terminal and the console and from a vanilla python project but not from a GAE project. To double up on this I made a basic test of the two as seen below: Both using the same virtualenv... Standard Vanilla Python Project: main.py contains import psutil def x(): print "hello world" if __name__ == "__main__": x() Google App Engine Project - main.py contains import webapp2 import psutil class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) The import in the vanilla python project works fine, but the import in the GAE app returns the traceback: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/Users/chez 1/google-app-engine-projects/untitled/main.py", line 18, in &lt;module&gt; import psutil ImportError: No module named psutil Has anyone had similar problems and found a fix?
linked to: http://stackoverflow.com/q/26069254
type: UnansweredQuestion
tagged with: google-app-engine
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52920865
score: 1
type: Question
has answer: http://stackoverflow.com/a/46841177
answer count: 2

http://stackoverflow.com/q/46818471
tagged with: python
tagged with: editor
answer count: 0
has comment: http://stackoverflow.com/comment/80585018
has comment: http://stackoverflow.com/comment/80603887
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80603849
has body: So I have just downloaded and installed WinPython. I have included the directory to my Path (it probably sounds very dumb, but I don't even know what this means. I was just told this is important and so I have followed a tutorial). Now, when I open the Spyder editor the editor never stops loading. It opens, but I can't do anything with it, because it just won't react. I have no clue whatsoever what I did wrong!
has title: WinPython: Spyder keeps breaking down
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80603881
tagged with: spyder

http://stackoverflow.com/q/46774684
tagged with: python
has body: I have a dataframe as show below +++++++++++++++++++++ colA | colB | colC | +++++++++++++++++++++ 123 | 3 | 0| 222 | 0 | 1| 200 | 0 | 2| I want to replace the values in colB and colC with a value of 1 if they are greater than 0. I am able to use the na.fill function if I need to fill nulls with 0. But I am not sure how to do this.
accepted answer: http://stackoverflow.com/a/46774810
type: AnsweredQuestion
type: Question
tagged with: pyspark
has answer: http://stackoverflow.com/a/46774810
score: 0
answer count: 1
has title: PySpark: Replace values of dataframe based on criteria

http://stackoverflow.com/a/46895784
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46869640
answers question: http://stackoverflow.com/q/46869640
downvote count: 0
has body: One way to obtain k flat clusters is to use scipy.cluster.hierarchy.fcluster with criterion='maxclust': from scipy.cluster.hierarchy import fcluster clust = fcluster(Z, k, criterion='maxclust')
type: AcceptedAnswer
score: 4
type: Answer

http://stackoverflow.com/comment/80587094
type: AnswerComment
has text: @ShwSvn Please read this to have a better understanding of your current problem. https://stackoverflow.com/a/35444608/1666143
type: Comment
comment on: http://stackoverflow.com/a/46819464
score: 0

http://stackoverflow.com/comment/80621165
type: AnswerComment
has text: @DiegoGuedes-Sobrinho Done.
comment on: http://stackoverflow.com/a/46835175
type: Comment
score: 0

http://stackoverflow.com/q/46881328
has comment: http://stackoverflow.com/comment/80709951
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/59308800
has answer: http://stackoverflow.com/a/52580581
tagged with: mask
has comment: http://stackoverflow.com/comment/80710004
tagged with: ip
type: Question
has comment: http://stackoverflow.com/comment/80710261
has comment: http://stackoverflow.com/comment/80710361
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/46881538
downvote count: 0
has comment: http://stackoverflow.com/comment/80710439
upvote count: 3
has answer: http://stackoverflow.com/a/46881538
has answer: http://stackoverflow.com/a/76332067
has title: Determine Network IP when given an IP and subnet mask
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/59308800
tagged with: python
has comment: http://stackoverflow.com/comment/80710303
has body: In Python, if I have an IP address and a subnet mask as string, how do I determine the network IP? i.e. IP = 10.0.0.20, mask = 255.255.255.0 would result in a network IP of 10.0.0.0
has comment: http://stackoverflow.com/comment/80710386

http://stackoverflow.com/comment/80675494
score: 0
type: Comment
type: QuestionComment
has text: @Jon Clements I did not notice that! I hate when that happens. :P I have not edited your answer in case you were doing it at the same time. Many thanks. It seems to be working.
comment on: http://stackoverflow.com/q/46863079

http://stackoverflow.com/comment/80693758
has text: What precisely makes an image white or yellow?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46873344

http://stackoverflow.com/a/46874403
answers question: http://stackoverflow.com/q/46874324
type: Answer
upvote count: 2
score: 2
has body: Use double nlargest - first for get 2 top values and then sum them first and then for another top 2 index values: L = df.groupby('PrimaryName')['Value'] .apply(lambda x: x.nlargest(2).sum()) .nlargest(2) .index .tolist() print (L) ['PN1', 'PN0'] Detail: print (df.groupby('PrimaryName')['Value'].apply(lambda x: x.nlargest(2).sum())) PrimaryName PN0 11 PN1 13 PN2 5 Name: Value, dtype: int64 Or: L = df.sort_values('Value', ascending=False) .groupby('PrimaryName')['Value'] .apply(lambda x: x.head(2).sum()) .nlargest(2) .index .tolist()
accepted answer of: http://stackoverflow.com/q/46874324
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46798124
tagged with: pandas
tagged with: python
has title: Pandas Merge columns of a pivot table
has answer: http://stackoverflow.com/a/46799093
has body: I generated a pandas pivot table that looks like this: Encounters Code 132 133 145 Record Number Start_date End_date Service_Date 2322 1/1/2017 1/3/2017 1/1/2017 0 1 1 1/2/2017 1 0 0 1/3/2017 0 1 1 I would like to merge and sum some of the pivot table columns based on the Code Desired output: Encounters Code 132 133-145 Record Number Start_date End_date Service_Date 2322 1/1/2017 1/3/2017 1/1/2017 0 2 1/2/2017 1 0 1/3/2017 0 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46799093
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/80544117
score: 0

http://stackoverflow.com/comment/80539547
score: 0
type: Comment
type: QuestionComment
has text: Actually, no, this is quite a difference so I would like to look into it :) Also, I have got rid of `eval` and cast the input to `int` instead. Please don't use `eval`: https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
comment on: http://stackoverflow.com/q/46796266

http://stackoverflow.com/q/46767818
has answer: http://stackoverflow.com/a/46768031
tagged with: generator-expression
has body: I am trying to delete all the first element of a list that are equals among themselves, but I found my code ugly. Here an example: my_list = [1,1,1,9,9,2] become my_list = [1,9,9,2] for spot_prec, spot in zip(my_list, my_list[1:]): if spot_prec == spot: del spot_prec else: break How to compact it? I heard about generator expression, but I have a problem to include my else break statement.
type: Question
has comment: http://stackoverflow.com/comment/80480981
has comment: http://stackoverflow.com/comment/80480985
has title: How to merge a for loop with an if-else statement?
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80481129
tagged with: python

http://stackoverflow.com/comment/80534949
has text: @RonNorris a way to do it automatically for every loop ?
comment on: http://stackoverflow.com/q/46794017
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92781034
type: Comment
comment on: http://stackoverflow.com/a/46784943
has text: Do you mean `tf.squared_difference(a,b)` without squared root?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80683755
has text: Are you sure your input file was pristine before trying it? If you were using a stale copy, it would simply propagate the problem.
score: 0
comment on: http://stackoverflow.com/q/46868154
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46768314
has comment: http://stackoverflow.com/comment/80494188
has comment: http://stackoverflow.com/comment/80487973
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80495646
answer count: 0
has comment: http://stackoverflow.com/comment/80494543
has comment: http://stackoverflow.com/comment/80496225
tagged with: pyqt5
tagged with: live
type: Question
has body: I need to plot in live with Qchart, but it didn't update with the code below. So I am searching the function or the slot which is responsable of plot update, so I will activate it by myself. def __init__(self, params): super().__init__() #init with params self.mycurv.append(QLineSeries(self)) self.addSeries(self.allCruvs[-1]) def plotData(self, Time, Values, color=None, curvIndex=0): self.mycurv.clear() lastTime = self.myZero for i, theTime in enumerate(Time): if (theTime &gt; lastTime + MININTERVALTIME): self.mycurv.append(lastTime - self.myZero, Values[i]) self.mycurv.append(theTime - self.myZero, Values[i]) lastTime = theTime self.update() if at the end in stead of self.update, I put : self.removeAllseries() self.addseries(self.mycurv) it is working in live for a while, and the the application crashes. All the class code is here : from PyQt5 import QtGui from PyQt5.QtGui import Qt from PyQt5.QtChart import QChart, QChartView, QLineSeries, QValueAxis import datetime MININTERVALTIME = 5 PENSIZE = 2.5 class chartClass(QChart): def __init__(self, params): super().__init__() #init with params self.allCruvs = [] self.allCruvs.append(QLineSeries(self)) self.addSeries(self.allCruvs[-1]) def plotData(self, Time, Values, color=None, curvIndex=0): #test new curv or clear the old one if (curvIndex &lt; len(self.allCruvs)): self.allCruvs[curvIndex].clear() else: curvIndex = len(self.allCruvs) self.allCruvs.append(QLineSeries(self)) self.addSeries(self.allCruvs[-1]) # Get max and min for time axe and title self.myZero = min(Time) self.myMax = max(Time) # define title dateFormat = '%m/%d %H:%M' myZeroSTR = datetime.datetime.fromtimestamp(int(self.myZero)).strftime(dateFormat) myMaxSTR = datetime.datetime.fromtimestamp(int(self.myMax)).strftime(dateFormat) self.allCruvs[-1].setName(self.type + " [ " + myZeroSTR + " - " + myMaxSTR + " ]") # define number of ticks // still in prehistoric way to do automatic new one maxDelta = round(max(Time) - self.myZero, 0) if (maxDelta &lt; 20)…
has comment: http://stackoverflow.com/comment/80495576
has title: what is the function or the slot which is responsable of plot update in QChart?
has comment: http://stackoverflow.com/comment/80496271
has comment: http://stackoverflow.com/comment/80496113
tagged with: qchart
score: 0
tagged with: pyqt

http://stackoverflow.com/comment/80506174
type: Comment
has text: @TomKarzes is efficiency the issue with `pow(i, 2)`?
type: AnswerComment
comment on: http://stackoverflow.com/a/46780068
score: 0

http://stackoverflow.com/a/51894355
has comment: http://stackoverflow.com/comment/96814221
score: 54
has body: Let me first put some general guidelines: Practically speaking, if you have a lot of features and lesser samples, Mahalanobis algorithm tends to give misleading results (you can try it yourself), so the more features you have, the more samples you should provide. The covariance matrix must be Symmetric and Positive Definite to make the algorithm works, so you should check before proceeding. As it's already mentioned, Euclidean Metric fails to find the correct distance because it tries to get ordinary straight-line distance. Thus, if we have multi-dimensional space of variables, two points may look to have the same distance from the Mean, yet one of them is far away from the data cloud (i.e. it's an outlier). The solution is Mahalanobis Distance which makes something similar to the feature scaling via taking the Eigenvectors of the variables instead of the original axis. It applies the following formula: where: x is the observation to find its distance; m is the mean of the observations; S is the Covariance Matrix. Refresher: The Covariance represents the direction of the relationship between two variables (i.e. positive, negative or zero), so it shows the strength of how one variable is related to the changes of the others. Implementation Consider this 6x3 dataset, in which each row represents a sample, and each column represents a feature of the given sample: First, we need to create a Covariance Matrix of the features of each sample, and that's why we set the parameter rowvar to False in the numpy.cov function, so each column now represents a variable: covariance_matrix = np.cov(data, rowvar=False) # data here looks similar to the above table # in the picture Next, we find the Inverse of the Covariance Matrix: inv_covariance_matrix = np.linalg.inv(covariance_matrix) But before proceeding, we should check, as mentioned above, if the matrix and its inverse are Symmetric and Positive Definite. We use for this Cholesky Decomposition Algorithm, which, fortunately, is a…
has comment: http://stackoverflow.com/comment/96813826
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/96814670
has comment: http://stackoverflow.com/comment/96813273
has comment: http://stackoverflow.com/comment/96814297
has comment: http://stackoverflow.com/comment/96814293
upvote count: 54
answers question: http://stackoverflow.com/q/46827580
has comment: http://stackoverflow.com/comment/124914688
has comment: http://stackoverflow.com/comment/128716174
has comment: http://stackoverflow.com/comment/90740049
has comment: http://stackoverflow.com/comment/116841225

http://stackoverflow.com/comment/80668854
type: Comment
type: QuestionComment
has text: Any specific reason for declaring functions inside a function ?
comment on: http://stackoverflow.com/q/46860671
score: 0

http://stackoverflow.com/q/46895000
possible better answer: http://stackoverflow.com/a/46900940
has body: I want to scrape the latitude and longitude of the restaurant from URL. I am able to scrape other information like name, ratings but not latitude and Longitude of the hotel. Help Me! I am attaching my code snippet. image On inspecting the map on webpage I get this but I am not able to fetch the coordinates from it.
has answer: http://stackoverflow.com/a/46903084
accepted answer: http://stackoverflow.com/a/46903084
has answer: http://stackoverflow.com/a/46900940
has title: scrape longitude and latitude from this html using scrapy
score: 0
tagged with: python
type: AnsweredQuestion
tagged with: scrapy
type: Question
answer count: 2

http://stackoverflow.com/comment/80476835
comment on: http://stackoverflow.com/q/46765421
has text: I edit answer, please check it.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80696057
type: QuestionComment
has text: why not read the EXIF information from the source image and write it to the destination image?
comment on: http://stackoverflow.com/q/46874544
score: 0
type: Comment

http://stackoverflow.com/q/46835245
tagged with: garbage-collection
has comment: http://stackoverflow.com/comment/80638780
type: Question
score: 3
has body: Consider the following minimal example: # used memory: Python2=7421 MB, Python3=7440 MB a = list(range(10**8)) # used memory: Python2=10553 MB, Python3=11317 MB a = 1 # used memory: Python2=9785 MB, Python3=7454 MB # ---&gt; why does Python2 need &gt;2GB of RAM here? # after python process terminates: Python2=7433 MB, Python3=7458 MB A large object is created which should be garbage collected after the second line. The memory usage has been monitored using free -m (this is not an exact measurement of course). Python 3 needs more memory (3.7GB instead of 3.05GB) to store the large object, but it does what I expected: memory usage drops after the object is not needed any longer. Python2 seems to delete only 768 MB and keep 2.3GB of memory allocated. Why? This is repeatable: if the list is created a second time, it will use again 3.05 GB, not more and it will drop again to 2.3GB RAM usage. gc.collect() returns 0 and does not change the amount of used memory. Please don't tell me to use Python 3 - I know... :) Some links to documentation which did not answer my question: https://docs.python.org/2/library/gc.html https://docs.python.org/2/c-api/memory.html
has title: Why does Python 2 consume a lot of memory even if there are no large objects referenced?
tagged with: memory
has comment: http://stackoverflow.com/comment/80637276
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46835345
favorite count: 0
has comment: http://stackoverflow.com/comment/80638368
tagged with: python
has comment: http://stackoverflow.com/comment/80618089
has comment: http://stackoverflow.com/comment/80618056
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/80503315
comment on: http://stackoverflow.com/q/46778710
score: 0
type: Comment
has text: Isn't it possible to know that, is a packet using HTTP (application layer protocol) or not ?
type: QuestionComment

http://stackoverflow.com/a/46841759
type: Answer
has body: You could do pd.bdate_range('21/12/2017', periods=10).tolist() Or, be more specific with pd.to_datetime(.., format=) pd.bdate_range(pd.to_datetime('21/12/2017', format='%d/%m/%Y'), periods=10).tolist()
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46841659
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46841659

http://stackoverflow.com/a/46830731
answers question: http://stackoverflow.com/q/46818865
has comment: http://stackoverflow.com/comment/80609120
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46818865
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80609159
has comment: http://stackoverflow.com/comment/80609684
type: Answer
has body: You should have only one series with two features. If A and B are lists (not numpy arrays): fullSeq = np.array(A + B) #this shape is (lenA + lenB,) fullSeq = fullSeq.reshape((2,len(A))) fullSeq = fullSeq.swapaxes(0,1).reshape((1,len(A),2)) #make sure that the resulting array is something like [[[1,0],[2,0],[3,1],...]] Now you have a single sequence with num_features=2. A and B get totally dependent now.
score: 1
has comment: http://stackoverflow.com/comment/80609408

http://stackoverflow.com/q/46871746
type: AnsweredQuestion
score: 0
has body: Before asking this question, I have searched SO, find several related links:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128), regarding reading in files But they are no useful for my post, all of them are about program, but mine is for installation. After I install the pip, I check the pip list: C:\Users\中jin>pip list DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning. pip (9.0.1) setuptools (28.8.0) When I install django use pip, I get the bellow error: C:\Users\中jin>pip install django Collecting django Exception: Traceback (most recent call last): File "C:\Python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Python27\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 821, in unpack_url hashes=hashes File "C:\Python27\lib\site-packages\pip\download.py", line 659, in unpack_http_url hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 880, in _download_http_url file_path = os.path.join(temp_dir, filename) File "C:\Python27\lib\ntpath.py", line 85, in join result_path = result_path + p_path UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128) EDIT-1 I am in Windows10, and python 2.7.
tagged with: pip
tagged with: django
linked to: http://stackoverflow.com/q/33295085
type: Question
has answer: http://stackoverflow.com/a/46871791
has title: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128)
answer count: 1
accepted answer: http://stackoverflow.com/a/46871791
tagged with: python

http://stackoverflow.com/comment/80458699
type: Comment
type: QuestionComment
score: 0
has text: Have you tried: `for d in data['root']['station']: print d['name']`
comment on: http://stackoverflow.com/q/46756686

http://stackoverflow.com/comment/80471348
has text: Send the account creation sms after the user was successfully created.
comment on: http://stackoverflow.com/q/46762918
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80754827
comment on: http://stackoverflow.com/a/46904094
type: Comment
has text: This is just a snippet of the data, if I drop na, it will affect the other columns in the data frame.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/96790502
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46844517
type: Comment
has text: why not `xml = open("import.xml", "w")`

http://stackoverflow.com/comment/136383161
score: 1
type: AnswerComment
type: Comment
has text: @XinNiu There are very few cases where you shouldn't use an intercept, and for most of those there are better statistical solutions, but theoretically if you know that X=0 implies Y=0, there may be a case for it. Consider an example like you are plotting your maximum run distance (y) against a given time (x). You know you can't run any distance in x=0, so perhaps a fixed at zero intercept is appropriate. Again, there are generally better modelling solutions.
comment on: http://stackoverflow.com/a/46781428

http://stackoverflow.com/comment/117762460
has text: I'm not sure where my responsibilities end between merely answering the original question directly and turning this answer into a perpetually relevant source of advice on security practices. I'm going to settle for a general disclaimer for now. Thanks for drawing my attention to this.
type: Comment
comment on: http://stackoverflow.com/a/46806097
score: 0
type: AnswerComment

http://stackoverflow.com/q/46850362
has comment: http://stackoverflow.com/comment/80648276
has comment: http://stackoverflow.com/comment/80648470
score: 0
has title: PHP exec() on Heroku is not working
tagged with: python
answer count: 0
has body: i have an app on heroku that calls a python script, on localhost this works fine, but when i push to heroku's server exec doesnt work. I'm using a simple code only for test. PHP $result = exec("python testscript.py"); Python def get_test(): return 2 if __name__ == "__main__": print get_test() Edit: im using Multiple Buildpacks, my app is configured to use php and python
type: UnansweredQuestion
tagged with: php
has comment: http://stackoverflow.com/comment/80649256
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/80648087
has comment: http://stackoverflow.com/comment/80648206

http://stackoverflow.com/comment/80541192
has text: You can split cells
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46797224
score: 1

http://stackoverflow.com/a/71768822
has body: I ran into this as well, but in my case both DAGs were using the same schedule_interval, so none of the above suggestions helped. Turned out it was an Airflow bug. Templates in the external_task_id/external_task_ids fields are currently broken in v2.2.4: https://github.com/apache/airflow/issues/22782
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46807297

http://stackoverflow.com/a/46855310
has body: So, as I understand, the problem is that setuptools installs the internal dependencies into the local folder (.eggs if I remember correctly), not into the normal virtualenv that you use. And you do not like how setuptools does that. Neither do I, especially when I need a local DevPI server to be used (setuptools ignores that). So I do this way: setup( ... install_requires=['monotonic'], # just for example extras_require={ 'test': ['pytest', 'pytest-timeout'], 'docs': ['sphinx', 'alabaster'], }, ) When you need to test, assuming that you create and install virtualenv somehow: pip install -e .[test] Here, . is the current directory. -e mean editable mode (but can be omitted). [test] is a setuptools "extra". You can declare multiple "extras", and instal them as pip install mylib[ext1,ext2] if needed. Then you can run the tests either way: pytest python setup.py test The latter one is only if the test command is already configured to run pytest (see pytest integration manual). The trick is that if setuptools can find the test-dependencies in the current environment (virtualenv, pyenv, system python, whatever else), it will not install them as the eggs, and will just use the installed versions. Actually, you do not even need to declare tests_require= in that case, as the libraries are assumed to be installed into the virtualenv. If they were not, the test command will just fail. Similarly, you can pip install .[docs], and build your docs with sphinx-build ... command from the current virtualenv. Note that the install_requires are installed always, no matter with extras you add. So the app/lib itself will be always fully functional, importable and introspectable. Hopefully, this was the question (if I understood it correctly).
score: 6
downvote count: 0
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/46796011

query-string
tags question: http://stackoverflow.com/q/46832025
tag name: query-string
type: Tag

http://stackoverflow.com/a/46757424
accepted answer of: http://stackoverflow.com/q/46757247
answers question: http://stackoverflow.com/q/46757247
score: 0
type: AcceptedAnswer
type: Answer
has body: For convolution operation to make sense you need to give 3 dimensions. In your case you are giving (8000, 1) which is clearly not having 3 dimensions( it has 2). With information provided in question it is very difficult to exactly give you the dimensions, but your problem is mostly with dimensions. You should check your input dimensions while training.

http://stackoverflow.com/q/46762195
has body: while True: reply = raw_input("Enter text, (type [stop] to quit): ") print reply.lower() if reply == 'stop': break x = min(reply) y = max(reply) print("Min is " + x) print("Max is " + y) I'm trying to make a statement containing a while statement where it asks a series of input statements and takes them all and finds the min and max of all of the inputted numbers. Anyone have any solutions? I've been trying to work through the issue for a while without any luck. Thanks all!
has comment: http://stackoverflow.com/comment/80469736
has answer: http://stackoverflow.com/a/46762275
has comment: http://stackoverflow.com/comment/80469830
score: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/46762325
downvote count: 1
possible better answer: http://stackoverflow.com/a/46762275
has title: While Statement with Min & Max python
has answer: http://stackoverflow.com/a/46762341
answer count: 4
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/46762389
has answer: http://stackoverflow.com/a/46762325
has comment: http://stackoverflow.com/comment/80469810
type: Question
tagged with: python

http://stackoverflow.com/q/46858273
duplicate of: http://stackoverflow.com/q/8856117
tagged with: email
answer count: 0
downvote count: 0
tagged with: smtp
favorite count: 0
has body: Fairly frustrating - I put this in IDLE / terminal: import smtplib server = smtplib.SMTP('smtp.mail.com', 587) server.starttls() server.login("emailaddress@mail.com", 'password') msg = "duck" server.sendmail("emailaddress@mail.com", "emailaddress@mail.com", msg) Here's the annoying part - this worked twice, but then when I tried it a third time and thereafter, it just stopped working, getting the following error message: File "C:\Users\duck\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 880, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'emailaddress@mail.com': (550, b'Requested action not taken: mailbox unavailable\nFailure sending mail. Try again later')} I've tried emailing it to the same address I'm sending it from, and a different address - no cigar. The fact that it was working earlier - but suddenly stopped, does that mean that mail.com limits emails from being sent via smtp? How would I know what if this is a mail.com issue or something I can fix on my end? I've tried the 'ehlo' command before the starttls() - and it didn't work for me. This was suggested in some other questions about error 550.
type: Question
score: 3
tagged with: python
tagged with: tls1.2
upvote count: 3
linked to: http://stackoverflow.com/q/8856117
has comment: http://stackoverflow.com/comment/112071260
tagged with: smtplib
has comment: http://stackoverflow.com/comment/110353617
type: UnansweredQuestion
has title: smtplib.SMTPRecipientsRefused: How to fix smtplib error in Python?

http://stackoverflow.com/a/46770682
answers question: http://stackoverflow.com/q/46770177
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80487309
accepted answer of: http://stackoverflow.com/q/46770177
has comment: http://stackoverflow.com/comment/80488298
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: This will give you the location of your script. import os import sys script_location = os.path.split(os.path.realpath(sys.argv[0]))[0]

http://stackoverflow.com/comment/80502790
score: 0
type: Comment
type: QuestionComment
has text: @KlausD. I understand that and I am trying to implement Flask to call the method. However, it is not able to get the python file for some reason giving me a 404 error. I don't understand where the 404 error is coming from.
comment on: http://stackoverflow.com/q/46777222

http://stackoverflow.com/comment/80654443
type: Comment
has text: There *are no private fields* in Python. That is your fundamental misunderstanding. You are using double-underscore name-mangling, which it to prevent name-collisions in inherited classes, not to prevent access. As an aside, I hope you realize you are defining *class level variables*, equivalent to "static variables" in other languages, rather than instance variables.
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/46853442

http://stackoverflow.com/a/46902857
downvote count: 0
score: 1
has body: The script (or a Makefile) tries to invoke f2py-2.7 instead of f2py. If it is your script or you can easily adjust it, rename all f2py-2.7 to f2py. Otherwise you have to tell us more about the script and show the code of the script. As foodtooth says, make sure you have f2py 2.7 and not f2py-3, but I don't expect that to be a problem. You could also make a symlink f2py -> f2py-2.7 for the script.
answers question: http://stackoverflow.com/q/46901408
upvote count: 1
type: Answer

http://stackoverflow.com/a/46880817
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46876213
downvote count: 0
score: 1
has body: I tried the code you gave, and it worked well on my computer. import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import keras as K def mda(y_true, y_pred): s = K.equal(K.sign(y_true[1:] - y_true[:-1]), K.sign(y_pred[1:] - y_pred[:-1])) return K.mean(K.cast(s, K.floatx())) y = np.array([0, 1, 2, 1, 0, 1]) y_hat = np.array([0, 1, 0, 1, 0, 1]) plt.plot(y) plt.plot(y_hat, alpha=.6) plt.show() sess = tf.Session() print(sess.run(mda(tf.constant(y), tf.constant(y_hat))) What are your Tensorflow/Keras settings?

http://stackoverflow.com/comment/80509687
score: 1
has text: What martineau said. If ever you find yourself creating a whole series of numbered variables like your board1..board5 that's a sign that you're doing something wrong, and those boards should be items in a list, or perhaps a dict.
comment on: http://stackoverflow.com/q/46781180
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46801237
upvote count: 3
has comment: http://stackoverflow.com/comment/80549609
answers question: http://stackoverflow.com/q/46801175
has comment: http://stackoverflow.com/comment/80549632
has comment: http://stackoverflow.com/comment/80549469
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46801175
has body: For lists of lists, you can get your desired result like this: &gt;&gt;&gt; [s[1:3] for s in matrix[1:3]] [[6, 7], [10, 11]] &gt;&gt;&gt; &gt;&gt;&gt; [s[2:3] for s in matrix[1:4]] [[7], [11], [15]] &gt;&gt;&gt; Note that the latter is a vertical slice, so each element is wrapped in its own list. Also note that this is Python indexing, so the second limit in a range specifier is one higher than the last index in the slice.
type: Answer
score: 3

http://stackoverflow.com/comment/80477953
comment on: http://stackoverflow.com/q/46764246
has text: @mrCarnivore I make it using pandas DataFrame and initialized it to zero with np.zeros
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46869701
has comment: http://stackoverflow.com/comment/80686624
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80686727
tagged with: python
has answer: http://stackoverflow.com/a/46869716
has body: I'm trying to create a little program that lets the user to buy stuff from the shop or money buy working at a job. Code: #Info before user starts print "Enter job, shop, or exit" print "" #-------------------------------------------------------------------------------------------- #Variabls name = raw_input("What is your name?") ask = raw_input("Where do you want to go:") currency = 20 #-------------------------------------------------------------------------------------------- #Functions def job(): print "hello" def shop(): print "Hello " + name + ", what would you like? You have $" + currency #------------------------------------------------------------------------------------------- #Body while (ask != "job") and (ask != "shop") and (ask != "exit"): print "That is not an option. Please choose job, shop, or exit" ask = raw_input("Where do you want to go:") if(ask == "job"): job() elif (ask == "shop"): shop() The programs asks the user's name and asks where he would like to go. For the function shop, the program should print: "Hi [User's name], What would you like? You have $20". When I run it, it shows up this error: Traceback (most recent call last): File "python", line 30, in &lt;module&gt; File "python", line 18, in shop TypeError: cannot concatenate 'str' and 'int' objects Could anyone explain what is happening?
has answer: http://stackoverflow.com/a/46869744
score: 1
has answer: http://stackoverflow.com/a/46869796
type: Question
tagged with: syntax-error
answer count: 3
upvote count: 1
has title: Python: cannot concatenate 'str' and 'int' objects error
favorite count: 0
downvote count: 0

http://stackoverflow.com/comment/80659496
comment on: http://stackoverflow.com/q/46854609
type: Comment
type: QuestionComment
has text: I mean this is just my partial code. I am not sure how can I have 'insert statement' or 'create table' statement as part of this code in Oracle part. I want to load the data as it reads from excel in a loop for every column. TIA!
score: 0

http://stackoverflow.com/q/46760602
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I only manage to use the Emotion API subscription key for pictures but never for videos. It makes no difference whether I use the API Testing Console or try to call the Emotion API by Pathon 2.7. In both cases I get a response status 202 Accepted, however when opening the Operation-Location it says { "error": { "code": "Unauthorized", "message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key." } } On the Emotion API explanatory page it says that Response 202 means that The service has accepted the request and will start the process later. In the response, there is a "Operation-Location" header. Client side should further query the operation status from the URL specified in this header. Then there is Response 401, which is exactly what my Operation-Location contains. I do not understand why I'm getting a response 202 which looks like response 401. I have tried to call the API with Python using at least three code versions that I found on the Internet that all amount to the same, I found the code here : Microsoft Emotion API for Python - upload video from memory python-upload-video-from-memory import httplib import urllib import base64 import json import pandas as pd import numpy as np import requests _url = 'https://api.projectoxford.ai/emotion/v1.0/recognizeInVideo' _key = '**********************' _maxNumRetries = 10 paramsPost = urllib.urlencode({'outputStyle' : 'perFrame', \ 'file':'C:/path/to/file/file.mp4'}) headersPost = dict() headersPost['Ocp-Apim-Subscription-Key'] = _key headersPost['content-type'] = 'application/octet-stream' jsonGet = {} headersGet = dict() headersGet['Ocp-Apim-Subscription-Key'] = _key paramsGet = urllib.urlencode({}) responsePost = requests.request('post', _url + "?" + paramsPost, \ data=open('C:/path/to/file/file.mp4','rb').read(), \ headers = headersPost) print responsePost.status_code videoIDLocation = responsePost.headers['Operation-Location'] p…
has answer: http://stackoverflow.com/a/46766063
type: Question
has title: Iinvalid subscription key when using Microsoft Emotion API for Video in API Testing Console and in Python 2.7
has answer: http://stackoverflow.com/a/46772755
accepted answer: http://stackoverflow.com/a/46772755
answer count: 3
tagged with: api
upvote count: 1
tagged with: subscription
tagged with: key
possible better answer: http://stackoverflow.com/a/46766063
favorite count: 0
tagged with: azure-cognitive-services
has answer: http://stackoverflow.com/a/46774122

http://stackoverflow.com/comment/80475241
score: 0
type: Comment
type: QuestionComment
has text: The question got marked as duplicate but the result there is not working in my program. How can I get rid of the Duplicate marking that the question is open again?
comment on: http://stackoverflow.com/q/46764599

http://stackoverflow.com/comment/80627902
type: Comment
score: 0
type: QuestionComment
has text: before testing the login, can you check the page first if you successfully accessed instagram? There's a possibility that you got an error especially if they implemented anti-bot features.
comment on: http://stackoverflow.com/q/46839880

http://stackoverflow.com/comment/80667639
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/46860011
has text: What are you trying to do, precisely?
type: Comment

http://stackoverflow.com/comment/80473729
has text: it comes with `nginx.service`. and what is incorrect there...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46755451

http://stackoverflow.com/q/46853354
type: Question
tagged with: numpy
downvote count: 0
tagged with: http://stackoverflow.com/tag/r
has body: Teaching myself about GPs and Gaussian Regression i stumbled upon Nando's lectures on the subject (part 1 and part 2). So since my knowledge in python is limited, i tried to rewrite his script in R. However, I am getting NaNwhen producing the standard deviation for the confidence intervals. After some more thorough examination of the problem, i discovered that the main difference lies in the np.linalg.solve() and R's solve(). So the question is, which is a suitable R solver for these kinds of operations? EDIT While trying to attack the issue, i found out that the results from the two pieces of code partially match when solve(L, ker_x_x.test) is replaced by forwardsolve(L, ker_x_x.test). Still i cannot mimic the results from the original script. EDIT 2 I have managed to match the results. In the Python version, matrix Lk is computed using np.linalg.solve() where in R script it should be backsolve(). To compute the mu vector ìn R, you should use the forwardsolve(). Links to documentation: numpy.linalg.solve R solve R backsolve and forwardsolve I provide my code for more comments: # GPs Nando Style # Simple GP Regression. Assumes a zero mean GP Prior. # setwd("your directory") # rm(list=ls()) # graphics.off() # cat("\014") # y &lt;- 0.25*(x^2) kernel &lt;- function(sigma_f, l, x_i, x_j){ val &lt;- (sigma_f^2)*exp((-1*(t(x_i - x_j)%*%(x_i - x_j)))/(2*l^2)) return(val) } N &lt;- 10 # Number of training points n &lt;- 50 # Number of test points s &lt;- 10^(-5) x &lt;- runif(N, -5, 5) y &lt;- sin(0.9*x) + s*rnorm(N, mean = 0, sd = 1) # f(X) is sin(0.9*x) ker_x_x &lt;- matrix(0, nrow = length(x), ncol = length(x)) for (i in 1:length(x)) { for (j in 1:length(x)) { ker_x_x[i, j] &lt;- kernel(1, 0.1, x[i], x[j]) } } L &lt;- chol(ker_x_x + s*diag(N)) # points we are going to make predictions on x_testSet &lt;- seq(-5, 5, length.out = n) # compute kernel ker_x_x.test &lt;- matrix(0, nrow = length(x), ncol = length(x_testSet)) for (i in 1:length(x)) { for (j in 1:length(x_testSet…
tagged with: python
upvote count: 6
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/80654286
has title: Difference between numpy.linalg.solve() and R solve()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80654547
score: 6
has comment: http://stackoverflow.com/comment/80654459

http://stackoverflow.com/a/46776485
type: Answer
answers question: http://stackoverflow.com/q/46775546
has body: IIUC: In [43]: df Out[43]: Lbl # Value Time 0 16 160 0-00-000-0000-0000-0000-0000-00 000:00:00:00.206948 1 17 270 0-00-000-0000-0001-1010-0110-00 000:00:00:00.212948 2 18 271 1-00-000-0000-0000-0110-1110-00 000:00:00:00.215828 3 19 272 0-00-001-1000-0111-1111-1000-00 000:00:00:00.218708 4 20 273 1-00-000-0000-0000-0111-1110-00 000:00:00:00.221588 5 21 274 0-00-000-0000-0000-1001-0110-00 000:00:00:00.224468 6 22 275 0-00-001-1111-0000-0000-0000-00 000:00:00:00.227348 7 23 276 1-00-000-0000-0000-0000-0000-00 000:00:00:00.233428 8 24 277 0-00-000-0000-0000-0000-0000-00 000:00:00:00.236308 9 29 334 0-11-000-0000-0000-0000-0000-00 000:00:00:00.253900 10 63 160 0-00-000-0000-0000-0000-0000-00 000:00:00:00.458692 In [44]: df.Value.str.replace('-','').str.extractall('(\d)').unstack().astype(np.int8).add_prefix('b') Out[44]: b0 ... match b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ... b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ... 1 0 1 0 0 1 1 0 0 0 2 1 0 0 0 0 0 0 0 0 0 ... 0 1 1 0 1 1 1 0 0 0 3 0 0 0 0 0 1 1 0 0 0 ... 1 1 1 1 1 0 0 0 0 0 4 1 0 0 0 0 0 0 0 0 0 ... 0 1 1 1 1 1 1 0 0 0 5 0 0 0 0 0 0 0 0 0 0 ... 1 0 0 1 0 1 1 0 0 0 6 0 0 0 0 0 1 1 1 1 1 ... 0 0 0 0 0 0 0 0 0 0 7 1 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 9 0 1 1 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 [11 rows x 24 columns]
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80498598
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46775546

http://stackoverflow.com/a/47693272
has comment: http://stackoverflow.com/comment/97186077
answers question: http://stackoverflow.com/q/46755832
downvote count: 0
score: 6
upvote count: 6
has body: I think you are using python3 version. I found what the problem is. The auth.create_custom_token(uid) method returns a bytes literal and bytes literal are not JSON serializable. That is why you are getting the error. You can see b' infront of the jwt token. So, you need to just convert the byte literal to string using the code below. custom_token = (auth.create_custom_token(uid)).decode()
type: Answer

http://stackoverflow.com/q/46836480
has comment: http://stackoverflow.com/comment/80621005
linked to: http://stackoverflow.com/q/23911670
upvote count: 2
has title: Is MATLAB's bsxfun the best? Python's numpy.einsum?
has comment: http://stackoverflow.com/comment/80621257
downvote count: 1
has answer: http://stackoverflow.com/a/46836880
accepted answer: http://stackoverflow.com/a/46836952
has comment: http://stackoverflow.com/comment/80621149
favorite count: 0
possible better answer: http://stackoverflow.com/a/46836880
tagged with: python
has answer: http://stackoverflow.com/a/46836952
tagged with: vectorization
has body: I have a very large multiply and sum operation that I need to implement as efficiently as possible. The best method I've found so far is bsxfun in MATLAB, where I formulate the problem as: L = 10000; x = rand(4,1,L+1); A_k = rand(4,4,L); tic for k = 2:L i = 2:k; x(:,1,k+1) = x(:,1,k+1)+sum(sum(bsxfun(@times,A_k(:,:,2:k),x(:,1,k+1-i)),2),3); end toc Note that L will be larger in practice. Is there a faster method? It's strange that I need to first add the singleton dimension to x and then sum over it, but I can't get it to work otherwise. It's still much faster than any other method I've tried, but not enough for our application. I've heard rumors that the Python function numpy.einsum may be more efficient, but I wanted to ask here first before I consider porting my code. I'm using MATLAB R2017b.
tagged with: matlab
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80621189
has comment: http://stackoverflow.com/comment/80620687
type: Question
answer count: 2
tagged with: bsxfun
has comment: http://stackoverflow.com/comment/80620735
tagged with: arrays

http://stackoverflow.com/a/46839220
answers question: http://stackoverflow.com/q/46773522
has comment: http://stackoverflow.com/comment/80696529
has comment: http://stackoverflow.com/comment/80639015
has comment: http://stackoverflow.com/comment/80637705
downvote count: 0
has body: Have you considered creating a decorator for your execute or equivalent (e.g. execute_concurrent) that logs the CQL query used for your statement or prepared statement? You can write this in a manner that the CQL query is only logged if the query was executed successfully.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/80498579
type: Comment
type: QuestionComment
has text: yes of course,"fatal python error cannot recover from stackoverflow". I am working on an embedded device and i wonder why i dont get recursion error while i have not set it to a high limit!?
comment on: http://stackoverflow.com/q/46775912
score: 0

http://stackoverflow.com/q/46782766
has comment: http://stackoverflow.com/comment/80511974
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80511937
has comment: http://stackoverflow.com/comment/80539325
answer count: 0
tagged with: subprocess
tagged with: popen
has comment: http://stackoverflow.com/comment/80511986
has body: I'm trying to execute a command using Popen and search through the output using a regex to find a UserID. When I run the code below and have if reg_ex.search(line) code block commented out, the command runs successfully (although I don't have my userID). As soon as I uncomment out the regex code, the command itself fails. Any ideas why this regex if statement makes the command itself fail when I'm just iterating through output and any idea how to get the userId I need from the output? I've already confirmed the regex itself works when run separately (although for those that want it, the output line for regex will look like this u'userId': u'userID_in–question'}. import re import subprocess #command I want to run command = "add-user " + FirstName + " " + LastName + " " + Email + " " + Phone #Regex to find userId in output reg_ex_find = re.compile('userId') reg_ex_replace = re.compile("(""u'userId""|\s|:|}|')") #call command process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in iter(process.stdout.readline, b''): print line if reg_ex_find.search(line): UserId = line reg_ex_replace.sub('',UserId) process.stdout.close() process.wait() print process.returncode
upvote count: 1
downvote count: 1
type: Question
score: 0
has title: How to run run output of Popen command through a regular expression

http://stackoverflow.com/comment/81105299
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46815156
has text: @Ollie: Maybe you should stop thinking in lines because BeatifulSoup does not operate on lines but on an object tree.

http://stackoverflow.com/q/46771858
type: UnansweredQuestion
tagged with: python
tagged with: list
upvote count: 2
has comment: http://stackoverflow.com/comment/80491846
has comment: http://stackoverflow.com/comment/80490883
has answer: http://stackoverflow.com/a/46773477
type: Question
has title: For Loops with Multiple Variables - Python
tagged with: algorithm
tagged with: for-loop
has comment: http://stackoverflow.com/comment/80519526
score: 2
answer count: 1
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/80490261
favorite count: 0
has body: I am attempting to code a particular algorithm, called the Verlet Algorithm, which basically updates the values of certain variables, called x,v and E, each time the algorithm runs. import matplotlib.pyplot as plt import numpy as np # set constants k = 1 m = 1 #Set the number of iterations to be used in the for loop no_of_iterations=1001 # make arrays to define the data t = np.zeros(no_of_iterations) x = np.zeros(no_of_iterations) v = np.zeros(no_of_iterations) E = np.zeros(no_of_iterations) # set initial conditions t[0] = 0 x[0] = 0 v[0] = 1 E[0] = 0 # make arrays to store data x1=[] v1=[] E1=[] '''N = 4 Loops''' #loop for dt = 0.1,N = 4,j=1 for N in range(1,5,1): for i in range(1,no_of_iterations): j = 1 x[0]= np.sin((np.pi*j*k)/(N+1)) t_max = 100.0 dt = t_max/no_of_iterations #time step t[i] = dt * i v[i] = v[i-1] - ((dt *k/m*(x[N]-x[N-1]))/2) x[i] = x[i-1] + dt * v[i] E[i] = ((((v[i])**2)/2) + (x[N]-x[N-1])) x1.append(x[i]) v1.append(v[i]) E1.append(E[i]) Essentially what this is doing is appending the updated values of x,v and E to empty lists, while given certain initial conditions. Now my problem comes from the fact that my variables that I'm looping over have many different values: N = 4,16,128 : dt = 0.1,0.01 : j = 1,N/2 and I am supposed to plot each array I create, and example of which is shown below: Plot for N = 4, dt = 0.1, j = 1 ( With my N = 4 loop) One problem is that I am storing ALL the values of N=1,2,3,4 into one list, called x1, while I actually want to have 4 separate lists, one for each value of N that I iterate over, ie. x1_N1, x2_N2, x3_N3, x4_N4. But even if I do that things will get pretty messy pretty quickly. For example, with N=128, I should have 4 graphs( (dt = 0.1 and j = 1) , (dt = 0.01 and j = 1) , (dt = 0.01 and j = N/2) , (dt = 0.01 and j = N/2) ) each with 128 lists. Thus I would have to create 8 for loops just for N = 4! So, is there a way to create a new list inside this for loop and append it, rather than having to define an …

http://stackoverflow.com/q/46749434
has comment: http://stackoverflow.com/comment/80446211
has comment: http://stackoverflow.com/comment/80445424
has comment: http://stackoverflow.com/comment/80446192
has comment: http://stackoverflow.com/comment/80445490
tagged with: file-not-found
has comment: http://stackoverflow.com/comment/80446486
has comment: http://stackoverflow.com/comment/80446334
type: Question
has body: I created a PyCharm python project that has a directory of images. When I try to access one of the files in the directory, PyCharm gives me a "FileNotFoundError: [Errno 2] No such file or directory". The icon of the image directory folder in the PyCharm project has a circle in it, which I think suggests that PyCharm thinks it is a package. Either, how do I change the directory from being a package to a regular directory, or, am I missing something else about having a directory under a project in PyCharm? The code I'm using is simply: f = open("images/image.png", "r") Here is a screengrab of the folder icon with a circle in it. Folder icon in PyCharm
has comment: http://stackoverflow.com/comment/80446028
downvote count: 0
tagged with: ide
score: 1
has comment: http://stackoverflow.com/comment/80446268
has comment: http://stackoverflow.com/comment/80444949
tagged with: python
favorite count: 0
answer count: 0
tagged with: pycharm
type: UnansweredQuestion
upvote count: 1
has title: PyCharm project directory of images not accessible in code

http://stackoverflow.com/comment/80670339
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46762533
has text: actually, that is much simpler than using a Manager.

http://stackoverflow.com/a/46780018
answers question: http://stackoverflow.com/q/46779616
upvote count: 7
has body: The information is there, but you'll have to dig around in dist-info and/or egg-info subdirectories to find it. Binary distributions include a RECORD file in their metadata subdirectory. Source distributions include an installed-files.txt file in their metadata subdirectory. The RECORD files are csv lines of (path, hash, size) as documented in PEP-376. The older installed-files.txt from an egg is just the filenames, and you'll have to stat those files manually. As a simple example, I have source and binary distributions of my package copyingmock available on PyPI. With the binary distribution installed (pip install copyingmock): $ pip show --files copyingmock Name: copyingmock Version: 0.1 Summary: A subclass of MagicMock that copies the arguments Home-page: https://github.com/wimglenn/copyingmock Author: Wim Glenn Author-email: hey@wimglenn.com License: MIT Location: /tmp/blah/venv/lib/python3.6/site-packages Requires: Files: __pycache__/copyingmock.cpython-36.pyc copyingmock-0.1.dist-info/DESCRIPTION.rst copyingmock-0.1.dist-info/INSTALLER copyingmock-0.1.dist-info/LICENSE.txt copyingmock-0.1.dist-info/METADATA copyingmock-0.1.dist-info/RECORD copyingmock-0.1.dist-info/WHEEL copyingmock-0.1.dist-info/metadata.json copyingmock-0.1.dist-info/top_level.txt copyingmock.py $ cat venv/lib/python3.6/site-packages/copyingmock-0.1.dist-info/RECORD copyingmock.py,sha256=DoLAuaS7KqGT87BIlD93G1M7q9bNWgHYu1m1TZP1D1g,345 copyingmock-0.1.dist-info/DESCRIPTION.rst,sha256=L_0CS_8XNYgAVfq3tj3GZEYg_9vML9nDP-FUU37GIbs,1541 copyingmock-0.1.dist-info/LICENSE.txt,sha256=sDdX5cBRRpk3rmZ8hbYEfAUIYRdDqrlXmChOUkqf62o,1066 copyingmock-0.1.dist-info/METADATA,sha256=bKJ5RXwvj0rGrg22p4K91WiJoLM5MqLHYqlpWYWUhPU,2031 copyingmock-0.1.dist-info/RECORD,, copyingmock-0.1.dist-info/WHEEL,sha256=5wvfB7GvgZAbKBSE9uX9Zbi6LCL-_KgezgHblXhCRnM,113 copyingmock-0.1.dist-info/metadata.json,sha256=SLtuqq4tUGr0A2h4hQnZEdPIm_4MrvcunLzP-_1I7Qc,677 copyingmock-0.1.dist-info/top_level.txt,sha256=X3FsY_0npOxR5rKvOJ-b…
score: 7
accepted answer of: http://stackoverflow.com/q/46779616
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80506248

http://stackoverflow.com/q/46828207
has body: I am quite new to Scrapy / ProxyMesh. My request to the Proxymesh server seems to be working as I see my bandwith consumption on the ProxyMesh website, and the meta.proxy is correct in my logs. However, when I log the response headers in Scrapy, I do not receive the X-Proxymesh-IP that I am supposed to receive. Here is my code. What am I doing wrong? This is my middleware class Proxymesh(object): def __init__(self): logging.debug('Initialized Proxymesh middleware') self.proxy_ip = 'http://host:port' def process_request(self, request, spider): logging.debug('Processing request through proxy IP: ' + self.proxy_ip) request.meta['proxy'] = self.proxy_ip These are my settings in my spider custom_settings = { "DOWNLOADER_MIDDLEWARES": { "projectName.middlewares.proxymesh.Proxymesh" : 1, } This is what the response headers look like ['Set-Cookie']:['__cfduid=d88d4e4cb7... HttpOnly'] ['Vary']:['User-Agent,Accept-Encoding'] ['Server']:['cloudflare-nginx'] ['Date']:['Thu, 19 Oct 2017 10...38:10 GMT'] ['Cf-Ray']:['3b031b30cbef1565-CDG'] ['Content-Type']:['text/html; charset=UTF-8'] Thank you for your help
has answer: http://stackoverflow.com/a/46828444
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54237713
tagged with: scrapy
type: Question
answer count: 2
tagged with: header
tagged with: proxy
score: 0
has title: Not receiving headers Scrapy ProxyMesh
tagged with: python

http://stackoverflow.com/a/46880560
answers question: http://stackoverflow.com/q/46878520
downvote count: 1
has body: There is a great api released by Microsoft called cognitive service. You may use that to do image recognization. https://azure.microsoft.com/en-us/services/cognitive-services/
has comment: http://stackoverflow.com/comment/80715632
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/80783340
type: QuestionComment
comment on: http://stackoverflow.com/q/46903154
score: 0
type: Comment
has text: @AnthonyD'amato this doesn't work because fstate is a LSTMStateTuple. However, if I do this instead `logits[0] = tf.matmul(tf.concat([fstate[0].h, fstate2[0].h], 1), output_layer[0]) + output_bias[0]`, it succeeds in the concatenation but later on complains that the output shape is not right. The shape is `(9, 512)`, when it should be `(9, 256)` since each LSTM cell has size 256. Thus, it can't do the multiplication with `output_layer[0]`, since that has a size of `(256, output)`. I don't think the right solution is to change `output_layer` size, or is it?

http://stackoverflow.com/comment/80542241
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46773477
has text: Thank you so much for your help! There's a lot of really cool code in there! Spent a while today deciphering it and I have learned so much! I genuinely appreciate all your help.

http://stackoverflow.com/q/46792424
tagged with: powerpoint
has answer: http://stackoverflow.com/a/46830300
type: Question
has title: How to use Python Seaborn Visualizations in PowerPoint?
has answer: http://stackoverflow.com/a/49083874
has body: I created some figures with Seaborn in a Jupyter Notebook. I would now like to present those figures in a PowerPoint presentation. I know that it is possible to export the figures as png and include them in the presentation. But then they would be static, and if something changes in the dataframe, the picture would be the same. Is there an option to have a dynamic figure in PowerPoint? Something like a small Jupyter Notebook you could Display in the slides?
tagged with: figure
answer count: 3
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/46801905
favorite count: 0
upvote count: 2
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
tagged with: dynamic

http://stackoverflow.com/q/46840382
has comment: http://stackoverflow.com/comment/80628694
tagged with: configuration-files
score: 0
tagged with: python
has body: I'm trying to import a file that has multiple variables within it, each variable containing anywhere from 1 entry to about a hundred. so something like this: [info] name = Jon number = 2 multiple_num = 5 2 4 65 78 45 I've formatted this as an .ini file and used ConfigParser to read it in, however, unless I have the multiline values indented, ConfigParser gives me errors. So the above snippit of code will give me errors, yet this one will be fine. [info] name = Jon number = 2 multiple_num = 5 2 4 65 78 45 Is there a better way to do this that doesn't involve the user hand indenting every single line? Like I said, the data within some of the variables, while not enormous, would still be long enough to get annoying. Am I going about this the complete wrong way? Any help is appreciated! Thanks, Tyler
type: UnansweredQuestion
type: Question
has title: Best way to import a configuration file which contains multiple sets of multiline data in Python?
tagged with: configparser
has answer: http://stackoverflow.com/a/46840431
answer count: 1

http://stackoverflow.com/comment/80651015
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46833651
type: Comment
has text: I can't find the library having MahalanobisDist please tell the library.And it will be helpful if you explain it .

http://stackoverflow.com/comment/80537035
type: Comment
has text: Hi, Thank you for responding back. i am getting this .cd /home/anish anish@anish-Vostro-1450:~$ chmod +x mu_2017-06-21_18_07_master_3202867.bin anish@anish-Vostro-1450:~$ sudo usermod -a -G dialout Anish [sudo] password for anish: usermod: user 'Anish' does not exist anish@anish-Vostro-1450:~$ sudo usermod -a -G dialout anish anish@anish-Vostro-1450:~$ ./mu_2017-06-21_18_07_master_3202867.bin Segmentation fault (core dumped) anish@anish-Vostro-1450:~$
comment on: http://stackoverflow.com/a/46794647
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80581860
comment on: http://stackoverflow.com/q/46817126
has text: Just edited the question. Basically I get that the function or self is not defined.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80679758
has text: @ChristianDean Indeed, and I'm doing my small part to reverse that trend. ;) It may seem a little pedantic, but when there are two built-in array-like types (lists and tuples), the arrays of the `array` module I linked above, plus Numpy arrays, I think it's important to give these things their correct names.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46866105
score: 3

http://stackoverflow.com/comment/80468888
type: Comment
type: QuestionComment
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html
comment on: http://stackoverflow.com/q/46761576
score: 0

http://stackoverflow.com/comment/80732297
type: Comment
comment on: http://stackoverflow.com/a/46809257
score: 0
type: AnswerComment
has text: Thank you for your suggestions. I will post my findings after trying them.

http://stackoverflow.com/comment/80497217
comment on: http://stackoverflow.com/q/46775835
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/11964450/python-order-a-list-of-numbers-without-built-in-sort-min-max-function

http://stackoverflow.com/a/46755224
type: Answer
answers question: http://stackoverflow.com/q/46754940
has comment: http://stackoverflow.com/comment/80460862
accepted answer of: http://stackoverflow.com/q/46754940
has body: There are a few problems with that code. A major one is this line: if P1.heading() is 180: The is operator tests identity, i.e., it's True if two expressions evaluate to the same object. You should not use it to test if two expressions have the same value. In this case, P1.heading() returns the float object with a value of 180.0, so there's no way it could be the same object as the integer object with value 180. Thus your if block is never entered. And since the main commands that move the turtles are at the end of the if block, the turtles don't move once you enter the while loop. Also, you are using n to index into your lists, but you never update n from zero, so all of the coordinates that you want to save are getting written into the first items of the lists. However, if you did update n you'd run into another problem: you'd be attempting to index list items that don't exist, since x1 and y1 are of length one, and x2 and y2 are of length zero. Anyway, here's a simplified version of your code that does update the lists correctly, and does simple collision detection. It only detects exact collision, not approximate collision, but it should get you going in the right direction. import turtle Screen = turtle.Screen() Screen.screensize(100, 100) P1 = turtle.Turtle() P2 = turtle.Turtle() x1 = [] x2 = [] y1 = [] y2 = [] P1.penup() P1.setheading(180) P2.setheading(90) P1.goto(100, 50) P2.penup() P2.goto(50, 0) P2.pendown() P1.pendown() while True: print(P1.heading() is 180) XC = P2.position()[0] YC = P2.position()[1] x2.append(XC) y2.append(YC) XC = P1.position()[0] YC = P1.position()[1] x1.append(XC) y1.append(YC) if XC in x2 and YC in y2: print("Found") P2.forward(1) P1.forward(0.5) turtle.done()
type: AcceptedAnswer
score: 0

geoalchemy2
tag name: geoalchemy2
tags question: http://stackoverflow.com/q/46836009
type: Tag

http://stackoverflow.com/comment/80685921
has text: VTK description data should the minimum to post ...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46869358
score: 0

http://stackoverflow.com/comment/80676200
has text: What does KeyError mean?
comment on: http://stackoverflow.com/q/46864127
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80695211
has text: well you could use ascii_lowercase and wrap this part `(string.ascii_letters.index(ch) + offset` in brackets(% has higher precedence than +), to solve the wrapping issue
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46874049
type: Comment

http://stackoverflow.com/comment/80828608
type: Comment
has text: @Everlong then you have additional dependency to group, which you can add to AlterEgo class. It is null be default, so when user joins the group he should also choose the alter ego he will use in the group (or you define it for the user) Then in the template you can just check if alter ego group equals to the group for which you output names. See my edited answer
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46898724

http://stackoverflow.com/comment/80466564
has text: Does `print(job)` show all lines?
type: QuestionComment
comment on: http://stackoverflow.com/q/46760494
score: 0
type: Comment

http://stackoverflow.com/comment/80682012
score: 2
has text: You will not be able to edit it inline when you upload your deployment package as zip. Did you try running your code in lambda? What error are you getting when you run it?
comment on: http://stackoverflow.com/q/46867246
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80690024
score: 0
has text: Web script actually has some dababase reading/writing. I wanna to test them totally, including HTTPServer's handling, without external web access.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46869227

http://stackoverflow.com/comment/80727880
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46890238
has text: Can you be more precise? What should be the name of the system variable?
type: AnswerComment

http://stackoverflow.com/comment/80472715
comment on: http://stackoverflow.com/q/46763675
has text: self = <lib.ui.login_page.LoginPage object at 0x04654FF0> def wait_for_login_page(self): wait = WebDriverWait(self.driver, 30) \x1b[1m> element = self.driver.title("Facebook \u2013 log in or sign up")\x1b[0m E TypeError: 'str' object is not callable lib\ui\login_page.py:35: TypeError
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80644869
type: QuestionComment
has text: It'd help if you showed your attempt at using `pandas.read_fwf` as that's the correct approach...
comment on: http://stackoverflow.com/q/46832969
score: 0
type: Comment

http://stackoverflow.com/a/46754824
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46753989
has body: A solution could be: (?:href=)('|")(.*)\1 (?:href=) is a non capturing group. It means that the parser use href during the matching but it actually does not return it. As a matter of fact if you try this in regex you will see there's no group holding it. Besides, every time you open and close a round bracket, you create a group. As a consequence, ('|") defines the group #1 and the URL you want will be in group #2. The way you retrieve this info depends on the programming language. At the end, the \1 returns the value hold by group #1 (in this case it will be ") to provide a delimiter to the URL
type: Answer

http://stackoverflow.com/q/46856137
tagged with: nonblocking
has body: I have a piece of python code to practice python co-routines. As explained by A. Jesse Jiryu Davis. Firstly, I define a co-routine named 'get' to get the content of some URL. Then I define a Task class to iterate the co-routine to completion. Then I create one Task object which open one URL. If I put two successive socket.recv() method in the co-routine, I got the error message: 'A non-blocking socket operation could not be completed immediately' in the second chunk = s.recv(1000) line. But if I change all the yield to time.sleep(1) and directly call get() in the global context, the two successive s.recv(1000) will cause no errors. Even more successive s.recv(1000) is OK. After several days searching and reading python documents, I still have no idea why this is happening. I must missed some 'python Gotchas', do I? I'm using python 3.6 to test. The code is as following and I have deleted all the irrelevant code to make the following code precise and relevant to the topic: #! /usr/bin/python import socket import select import time selectors_read = [] selectors_write = [] class Task: def __init__(self, gen): self.gen = gen self.step() def step(self): try: next(self.gen) except StopIteration: return def get(): s = socket.socket() selectors_write.append(s.fileno()) s.setblocking(False) try: s.connect(('www.baidu.com', 80)) except: pass yield selectors_write.remove(s.fileno()) print('[CO-ROUTINE] ', 'Send') selectors_read.append(s.fileno()) s.send('GET /index.html HTTP/1.0\r\n\r\n'.encode()) yield while True: chunk = s.recv(1000) chunk = s.recv(1000) if chunk: print('[CO-ROUTINE] received') else: selectors_read.remove(s.fileno()) break # yield task_temp = Task(get()) while True: for filenums in select.select(selectors_read, selectors_write, []): for fd in filenums: task_temp.step()
score: 1
upvote count: 1
tagged with: recv
favorite count: 0
type: UnansweredQuestion
tagged with: sockets
has title: In python co-routine, two successive socket.recv() causes BlockingIOError
tagged with: python
answer count: 0
downvote count: 0
type: Question

http://stackoverflow.com/a/46844146
has body: import re a = """ staffs: 50 - 100 year_turnover: 0 url: http://www.chinaanigu.com """ b = re.findall("staffs:\s+(\d.+\d)", a) c = re.findall("year_turnover:\s+(\d)", a) print(b) print(c)
score: 0
answers question: http://stackoverflow.com/q/46843992
type: Answer

http://stackoverflow.com/comment/80465157
has text: @DanielRoseman And How am I going to use it on the view when I call the form? Already tried to remove it and just place the field names inside `field[]`. But only the field name is displayed, not the dropDown
type: QuestionComment
comment on: http://stackoverflow.com/q/46759208
score: 0
type: Comment

http://stackoverflow.com/q/46774030
favorite count: 0
has body: from pywinauto import application Error message: Traceback (most recent call last): File "D:/Program Files/Python/pywinauto.py", line 1, in from pywinauto import application File "D:/Program Files/Python\pywinauto.py", line 1, in from pywinauto import application ImportError: cannot import name 'application'
has answer: http://stackoverflow.com/a/46795579
possible better answer: http://stackoverflow.com/a/50259536
tagged with: python
type: AnsweredQuestion
has title: cannot import name 'application' in python 3
type: Question
score: -2
has answer: http://stackoverflow.com/a/50259536
has answer: http://stackoverflow.com/a/46774103
accepted answer: http://stackoverflow.com/a/46774103
answer count: 3
downvote count: 3
upvote count: 1

http://stackoverflow.com/comment/80668057
type: QuestionComment
comment on: http://stackoverflow.com/q/46859866
score: 0
has text: @LuisLeal Or `count != 10`
type: Comment

http://stackoverflow.com/comment/80955542
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46854905
has text: @Achyuth I'm in the process of doing all that. Do you want to gather your thoughts and paste them in an answer below? That way if this line of investigation bears fruit I can assign it the accepted answer
score: 0

http://stackoverflow.com/q/46870841
has title: Quotation in csv library
score: 0
has answer: http://stackoverflow.com/a/46878679
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80703189
type: Question
has comment: http://stackoverflow.com/comment/80698734
has body: I'm trying to request an XML API for the first column in the input tsv file, and get a tsv file as output. My input file(tab separated): input1 input1.1 input1.2 input1.3 input2 input2.1 input2.2 input2.3 The code: with open('data/input.txt', 'r') as tsvin, open('data/output.txt', 'w') as csvout: tsvin = csv.reader(tsvin, delimiter='\t') csvout = csv.writer(csvout, delimiter='\t', quoting=csv.QUOTE_NONE) for i in tsvin: word = i[0] r = requests.get(api_url + str(word), params=payload) root = ElementTree.fromstring(r.content) for child in root.iter('entry'): if child.attrib['id'] == word + word_id or child.attrib['id'] == word: for child_nested in child: if child_nested.tag == 'pr': csvout.writerow([i, child_nested.text]) As a result I got: ['input1', 'input1.1', 'input1.2', 'input1.3'] value_from_api1 ['input2', 'input2.1', 'input2.2', 'input2.3'] value_from_api2 If I do csvout.writerow([i]) at the end, the initial row writes to the output properly without any quotation. But if I added the result from API child_nested.text after the comma, it writes with quotes. So, how to append child_nested.text to i and write it without quotes?
has comment: http://stackoverflow.com/comment/80689500
answer count: 1
has comment: http://stackoverflow.com/comment/80691540

http://stackoverflow.com/q/46882516
has comment: http://stackoverflow.com/comment/80712339
accepted answer: http://stackoverflow.com/a/46882980
tagged with: dataframe
has body: Could someone tell me how to Add rows in this dataframe automatically? I have a data frame df : frequency enrollment_id event days 1 access 2 3 7 8 9 4 10 3 12 2 15 21 18 4 19 8 20 20 22 16 23 2 28 2 29 14 navigate 2 1 7 4 9 1 10 3 11 1 12 1 15 5 18 1 19 1 22 3 23 1 28 1 29 2 page_close 2 1 7 6 9 2 10 3 ... ... 200881 navigate 28 1 200882 discussion 28 4 navigate 28 4 200883 access 28 2 navigate 28 2 page_close 28 1 200885 navigate 21 1 200887 access 21 3 navigate 21 2 page_close 21 1 video 21 1 200888 access 21 2 discussion 21 1 navigate 21 5 page_close 21 1 video 21 1 wiki 21 1 200889 navigate 21 1 200893 navigate 21 2 200895 navigate 21 1 200896 navigate 21 1 200897 navigate 21 1 200898 navigate 21 1 200900 navigate 21 1 200901 access 21 3 navigate 21 2 page_close 21 2 video 21 1 200904 navigate 21 1 200905 navigate 21 1 This df has 3 index: 1. event 2. days 3. enrollment_id and only one column frequency event has 7 different value like : access, remove etc. days has 30 different vaule 0 - 29 (not every event has 0 - 29. some event just has for example 0, 1, 4.) enrollment_id has a lot of different value (maybe 100000). Same, not each days has all enrollment_id. My question is : How can I add all lost rows? For example : If I have this frequency enrollment_id event days 1 access 2 3 7 8 I need to add rows for frequency enrollment_id event days 1 access 0 0 1 0 3 0 4 0 5 0 6 0 ... ... 29 0 and I need to add rows for 0 with all other enrollment_id and frequency 0 and and all rows for access with0days - 29days and enrollment_id from 1 - max I really want to get this answer. I really appreciate your help!!
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/46882980
has title: Add row in data frame automatically
tagged with: python
has comment: http://stackoverflow.com/comment/80712243
type: AnsweredQuestion

http://stackoverflow.com/comment/80569647
comment on: http://stackoverflow.com/a/46810773
type: AnswerComment
score: 0
has text: The result is what I need, but can you do it without any for-loop? Because it may affect performance.
type: Comment

http://stackoverflow.com/comment/80592586
score: 0
has text: @eugeneoei Okay, in a few moments I'll create an insert method. On the second point there is no official documentation, in fact the official documentation of PyQt points to the documentation of Qt so if you know the least of C ++ you can understand it. Please do not forget to mark my answer as correct.
comment on: http://stackoverflow.com/a/46818614
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80469750
has text: @Tom it won't necessarily cause an error, but it's generally an antipattern when nested loops use the same variable name. Ignoring the comments, your code is essentially the same as `for i in ops: s.extend([i] * len(ops) * len(ops))`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46762075

http://stackoverflow.com/comment/80620093
score: 0
comment on: http://stackoverflow.com/q/46835999
type: Comment
type: QuestionComment
has text: could tell us what issue are you facing and you need to show the content of CSV as well to understand what actually you have tried

http://stackoverflow.com/comment/80488606
type: QuestionComment
has text: Are you considering "printable" to be the range 32-126? I'm unclear if you decided yourself to only use that range or you have to.
score: 0
comment on: http://stackoverflow.com/q/46771142
type: Comment

http://stackoverflow.com/comment/80744233
has text: Welcome to SO. Please take the time to read [ask] and the links it contains. You should always include the complete Traceback - formatted as code - if there is an error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46898492

http://stackoverflow.com/comment/80720916
type: AnswerComment
type: Comment
has text: ok,thanks but it gives me serial error.However i want to take disconnected message.
score: 0
comment on: http://stackoverflow.com/a/46886604

http://stackoverflow.com/a/64263061
type: Answer
downvote count: 0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/136508685
has body: There may be another cause for duplicates when using the __name__ variable as the logger name. The logger assumes that dots in the name indicate a parent-child relatationship. If you already created a logger from a module higher in the tree, it is also called to handle the logging. So if you first logger = logger.get_logger(__name__) in module 'foo' and add handlers to it, then another_logger = logger.get_logger(__name__) in module 'foo.bar' and add handlers to it, you have created a parent and a child. Using another_logger.info('Some text') in the foo.bar module will result in executing the handlers of the 'foo.bar' handler first and then the same message by the 'foo' handler.
answers question: http://stackoverflow.com/q/46807204

http://stackoverflow.com/comment/80461463
score: 0
type: Comment
type: QuestionComment
has text: Fix your indentation please
comment on: http://stackoverflow.com/q/46758093

http://stackoverflow.com/comment/80473365
type: QuestionComment
comment on: http://stackoverflow.com/q/46762963
has text: A hand-made diagram is never enough to give good advice. Can you show real images ?
score: 0
type: Comment

http://stackoverflow.com/comment/92713561
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46761387
has text: See https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html Don't use ``python-path``, use ``python-home``.
type: AnswerComment

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/46905530
tags question: http://stackoverflow.com/q/46797622
tags question: http://stackoverflow.com/q/46897736
type: Tag

http://stackoverflow.com/comment/80455215
type: Comment
has text: Please read http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html.
score: 0
comment on: http://stackoverflow.com/q/46754707
type: QuestionComment

http://stackoverflow.com/q/46880569
type: Question
has answer: http://stackoverflow.com/a/46883140
answer count: 2
upvote count: 6
tagged with: pkg-resources
has body: I want my package's version number to live in a single place where everything that needs it can refer to it. I found several suggestions in this Python guide to Single Sourcing the Package Version and decided to try #4, storing it in a simple text file in my project root named VERSION. Here's a shortened version of my project's directory tree (you can see the the full project on GitHub): . ├── MANIFEST.in ├── README.md ├── setup.py ├── VERSION ├── src/ │ └── fluidspaces/ │ ├── __init__.py │ ├── __main__.py │ ├── i3_commands.py │ ├── rofi_commands.py │ ├── workspace.py │ └── workspaces.py └── tests/ ├── test_workspace.py └── test_workspaces.py Since VERSION and setup.py are siblings, it's very easy to read the version file inside the setup script and do whatever I want with it. But VERSION and src/fluidspaces/__main__.py aren't siblings and the main module doesn't know the project root's path, so I can't use this approach. The guide had this reminder: Warning: With this approach you must make sure that the VERSION file is included in all your source and binary distributions (e.g. add include VERSION to your MANIFEST.in). That seemed reasonable - instead of package modules needing the project root path, the version file could be copied into the package at build time for easy access - but I added that line to the manifest and the version file still doesn't seem to be showing up in the build anywhere. To build, I'm running pip install -U . from the project root and inside a virtualenv. Here are the folders that get created in &lt;virtualenv&gt;/lib/python3.6/site-packages as a result: fluidspaces/ ├── i3_commands.py ├── __init__.py ├── __main__.py ├── __pycache__/ # contents snipped ├── rofi_commands.py ├── workspace.py └── workspaces.py fluidspaces-0.1.0-py3.6.egg-info/ ├── dependency_links.txt ├── entry_points.txt ├── installed-files.txt ├── PKG-INFO ├── SOURCES.txt └── top_level.txt More of my configuration files: MANIFEST.in: include README.md include VERSION graft …
favorite count: 0
has title: How to access text file in project root from python package under `src/` directory
tagged with: setup.py
type: UnansweredQuestion
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/60066396
tagged with: versioning
downvote count: 0
tagged with: setuptools
linked to: http://stackoverflow.com/q/14211575

http://stackoverflow.com/comment/80702595
type: Comment
comment on: http://stackoverflow.com/a/46877636
type: AnswerComment
score: 0
has text: are you scraping all the pages in the same loop ? by saving the writer at the end, you should be able to keep all data

http://stackoverflow.com/q/46884487
tagged with: apache-kafka
has title: How can a org.apache.kafka.connect.data.Decimal stored in an avro file be converted to a python type?
has answer: http://stackoverflow.com/a/46948205
linked to: http://stackoverflow.com/q/48885704
upvote count: 6
linked to: http://stackoverflow.com/q/16996527
favorite count: 0
has answer: http://stackoverflow.com/a/71351576
answer count: 3
has answer: http://stackoverflow.com/a/60908825
type: UnansweredQuestion
tagged with: apache-kafka-connect
tagged with: python
downvote count: 0
score: 6
has body: I am trying to interpret a Avro record stored by Debezium in Kafka, using Python { "name": "id", "type": { "type": "bytes", "scale": 0, "precision": 64, "connect.version": 1, "connect.parameters": { "scale": "0" }, "connect.name": "org.apache.kafka.connect.data.Decimal", "logicalType": "decimal" } } I am not sure to which Python 3 primitive type this corresponds to. How can this value be deserialised? Thanks in advance!
type: Question
tagged with: debezium

http://stackoverflow.com/comment/80450004
comment on: http://stackoverflow.com/q/46751465
score: 0
type: Comment
type: QuestionComment
has text: @jezrael go ahead dude ! :-) plz mark it as dup ~

http://stackoverflow.com/q/46884648
favorite count: 0
has answer: http://stackoverflow.com/a/71625970
tagged with: python
has answer: http://stackoverflow.com/a/46884669
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/71625970
linked to: http://stackoverflow.com/q/36760414
upvote count: 2
has body: I am new to Python and I'm trying to understand how to manipulate data with pandas DataFrames. I searched for similar questions but I don't see any satisfying my exact need. Please point me to the correct post if this is a duplicate. So I have multiple DataFrames with the exact same shape, columns and index. How do I combine them with labels so I can easily access the data with any column/index/label? E.g. after the setup below, how do I put df1 and df2 into one DataFrame and label them with the names 'df1' and 'df2', so I can access data in a way like df['A']['df1']['b'], and get number of rows of df? &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'], index=['a', 'b']) &gt;&gt;&gt; df2 = pd.DataFrame([[5, 6], [7, 8]], columns=['A', 'B'], index=['a', 'b']) &gt;&gt;&gt; df1 A B a 1 2 b 3 4 &gt;&gt;&gt; df2 A B a 5 6 b 7 8
type: Question
linked to: http://stackoverflow.com/q/56460254
has title: Storing 3-dimensional data in pandas DataFrame
accepted answer: http://stackoverflow.com/a/46884669
answer count: 2
linked to: http://stackoverflow.com/q/24290495
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/80714135
has text: @user8638151, check the last edit - does that meet the requirements?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46883055

http://stackoverflow.com/q/46895509
has comment: http://stackoverflow.com/comment/80738435
has comment: http://stackoverflow.com/comment/80738612
has comment: http://stackoverflow.com/comment/80739157
tagged with: python
has comment: http://stackoverflow.com/comment/80738336
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46896757
upvote count: 1
type: Question
has body: The code is meant to auto rename a bunch of CSV files which are called history (1) ... history (42) here is the events list: https://drive.google.com/open?id=0B5bJvxM9TZkhYXZOSnRDVnhTbFk Here is a screen shot of the files in my folder: The new names are captured from a web page through Beautiful soup. The new names have two possibilities in format most of them have two sections and only four have three sections. When it comes to the rename function I encounter an error. Here is the whole code: from urllib.request import urlopen from bs4 import BeautifulSoup import os events = open('events.txt', 'r') os.chdir("C:\\Users\\Sayed\\Downloads") # name for event in events: sauce = urlopen(event).read() soup = BeautifulSoup(sauce, 'lxml') title = soup.find_all('title') for x in title: title = x.text try: firstName, lastNmame, country = (title.split('-')) firstName = firstName.strip() lastNmame = lastNmame.strip() country = country.strip() name = ('{} - {} - {}'.format(country, firstName, lastNmame)) for file in os.listdir(): firstName, ext = os.path.splitext(file) os.rename(firstName, name) except ValueError: pass try: firstName, country = (title.split('-')) firstName = firstName.strip() country = country.strip() name = ('{} - {}'.format(country, firstName)) for file in os.listdir(): firstName, ext = os.path.splitext(file) os.rename(firstName, name) except ValueError: pass Here is the error: Traceback (most recent call last): File "C:/Users/Sayed/PycharmProjects/Tutorial/pan.py", line 37, in &lt;module&gt; os.rename(firstName, name) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'history (1)' -&gt; 'European Monetary Union - Services Sentiment'
tagged with: file-rename
has comment: http://stackoverflow.com/comment/80738169
has title: error with code to auto rename a folder of CSV files
accepted answer: http://stackoverflow.com/a/46896757
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/46876752
has comment: http://stackoverflow.com/comment/80700513
score: 0
has title: Generating random numbers based on an inverse Gaussian distribution
has comment: http://stackoverflow.com/comment/80700646
answer count: 1
has comment: http://stackoverflow.com/comment/80700815
has body: I can easily generate a random number along a gaussian/normal probability distribution. slice = random.gauss(50.0, 15.0) But the probability distribution is the inverse of what I want: But what I want is the inverse probability. Inverse of Gaussian probability looks like this: And I would actually like to capture high probability not just for the left side, but also the right so. So literally whatever the probability is of a result along a normal distribution...I want the actual probability of my results to be the opposite. So if it's 90% probability on a normal distribution, I want that result to appear 10% of the time, etc.
has answer: http://stackoverflow.com/a/46876854
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80700596
tagged with: python
has comment: http://stackoverflow.com/comment/80700440
type: Question
tagged with: gaussian

http://stackoverflow.com/a/63053029
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46807776
has body: in spark 2.4.4 and python 3.7 (I guess its also relevant for previous spark and python version) -- My suggestion is a based on pauli's answer, instead of creating the struct and then using the agg function, create the struct inside collect_list: df = spark.createDataFrame([(0,1,2),(0,4,5),(1,7,8),(1,8,7)]).toDF("a","b","c") df.groupBy("a").agg(collect_list(struct(["b","c"])).alias("res")).show() result : +---+-----------------+ | a|res | +---+-----------------+ | 0|[[1, 2], [4, 5]] | | 1|[[7, 8], [8, 7]] | +---+-----------------+
type: Answer

http://stackoverflow.com/comment/80539058
type: Comment
type: QuestionComment
has text: But I'm not importing `biomes`, I'm importing a function from `biomes`, doesn't that make it non-circular?
comment on: http://stackoverflow.com/q/46796023
score: 0

http://stackoverflow.com/a/46881874
score: 0
type: Answer
has body: You can start mapping out the data schema you want. Decide what would be key and what would be value. Then, you can start by creating a dict() foo = dict() And you insert items into dictionary by foo["KEY"] = "VALUE" for example, foo["x"] = 12 then, the value will be stored in the dictionary. Here is a tutorial about how to use dictionary in python: https://www.youtube.com/watch?v=2j7ox_zqM4g
answers question: http://stackoverflow.com/q/46881755

http://stackoverflow.com/q/46794115
accepted answer: http://stackoverflow.com/a/46794313
upvote count: 5
has answer: http://stackoverflow.com/a/46794468
has title: passing a tuple in *args
has body: I'd like to pass a tuple (or maybe a list) to a function as a sequence of values (arguments). The tuple should be then unpacked as an argument into *arg. For example, this is clear: def func(*args): for i in args: print "i = ", i func('a', 'b', 3, 'something') But what I want to do is this: tup = ('a1', 'a2', 4, 'something-else') func(tup) And this should behave similar to the first case. I think I should use here reprint and eval but not sure how exactly. I know that I can just pass the tuple in the function and then unpack it within the body, but my question here is how to unpack it in the function call itself.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46794468
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53649220
has comment: http://stackoverflow.com/comment/80534963
tagged with: args
type: Question
tagged with: eval
linked to: http://stackoverflow.com/q/36901
score: 5
has answer: http://stackoverflow.com/a/46794313
tagged with: python
answer count: 3

http://stackoverflow.com/comment/83269286
has text: [Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.](http://meta.stackoverflow.com/questions/254393)
score: 0
comment on: http://stackoverflow.com/q/46793526
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80564242
comment on: http://stackoverflow.com/q/46807093
has text: Ok both subprocess calls are done in different functions and when I do both calls in both function then in one function both throw the error in the other function both don't throw the exception.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/80567313
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46809778
has text: @luschn is there anyway I can achieve this 2 problems?
score: 0

http://stackoverflow.com/q/46864240
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/80675870
has answer: http://stackoverflow.com/a/46864846
has answer: http://stackoverflow.com/a/46864600
type: UnansweredQuestion
tagged with: python-3.6
score: -3
upvote count: 0
has comment: http://stackoverflow.com/comment/80676175
favorite count: 0
has body: So I'm creating a fake chat generator, I've gotten chatlogs of Twitch streams to make a massive chatlog text file. However they're formatted like this, [2017-10-14 05:27:17 UTC] beboh13: is this guy good Is there a way to make a Python script to edit every line to remove the 4th space, so the message above would turn into this? is this guy good
type: Question
tagged with: python
has title: Editing Text File to remove everything before certain character
has comment: http://stackoverflow.com/comment/80675906
tagged with: text

http://stackoverflow.com/comment/80591290
has text: Yes. I forgot to add that. Thanks.
comment on: http://stackoverflow.com/a/46821946
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80683709
type: QuestionComment
comment on: http://stackoverflow.com/q/46868182
has text: I had so much difficult problems in this dataset, as a beginner. That I don't see the normal things anymore. I'm embarrassed.
score: 0
type: Comment

http://stackoverflow.com/comment/80667857
comment on: http://stackoverflow.com/a/46860067
has text: so if i wanted a json without unicode, (which helps with readability and less likely to cause issues when being pulled into programs), surely it's fine to remove anything with \u +4 extra characters before saving back into json?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80669216
comment on: http://stackoverflow.com/a/46845568
type: Comment
has text: Netifaces is written in C, so you need a C compiler. I'm sorry, I haven't developed on Windows in over a decade, so I don't know how to help you with that.
type: AnswerComment
score: 0

http://stackoverflow.com/q/46904410
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/80755515
has comment: http://stackoverflow.com/comment/96436538
tagged with: android
answer count: 1
has title: How to return json from Amazon Python Lambda, that can be handled be Android GSON api
tagged with: python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46926769
tagged with: http://stackoverflow.com/tag/json
tagged with: gson
type: Question
has body: Problem: lambda function return string, I can't write the correct syntax in lambda function toconvert it to json to be parsed with GSON. Android StudioLogs: FATAL EXCEPTION: AsyncTask #1 Process: com.innovdroid.awslambdatest, PID: 6252 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:111) atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:58)at java.lang.Thread.run(Thread.java:818)Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)at com.google.gson.Gson.fromJson(Gson.java:803)at com.google.gson.Gson.fromJson(Gson.java:741)at com.amazonaws.mobileconnectors.lambdainvoker.LambdaJsonBinder.deserialize(LambdaJsonBinder.java:47)at com.amazonaws.mobileconnectors.lambdainvoker.LambdaInvocationHandler.processInvokeResult(LambdaInvocationHandler.java:134)at com.amazonaws.mobileconnectors.lambdainvoker.LambdaInvocationHandler.invoke(LambdaInvocationHandler.java:64)at java.lang.reflect.Proxy.invoke(Proxy.java:393) at $Proxy0.GetAllSchoolsNames(Unknown Source)at com.innovdroid.awslambdatest.MainActivity$1.doInBackground(MainActivity.java:47)at com.innovdroid.awslambdatest.MainActivity$1.doInBackground(MainActivity.java:41) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237)at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWo…

http://stackoverflow.com/q/46834418
has body: Ok, decided to edit this real quick and just include my entire script here. This is my first 'real world' application using python, or, for that matter, any programming language. I've built a basic web scraper using a tutorial I found and am trying to add information and build upon it to create something more useful than it is. The problem I am having is that the information gathered has been relatively easy to get to so far, but now I am stuck on pulling the price out of this bit of code here, into my python script. I can get the price from here, but it's in a terrible formatting with characters and whitespace that I can't seem to figure out how to strip, which completely ruins my .csv file at the end of the code. from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq my_url = "https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38? Tpk=graphics%20cards" #Grabbing the page uClient = uReq(my_url) #Reading uCLient and saving contents as a variable called page_html (it is raw html code) page_html = uClient.read() #Close the web connection to uCLient uClient.close() #html parsing page_soup = soup(page_html, "html.parser") #Grabs graphics card containers / each product containers = page_soup.findAll("div",{"class":"item-container"}) filename = "products.csv" f = open(filename, "w") headers = "Brand, Product Name, Price, Shipping\n" f.write(headers) for container in containers: brand = container.div.div.a.img["title"] title_container = container.findAll("a",{"class":"item-title"}) product_name = title_container[0].text price_container = container.findAll("li",{"class":"price-current"}) price = price_container[0].text.strip('|') shipping_container = container.findAll("li",{"class":"price-ship"}) shipping = shipping_container[0].text.strip() print("Brand: " + brand) print("Product name: " + product_name) print("Price: " + price) print("Shipping: " + shipping) f.write(brand + "," + product_name.replace(",","|") + "," + price + "," + shippi…
upvote count: 2
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/80623330
score: 2
has answer: http://stackoverflow.com/a/46860321
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/80616767
has title: How do I pull a specific bit of information from html to a python webscraper?
has answer: http://stackoverflow.com/a/46835105
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/80575146
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46813929
has text: What order you really want the columns to be changed.?
type: AnswerComment

http://stackoverflow.com/q/46841062
tagged with: network-programming
downvote count: 0
has body: I have been trying to debug this error I've been getting for a while to no success. It is a basic socket program using python that takes in a lower case sentence from the client and the server returns it in uppercase form. The client file works perfectly fine, however I keep getting this error when trying to run "python server.py" in the console, returning this message: [yanb@athena:45]&gt; python server.py Traceback (most recent call last): File "server.py", line 7, in &lt;module&gt; serverSocket.bind(('',serverPort)) File "&lt; string &gt;", line 1, in bind socket.error: [Errno 98] Address already in use Here is my code: client.py from socket import * serverName = '127.0.0.1' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName,serverPort)) sentence = raw_input('Input lowercase sentence:') clientSocket.send(sentence) modifiedSentence = clientSocket.recv(1024) print 'From Server:', modifiedSentence clientSocket.close() server.py from socket import * serverPort = 12000 serverSocket = socket(AF_INET,SOCK_STREAM) serverSocket.bind(('',serverPort)) serverSocket.listen(1) print 'The server is ready to receive' while 1: connectionSocket, addr = serverSocket.accept() sentence = connectionSocket.recv(1024) capitalizedSentence = sentence.upper() connectionSocket.send(capitalizedSentence) connectionSocket.close()
has comment: http://stackoverflow.com/comment/80630122
tagged with: python
score: 1
favorite count: 0
answer count: 0
linked to: http://stackoverflow.com/q/19071512
type: UnansweredQuestion
tagged with: sockets
upvote count: 1
has comment: http://stackoverflow.com/comment/80630642
has title: Python Socket Program error when trying to run server
has comment: http://stackoverflow.com/comment/80630569
type: Question

http://stackoverflow.com/comment/80771113
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46896757
has text: @sayedgouda well Python needs to know which file to rename to what, so they have to follow some kind of format so here it is `history (x)` but you could easily modify the `code` for a different format... And what happened to the `up-vote`? **:P**

http://stackoverflow.com/comment/80622862
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46835859
has text: Spotted the problem, fixed second solution. Should be the right one for sure this time.

http://stackoverflow.com/a/46905620
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46905530
has body: Q1: It is at least concurrency, can be parallelism as well (terms intended as defined in the answer to this question). Clearly, if you have one processor only, true parallellism cannot be achieved, becuse only one process can use the CPU at a single time. In that case, however, the muliprocessing library still allows you to define multiple tasks, that run in separate processes. It will be the OS's scheduler to decide which process runs when. Q2: Multiprocessing (...which is kind of implied by the library name). Due to the Global Interpreter Lock present in most Python interpreter implementations, parallelism with threads is impossible. Multiprocessing offers a threading-like interface that makes use of processes under the hood. Q3: It doesn't. Python spawns processes, the OS scheduler decided who runs where and when. There are some ways to execute processes on specific CPUs, but this is not the default behaviour of multiprocessing (and I'm not aware of any way to force the library to pin processes to CPUs).
type: Answer
upvote count: 1

http://stackoverflow.com/q/46825924
has answer: http://stackoverflow.com/a/46826774
has answer: http://stackoverflow.com/a/46828409
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/46826774
has comment: http://stackoverflow.com/comment/80599493
has comment: http://stackoverflow.com/comment/80599424
downvote count: 0
has title: Change pixel shape in matplotlib imshow function
has comment: http://stackoverflow.com/comment/80599929
accepted answer: http://stackoverflow.com/a/46828409
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80599726
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/13384653
has body: I am trying to reproduce a figure from a paper in matplotlib, shown below. Basically, each cell has a percentage in it, and the higher the percentage, the darker the background of the cell: The code below produces something similar, but each cell is a square pixel and I would like for them to be flatter rectangles rather than squares, as in the above image. How can I achieve this with matplotlib? import numpy as np import matplotlib.pyplot as plt import itertools table = np.random.uniform(low=0.0, high=1.0, size=(10,5)) class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] plt.figure() plt.imshow(table, interpolation='nearest', cmap=plt.cm.Greys, vmin=0, vmax=1) plt.yticks(np.arange(10), class_names) for i,j in itertools.product(range(table.shape[0]), range(table.shape[1])): plt.text(j, i, format(table[i,j], '.2f'), horizontalalignment="center", color="white" if table[i,j] &gt; 0.5 else "black") plt.show() Here's what this code above produces: I suspect that changing the aspect and the extent for imshow may help me here. I don't fully understand how this works, but here's what I've tried: plt.imshow(table, interpolation='nearest', cmap=plt.cm.Greys, vmin=0, vmax=1, aspect='equal', extent=[0,14,10,0]) This produces the following: I realise that I also need to add the borders between the cells, remove the tick marks, and change the values to percentages rather than decimals, and I am confident that I will be able to do this by myself, but if you want to help me out with that too then please feel free!

http://stackoverflow.com/q/46774161
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80494066
type: Question
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/46766416
possible better answer: http://stackoverflow.com/a/46774616
has title: Assign a series to ALL columns of the dataFrame (columnwise)?
has answer: http://stackoverflow.com/a/46774616
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46774324
linked to: http://stackoverflow.com/q/44806006
favorite count: 0
has body: I have a dataframe, and series of the same vertical size as df, I want to assign that series to ALL columns of the DataFrame. What is the natural why to do it ? For example df = pd.DataFrame([[1, 2 ], [3, 4], [5 , 6]] ) ser = pd.Series([1, 2, 3 ]) I want all columns of "df" to be equal to "ser". PS Related: One way to solve it via answer: How to assign dataframe[ boolean Mask] = Series - make it row-wise ? I.e. where Mask = true take values from the same row of the Series (creating all true mask), but I guess there should be some more simple way. If I need NOT all, but SOME columns - the answer is given here: Assign a Series to several Rows of a Pandas DataFrame
has answer: http://stackoverflow.com/a/46774324
tagged with: python
has comment: http://stackoverflow.com/comment/80494403

http://stackoverflow.com/comment/80499354
comment on: http://stackoverflow.com/q/46776746
has text: Yes, no luck either...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80499560
comment on: http://stackoverflow.com/q/46776746
type: Comment
has text: @csrf_exempt and it is fixed
type: QuestionComment
score: 1

http://stackoverflow.com/a/46790171
has body: First i would make a dataframe of the grouped data so we can easily slice and/or filter the data. #Option 1: Filter input dataframe return_data=return_data.ix[return_data.year.isin(list(np.arange(1981,1993,1)))] temp_return=pd.DataFrame(return_data[return_data['Country']==4184].groupby(['Year','Cause']).max())
has comment: http://stackoverflow.com/comment/80552875
has comment: http://stackoverflow.com/comment/80569553
answers question: http://stackoverflow.com/q/46789023
score: 0
accepted answer of: http://stackoverflow.com/q/46789023
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/80527612

http://stackoverflow.com/comment/80490150
has text: Yes, i found out: two datafrmes with the same Column Names doesnt work: df['HOLIDAY'] = df['DATE'].isin(df2['DATE']).astype(int) gives me the error, but i changed the column name from df1 to another one, and now that works..i dont know why
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46770570

http://stackoverflow.com/q/46869227
score: 0
tagged with: mocking
answer count: 1
has title: How can I mock.patch in web script via HTTPServer?
has comment: http://stackoverflow.com/comment/80690165
has answer: http://stackoverflow.com/a/46870142
tagged with: python
type: UnansweredQuestion
tagged with: httpserver
has comment: http://stackoverflow.com/comment/80690024
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/80687369
has body: I'd like to unittest web script on HTTPServer. But mock.patch isn't working via HTTPServer. it seems kicking subprocess inside. For example, my web scripts has some external web access. web script: #!/usr/bin/python3 import requests class Script: def main(self): res = requests.put('http://www.google.co.jp') # get response code 405 print('Content-type: text/html; charset=UTF-8\n') print(res.content) if __name__ == '__main__': Script().main() And my test script seems it can't mock the external web access. test script: import unittest import requests from http.server import HTTPServer, CGIHTTPRequestHandler from threading import Thread from unittest import TestCase, mock class MockTreadTest(TestCase): def test_default(self): server = HTTPServer(('', 80), CGIHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.start() try: with mock.patch('requests.put', return_value=' mocked response ') as put: res = requests.get('http://localhost/cgi-bin/script.py') self.assertRegex(str(res.content), 'mocked response') # fail self.assertRegex(put.call_args_list[0][0][0], 'http://www.google.co.jp') finally: server.shutdown() server_thread.join() if __name__ == "__main__": unittest.main()
type: Question

http://stackoverflow.com/comment/80567484
has text: @HyunMoLukeYang To initiate an empty list which you fill your values to.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46810104

http://stackoverflow.com/comment/112916622
has text: how to access this generate_cool_page function from c#
comment on: http://stackoverflow.com/a/46766406
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80570414
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/46811558
type: Comment
has text: `signal` is a module in the standard library; you are importing that, not your `signal.py`.

http://stackoverflow.com/comment/80484854
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46769751
has text: Your `DISerializer.devicedetails` attribute does not have a `source` parameter specified. This means the default behavior will be invoked - looking for an attribute by that name on the `Device` object.

http://stackoverflow.com/a/46814162
has body: If I understand now what you need it is just the following: #!/usr/bin/env python import sys original_fn = sys.argv[1] company_fn = sys.argv[2] fpOriginal = open(original_fn, "r") for lineCompany in open(company_fn, "r").readlines(): if lineCompany.startswith('*'): sys.stdout.write( fpOriginal.readline() ) fpOriginal.readline() else: sys.stdout.write( lineCompany ) fpOriginal.close()
has comment: http://stackoverflow.com/comment/80600032
has comment: http://stackoverflow.com/comment/80603233
score: 0
answers question: http://stackoverflow.com/q/46796663
type: Answer
has comment: http://stackoverflow.com/comment/80576348

http://stackoverflow.com/comment/80593874
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46823196
type: Comment
has text: Why can't you just sort on stock name (omitting timestamp in sort order) and apply what is suggested originally? I believe @Tahseen has commented the same thing above.

http://stackoverflow.com/q/46809693
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80567033
has answer: http://stackoverflow.com/a/46986804
accepted answer: http://stackoverflow.com/a/46986804
type: Question
has comment: http://stackoverflow.com/comment/80599165
upvote count: 2
score: 0
downvote count: 2
has body: I'm creating a login system and using a SQLite3 database in python. I have a table called users, containing the username and password that a user enters when creating an account. The username is the primary key. How can I check if a username already exists in the table, allowing me to prompt the user to choose a different name? Thanks.
tagged with: sqlite
answer count: 1
has title: Can I check if a primary key exists within a SQLite table? [python]
favorite count: 0
tagged with: python

http://stackoverflow.com/q/46825382
score: 0
has comment: http://stackoverflow.com/comment/80618851
has title: how to use aliases in graphene-django
tagged with: graphene-python
answer count: 1
accepted answer: http://stackoverflow.com/a/46835809
has answer: http://stackoverflow.com/a/46835809
has body: I'm using python 3.5 with Django==1.11.6 graphene==2.0.dev20170802065539 graphene-django==2.0.dev2017083101 graphql-core==2.0.dev20171009101843 graphql-relay==0.4.5 I have a schema that fetch's single objects like this: class Query(graphene.AbstractType): story = graphene.Field(storyType, category=graphene.String(), id=graphene.Int()) def resolve_story(self, info, **kwargs): category = kwargs.get('category') id = kwargs.get('id') if category is not None: return models.story.objects.get(category=models.category.objects.get(name=category)) if id is not None: return models.story.objects.get(pk=id) return None My problem is that I can't use both story(category:"category") and (id:"id") in one query. I read here that I should use aliases but I don't know how. Thank's for any help.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80627604
type: Question
has comment: http://stackoverflow.com/comment/80622866
tagged with: graphql
tagged with: django
tagged with: python

http://stackoverflow.com/a/46886567
upvote count: 0
accepted answer of: http://stackoverflow.com/q/46886513
score: -1
answers question: http://stackoverflow.com/q/46886513
has body: open('/relative//path//to//file', 'r') If its windows dont forget put // otherwise python will not interpret it properly
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/comment/80578699
comment on: http://stackoverflow.com/a/46815714
has text: Did you try your steps out yourself?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/106627788
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/46936208
type: Comment
has text: You are awesome. Thank you so much, I've been trying to do this installation on my workstation for 20 work hours! thanks!

http://stackoverflow.com/comment/80560435
score: 0
comment on: http://stackoverflow.com/a/46806130
type: Comment
has text: oh okey but that gives me only 1 element, what if i had 100.(that's basically why i use ifs).
type: AnswerComment

http://stackoverflow.com/comment/80684766
type: QuestionComment
has text: Can you please add the content of `load_config()` function? Also, what do you mean by "crashes my machine"? How does it look like?
comment on: http://stackoverflow.com/q/46856502
score: 0
type: Comment

http://stackoverflow.com/comment/80673194
comment on: http://stackoverflow.com/q/46862874
type: Comment
score: 0
has text: you can write it as: `lambda x, j=i: x[j] - 1`
type: QuestionComment

http://stackoverflow.com/a/46794505
score: 79
accepted answer of: http://stackoverflow.com/q/46785507
type: Answer
has comment: http://stackoverflow.com/comment/95923660
has comment: http://stackoverflow.com/comment/86915865
has comment: http://stackoverflow.com/comment/134419716
has body: I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template. In application.py: from flask import Flask, render_template import os PEOPLE_FOLDER = os.path.join('static', 'people_photo') app = Flask(__name__) app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER @app.route('/') @app.route('/index') def show_index(): full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg') return render_template("index.html", user_image = full_filename) In index.html: Index Output:
upvote count: 81
downvote count: 2
has comment: http://stackoverflow.com/comment/95930281
has comment: http://stackoverflow.com/comment/106324668
has comment: http://stackoverflow.com/comment/86920902
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101421178
answers question: http://stackoverflow.com/q/46785507

http://stackoverflow.com/comment/80587080
has text: yes. thank you got it :)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46819292

http://stackoverflow.com/comment/80642291
has text: Well, this confusion makes it harder to understand your goal: could you provide us some accurate timestamps for checking our own solutions? Also, expected outputs are welcome too!
score: 0
comment on: http://stackoverflow.com/q/46846950
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46897153
downvote count: 2
has comment: http://stackoverflow.com/comment/80741951
type: Question
score: -2
has answer: http://stackoverflow.com/a/46897206
has comment: http://stackoverflow.com/comment/80741433
has comment: http://stackoverflow.com/comment/80741624
has comment: http://stackoverflow.com/comment/80741514
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/46897315
favorite count: 0
has title: error generating random number in python
tagged with: python
has body: Hi I am trying to generate 10 random numbers which are multiples of 5 in the range 1 to 100 import random f = [] for x in range(1,10): f = random.randint(1,101) for i in range(10): while f(i)%5.0 == 0.0: #multiples of 5 print f(i) But it's showing TypeError: 'int' object is not callable Any help
type: UnansweredQuestion

http://stackoverflow.com/comment/80667110
has text: Of possible interest: [Wrapping big list in Python 2.7 to make it immutable](https://stackoverflow.com/questions/21000994/wrapping-big-list-in-python-2-7-to-make-it-immutable#21001628)
comment on: http://stackoverflow.com/q/46859511
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/80514632
score: 0
comment on: http://stackoverflow.com/q/46783887
type: Comment
type: QuestionComment
has text: I followed this tutorial for that purpose: https://godjango.com/65-starting-with-django-allauth/

http://stackoverflow.com/a/46753984
has comment: http://stackoverflow.com/comment/80453733
type: Answer
score: 1
has body: The following code should do it. d1={} for key,val in d.items(): if key in pos and key&lt;=n : #the elements that had a key from the group num_positive in d, will have the same key in d2 d1[key] = val elif key in neg and ((key+n) in range(n+1)) : #the elements that had a negative key i from the group num_negative in d, will have the key n+i in d2 d1[key+n] = val #driver values : IN : n = 8 IN : pos = [0,1] IN : neg = [-3,-2,-1] IN : d = {-6: 'h', -3: 'a', -2: 'b', -1: 'c', 0: 'd', 1: 'e', 68: 'f', 99: 'g'} OUT : d1 = {5: 'a', 6: 'b', 7: 'c', 0: 'd', 1: 'e'} NOTE : there are some discrepancies in the OP's output. Few of them behave differently than what's defined. So, the keys that do not follow given constraints are ignored.
upvote count: 1
has comment: http://stackoverflow.com/comment/80453670
downvote count: 0
answers question: http://stackoverflow.com/q/46753672

http://stackoverflow.com/q/46772787
score: 1
has comment: http://stackoverflow.com/comment/80491320
type: Question
answer count: 1
has body: So, I am curently trying to write a programm that, when I input a number, it outputs all the numbers in the first numbers range, that can be divided by 3. The code looks like this, but it is only outputing 0 for me, and I have looked trough simillar situations to no awail. n = "" print('Ievadi skaitli') n = int( input( '==&gt; ' ) ) i = 0 print("Izvada skaitļus kas dalās ar 3" ) while i &lt;= n: if i%3==0: print(i, end = " " ) i += 1 Maby someone can point me in the right dirrection and tell me, what am I missing
has title: How do I make python show only dividable numbers
favorite count: 0
has comment: http://stackoverflow.com/comment/80491821
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/46772887

http://stackoverflow.com/q/46848095
type: Question
has comment: http://stackoverflow.com/comment/80643820
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47138806
answer count: 1
has comment: http://stackoverflow.com/comment/80670389
has comment: http://stackoverflow.com/comment/80645492
has comment: http://stackoverflow.com/comment/80647894
has comment: http://stackoverflow.com/comment/80645694
has body: I have a cython extension inside a package which is structured like so: packagename ├── MANIFEST.in ├── packagename │ ├── __init__.py │ ├── packagename.py │ ├── subpackage1 │ │ ├── __init__.py │ │ ├── subpackage1.py │ │ └── cythonExt1.pyx │ ├── subpackage2 │ │ ├── __init__.py │ │ ├── subpackage2.py │ │ └── cythonExt2.pyx │ └── VERSION ├── requirements.txt └── setup.py When I try to add a line in cythonExt2.pyx which imports numpy I get the following error: ------------------------------------------------------------- SystemError Traceback (most recent call last) &lt;ipython-input-5-5c4ef4d8efd3&gt; in &lt;module&gt;() 1 # Calling Functions of Interest ----&gt; 2 import pacakge.subpackage2 as thingy 3 import numpy as np 4 import matplotlib.pyplot as plt /home/user/anaconda2/envs/python3/lib/python3.5/site-packages/pacakage-0.0.3-py3.5-linux-x86_64.egg/package/__init__.py in &lt;module&gt;() 18 19 # the following line imports all the functions from package.py ---&gt; 20 from .package import * 21 import package.subpackage1 22 import package.subpackage2 /home/user/anaconda2/envs/python3/lib/python3.5/site-packages/package-0.0.3-py3.5-linux-x86_64.egg/package/package.py in &lt;module&gt;() 1 from package.subpackage1 import thingy1 ----&gt; 2 from package.subpackage2 import thingy2 3 import numpy as _np 4 from multiprocessing import Pool as _Pool /home/user/anaconda2/envs/python3/lib/python3.5/site-packages/package-0.0.3-py3.5-linux-x86_64.egg/package/subpackage2/subpackage2.py in &lt;module&gt;() 3 import os ----&gt; 4 from cythonExt2 import solve as solve_cython 5 from frange import frange 6 /home/user/anaconda2/envs/python3/lib/python3.5/site-packages/package-0.0.3-py3.5-linux-x86_64.egg/package/subpackage2/cythonExt2.pyx in init package.subpackge2.cythonExt2 (package/subpackage2/cythonExt2.c:6158)() 1 cimport numpy ----&gt; 2 import numpy 3 cimport cython 4 5 def get_z_n(n, z): SystemError: Parent module '' not loaded, cannot perform relative import If I just cimport …
tagged with: python
has comment: http://stackoverflow.com/comment/80647530
has title: Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Extension
score: 0
tagged with: cython
has answer: http://stackoverflow.com/a/47138806
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80669846
has comment: http://stackoverflow.com/comment/80645385
has comment: http://stackoverflow.com/comment/80670399

http://stackoverflow.com/q/46766174
tagged with: python
has body: Trying to sort by two fields, giving priority to first - but instead seems like priority is given to the second (lastName), in the majority of cases. Occasionally, it works correctly - not sure what makes the change. The same command works fine using Robo3t as client, connecting with the same database. Running Flask and using Mongoengine, with the code below: pipeline = [{"$sort": {"importance": -1, "lastName": 1}}, {"$match": {"visible": True, "editionId": "2017"}}, {"$project": {'firstName': 1, 'lastName': 1, 'biography': 1, 'position': 1, 'workAt': 1, '_id': 0, "imageUrl": 1}}] doc = Speakers.objects.aggregate(*pipeline) Same code (except 'True' becomes 'true'), in Robo3t: db.getCollection('speakers').aggregate([{"$sort": {"importance": -1, "lastName": 1}}, {"$match": {"visible": true, "editionId": "2017"}}, {"$project": {'firstName': 1, 'lastName': 1, 'biography': 1, 'position': 1, 'workAt': 1, '_id': 0, "imageUrl": 1}}], {"collation": {"locale": "en"}} ) Indexes on mongodb (3.4.9) look as below: &gt; db.speakers.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "website_v3.speakers" } ] Using db version v3.4.9 I had even tried creating an index (collation) for importance, but exactly the same happened. First it works, then it doesn't. Any ideas welcome! EDIT: It seems like flask_mongoengine is messing with the order of $sort, as well as $project. mongo &gt; db.system.profile.find().pretty() { "op" : "query", "ns" : "website_v3.system.profile", "query" : { "find" : "system.profile", "filter" : { } }, "keysExamined" : 0, "docsExamined" : 0, "cursorExhausted" : true, "numYield" : 0, "locks" : { "Global" : { "acquireCount" : { "r" : NumberLong(2) } }, "Database" : { "acquireCount" : { "r" : NumberLong(1) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(1) } } }, "nreturned" : 0, "responseLength" : 98, "protocol" : "op_command", "millis" : 0, "planSummary" : "COLLSCAN", "execStats" : { "stage" : "COLLSCAN", "nReturned" : 0, "execution…
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/15204341
score: 1
tagged with: flask-mongoengine
tagged with: mongoengine
has title: MongoEngine (flask) does not sort (via aggregate) correctly - every now and then
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/46778014
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/114343964
score: 0
type: AnswerComment
has text: This was a super simple solution to a big optimization issue on my end with user groups. Thanks!
comment on: http://stackoverflow.com/a/62080682
type: Comment

http://stackoverflow.com/comment/80737938
has text: `print(findall("Good[\s\S]*?Afternoon"))` what do you see?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46895303

http://stackoverflow.com/comment/80692793
score: 0
comment on: http://stackoverflow.com/q/46872756
type: QuestionComment
type: Comment
has text: @Reti43 Yes, it is a typo

http://stackoverflow.com/comment/80732073
has text: Yes looking at it right now, thank for the help!
type: QuestionComment
comment on: http://stackoverflow.com/q/46892046
score: 0
type: Comment

http://stackoverflow.com/comment/81012803
comment on: http://stackoverflow.com/q/46842793
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ is it possible to post the complete expected output?
score: 0
type: QuestionComment

http://stackoverflow.com/q/46824239
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80621897
tagged with: python-packaging
has answer: http://stackoverflow.com/a/46850282
tagged with: cython
accepted answer: http://stackoverflow.com/a/46850282
tagged with: pypi
type: Question
score: 5
answer count: 1
has title: Python packaging: Boost library as dependency
has comment: http://stackoverflow.com/comment/80652434
tagged with: python
has comment: http://stackoverflow.com/comment/80643541
favorite count: 0
upvote count: 5
downvote count: 0
tagged with: boost
has body: Assume that someone wants to package a Python (Cython) library that depends on the C++ boost library. What is the best way to configure the setup.py so that the user is properly informed that it is required to install the boost library (i.e., apt-get install libboost-dev in Ubuntu, etc in other OSes)? Or is it a better practice to include the boost library in the python package distribution?

http://stackoverflow.com/q/46750737
accepted answer: http://stackoverflow.com/a/46750888
answer count: 2
has comment: http://stackoverflow.com/comment/80447418
has comment: http://stackoverflow.com/comment/80447435
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80447394
has body: I've imported a cool package (if it matters, it's called tweepy). But there is a small limitation with 2 of the methods due to a recent change Twitter made. There's already a fix but it hasn't been pulled for some time I was considering trying to temporarily add the fix on my side and override the existing modules until the package is updated, although I'm not quite as experienced with python def statuses_lookup(self, id_, include_entities=None, trim_user=None, map_=None): return self._statuses_lookup(list_to_csv(id_), include_entities, trim_user, map_) @property def _statuses_lookup(self): """ :reference: https://dev.twitter.com/rest/reference/get/statuses/lookup :allowed_param:'id', 'include_entities', 'trim_user', 'map' """ return bind_api( api=self, path='/statuses/lookup.json', payload_type='status', payload_list=True, allowed_param=['id', 'include_entities', 'trim_user', 'map'], require_auth=True ) and overriding that with a similar (difference being adding an extra argument tweet_mode as far as I'm aware): def statuses_lookup(self, id_, include_entities=None, trim_user=None, map_=None, tweet_mode=None): return self._statuses_lookup(list_to_csv(id_), include_entities, trim_user, map_, tweet_mode) @property def _statuses_lookup(self): """ :reference: https://dev.twitter.com/rest/reference/get/statuses/lookup :allowed_param:'id', 'include_entities', 'trim_user', 'map', 'tweet_mode' """ return bind_api( api=self, path='/statuses/lookup.json', payload_type='status', payload_list=True, allowed_param=['id', 'include_entities', 'trim_user', 'map', 'tweet_mode'], require_auth=True ) I've never really tried something like this before in python 3.X
tagged with: python
tagged with: tweepy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46750888
possible better answer: http://stackoverflow.com/a/46750841
has title: override python module with one that has an extra argument - python
score: 1
has answer: http://stackoverflow.com/a/46750841
upvote count: 1
type: Question

http://stackoverflow.com/a/46770144
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46768159
has body: You can do it manually like this: a_string = u"abcdeFghijklmn" # Let say it is cyrillic with one latin letter represented here by 'F' (uppercase) # To change it to cyrillic i.e. here to lower latin you would do: l2c = {u"F": u"f"} # Map all latin to cyrillic for real l2c_get = l2c.get # Faster access but not necessary a_string = u"".join( l2c_get(x, x) for x in a_string) Of course, you can use unicode.translate() method which should do the same. When your 'a_string' is processed then just push it back to django. All mapped latins to cyrillic will be substituted. Just pay attention that everything is unicode in the mapping. If putting the translated string to django raises the UnicodeDecode/Encode error, it means that you should before try: a_string = a_string.encode("utf-8", "ignore") UTF-8 in binary should be accepted.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46768159
type: AcceptedAnswer

http://stackoverflow.com/q/46806699
upvote count: 4
has title: Use case for "import as" in Python
answer count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/80560652
tagged with: pep8
downvote count: 0
has comment: http://stackoverflow.com/comment/80560520
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80560764
possible better answer: http://stackoverflow.com/a/46807230
has answer: http://stackoverflow.com/a/46807230
has comment: http://stackoverflow.com/comment/80560445
has comment: http://stackoverflow.com/comment/80560428
tagged with: python-module
tagged with: python
has comment: http://stackoverflow.com/comment/130165354
has body: I am wondering if we can use "import as" for creating relatively compact or readable code. I am aware of its usual use cases based on PEP such as to void name clashes. Here is the situation (keeping it very simple for the demonstration purpose). Let's say I have a module name, process_words.py. process_words.py: def word_to_lower(word): return word.lower process_article.py (lets the main script): import process_words word = "HELLO" word_lower = process_words.word_to_lower(word) print(word_lower) Now would it be a bad or good practice to do something like this?: import process_words as pw word = "HELLO" word_lower = pw.word_to_lower(word) print(word_lower) It's a very simplistic example. I have a couple of modules with each module having a couple of functions. Importing each function with from module import something isn't an option. To me, it feels like, if I use import as with some shortcut names, it will improve the code readability. Any thoughts? NOTE: I am referring to custom modules here.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80560483
has answer: http://stackoverflow.com/a/46860500
linked to: http://stackoverflow.com/q/72504576
type: Question
has comment: http://stackoverflow.com/comment/80560539
score: 4
accepted answer: http://stackoverflow.com/a/46860500
has comment: http://stackoverflow.com/comment/80560546

http://stackoverflow.com/comment/80677309
has text: Not to offend asker or anyone. (1) write a for loop to count character is basic, and doesn't use `.count()`; (2) we don't do homework for no good evidence of your effort.
comment on: http://stackoverflow.com/q/46864839
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46855313
has body: #!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector import json import pandas as pd con = mysql.connector.connect(user='',password='',host='',database='') cursor = con.cursor() sqlquery = "blahblahblah" print sqlquery searches = [] print searches cursor.execute(sqlquery) for row in cursor: try: searchname = row[0].encode("utf-8") queryobject = row[1].encode("utf-8") except: print('Query not found') json_dict = json.loads(queryobject) searches.append(json_dict) print searchs pd.DataFrame(searches).to_csv('datefile.csv', index=False) Hey, i'm trying to input the above rows into a CSV which is working, however due to what I assume is unicode, the output has a 'u' before every word. The data is fine up until json_dict = json.loads(queryobject). Any help would be greatly appreciated, this is driving me mad.
has comment: http://stackoverflow.com/comment/80658881
has title: Python Unicode Exporting to CSV, removing 'u' character
tagged with: mysql
has comment: http://stackoverflow.com/comment/80662656
type: Question
answer count: 2
upvote count: 1
tagged with: unicode
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
has answer: http://stackoverflow.com/a/46855475
has comment: http://stackoverflow.com/comment/80658226
favorite count: 0
has comment: http://stackoverflow.com/comment/80658176
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/956867
tagged with: python
has answer: http://stackoverflow.com/a/46855772

http://stackoverflow.com/a/46805814
has body: I think its a Tensorflow version problem. In my version (1.2.1), I get the exact desired output from your inputs. However, I also tried the following code according to the older version. import tensorflow as tf indices = [[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3]], [[0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 1, 3]], [[1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 0, 3]]] params = [[[ 0., 0., 1., 2.], [ 0., 0., 2., 2.], [ 0., 0., 3., 3.], [ 0., 0., 4., 3.], [ 0., 0., 5., 4.], [ 0., 0., 6., 4.], [ 0., 0., 7., 5.]], [[ 1., 1., 0., 2.], [ 1., 2., 0., 2.], [ 1., 3., 0., 3.], [ 1., 4., 0., 3.], [ 1., 5., 0., 4.], [ 1., 6., 0., 5.], [ 1., 7., 0., 5.]]] output = tf.gather_nd(params, indices) with tf.Session()as sess: print (sess.run(output)) Hope this helps.
answers question: http://stackoverflow.com/q/46804332
score: 0
type: Answer

http://stackoverflow.com/comment/80531422
type: Comment
comment on: http://stackoverflow.com/q/46792252
score: 0
has text: pip and scipy is (currently) not a good idea on windows (but numpy should probably work)! (Gohlke's binaries can work; but care is needed)
type: QuestionComment

http://stackoverflow.com/q/46855551
linked to: http://stackoverflow.com/q/11040177
tagged with: date-format
tagged with: python
has title: Python change a date format in dataframe
accepted answer: http://stackoverflow.com/a/46855616
has body: I have a dataset containing a column "date": date item 20.3.2010 17:08 a 20.3.2010 11:16 b 2010-03-20 15:55:14.060 c 2010-03-21 13:56:45.077 d I would like to convert all values that have format as 20.3.2010 17:08 into 2010-03-21 13:56:45.077. Does anybody have an idea? Thank you.
tagged with: pycharm
type: AnsweredQuestion
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46855616
possible better answer: http://stackoverflow.com/a/46855589
has answer: http://stackoverflow.com/a/46855589
score: 0

http://stackoverflow.com/comment/80632456
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46838810
type: Comment
has text: Yes, so you call the functions from inside the `__missing__`. Try it, I'll leave that part up to you.

http://stackoverflow.com/comment/80659456
type: AnswerComment
comment on: http://stackoverflow.com/a/46855157
type: Comment
score: 0
has text: I see. Now it makes sense! :) Thanks

http://stackoverflow.com/comment/80688144
has text: What other details are needed? Shouldn't i be able to access `/auth` as long as my code contains the lines above?
comment on: http://stackoverflow.com/a/46870360
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46891581
has comment: http://stackoverflow.com/comment/80730412
upvote count: 0
has body: Use a for loop, and make sure you have spaces in the correct place for the command part. import os def get_nmap(options,ip): command = "nmap " + options + " " + ip process = os.popen(command) result = str(process.read()) return result for ip in range(0, 65535): print(get_nmap('-F', str(ip)))
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/46891422
type: Answer

file
type: Tag
tags question: http://stackoverflow.com/q/46803803
tags question: http://stackoverflow.com/q/46754658
tags question: http://stackoverflow.com/q/46835474
tags question: http://stackoverflow.com/q/46749172
tags question: http://stackoverflow.com/q/46749825
tags question: http://stackoverflow.com/q/46839909
tags question: http://stackoverflow.com/q/46788734
tags question: http://stackoverflow.com/q/46864338
tag name: file
tags question: http://stackoverflow.com/q/46899900
tags question: http://stackoverflow.com/q/46863879
tags question: http://stackoverflow.com/q/46795512
tags question: http://stackoverflow.com/q/46854659
tags question: http://stackoverflow.com/q/46767256
tags question: http://stackoverflow.com/q/46753638
tags question: http://stackoverflow.com/q/46798448
tags question: http://stackoverflow.com/q/46755002
tags question: http://stackoverflow.com/q/46801059
tags question: http://stackoverflow.com/q/46843833
tags question: http://stackoverflow.com/q/46757225
tags question: http://stackoverflow.com/q/46863924
tags question: http://stackoverflow.com/q/46757531
tags question: http://stackoverflow.com/q/46818539
tags question: http://stackoverflow.com/q/46780577
tags question: http://stackoverflow.com/q/46798074
tags question: http://stackoverflow.com/q/46819094
tags question: http://stackoverflow.com/q/46903114
tags question: http://stackoverflow.com/q/46764283
tags question: http://stackoverflow.com/q/46810255
tags question: http://stackoverflow.com/q/46869520
tags question: http://stackoverflow.com/q/46760771
tags question: http://stackoverflow.com/q/46754592
tags question: http://stackoverflow.com/q/46824280
tags question: http://stackoverflow.com/q/46867675
tags question: http://stackoverflow.com/q/46814874

http://stackoverflow.com/comment/80737784
score: 0
type: Comment
has text: Yes, now this program works only with this dictionary. But I would like to be able to submit any such dictionary to the input, and get a plot on the output and not change the program code (do not write down the names of the needs each time: "need1", "need2",...., in program code).
comment on: http://stackoverflow.com/a/46797009
type: AnswerComment

http://stackoverflow.com/comment/80467793
has text: no I tried that snippet as well, the original order is still preserved. No sorting appears to have taken place.
comment on: http://stackoverflow.com/a/46761051
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46805811
has answer: http://stackoverflow.com/a/46809372
has body: I am trying to present a graph that shows the current progress with an ongoing project. So basically once you open the plot, it will show you a plot of Passed, Failed and not run test runs in a stacked area. I want to drilldown on the main data (Passed, Failed, Not Run). I want to basically show the teams(s) that may have passed, failed, or not run. Let's say that you want to drill down on "Passed", once you click on "Passed", it should bring multiple series, each serie containing the team name and the amount of Passed tests. JSfiddle: https://jsfiddle.net/9aqbLzar/3/ Demo: Highcharts.Tick.prototype.drillable = function() {}; Highcharts.setOptions({ lang: { drillUpText: '◁ Go back' } }); Highcharts.chart('container', { chart: { type: 'area' }, xAxis: { type: 'datetime', tickmarkPlacement: 'on', title: { enabled: false } }, yAxis: { allowDecimals: false, title: { text: "Test runs" } }, tooltip: { shared: false }, plotOptions: { area: { stacking: 'normal', lineColor: null, lineWidth: 1, marker: { enabled: false, lineWidth: 1, lineColor: null, symbol: 'circle', radius: 3 } }, cursor: 'pointer', trackByArea: true }, series: [{ name: 'Passed', data: [{ x: Date.UTC(2017, 09, 06), y: 20, drilldown: 'Passed' }, { x: Date.UTC(2017, 09, 07), y: 21, drilldown: 'Passed' }, { x: Date.UTC(2017, 09, 08), y: 22, drilldown: 'Passed' }, { x: Date.UTC(2017, 09, 09), y: 23, drilldown: 'Passed' }] }, { name: 'Failed', data: [{ x: Date.UTC(2017, 09, 06), y: 6, drilldown: 'Failed' }, { x: Date.UTC(2017, 09, 07), y: 5, drilldown: 'Failed' }, { x: Date.UTC(2017, 09, 08), y: 4, drilldown: 'Failed' }, { x: Date.UTC(2017, 09, 09), y: 3, drilldown: 'Failed' }] }, { name: 'Not run', data: [{ x: Date.UTC(2017, 09, 06), y: 8, drilldown: 'Not run' }, { x: Date.UTC(2017, 09, 07), y: 7, drilldown: 'Not run' }, { x: Date.UTC(2017, 09, 08), y: 6, drilldown: 'Not run' }, { x: Date.UTC(2017, 09, 09), y: 5, drilldown: 'Not run' }] } ], drilldown: { series: [{ id: 'Passed', data: [{ x: Date.UTC(2017, 09, 1…
has comment: http://stackoverflow.com/comment/80559690
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Highcharts: Stacked area drilldown to multiple series
has comment: http://stackoverflow.com/comment/80558757
accepted answer: http://stackoverflow.com/a/46809372
type: Question
type: AnsweredQuestion
tagged with: javascript
score: 0
answer count: 1
tagged with: highcharts

http://stackoverflow.com/a/46854605
has comment: http://stackoverflow.com/comment/80662466
has comment: http://stackoverflow.com/comment/80657756
answers question: http://stackoverflow.com/q/46854496
has body: You are building a bad path with img=Image.open('/Users/ajinkyabobade/Desktop/2'+filename) Try the following instead (by adding / to the end of the directory path) img=Image.open('/Users/ajinkyabobade/Desktop/2/'+filename) or img=Image.open(os.path.join('/Users/ajinkyabobade/Desktop/2', filename))
score: 1
has comment: http://stackoverflow.com/comment/80657047
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80656930
has comment: http://stackoverflow.com/comment/80662547
has comment: http://stackoverflow.com/comment/80657620

http://stackoverflow.com/comment/80515626
comment on: http://stackoverflow.com/q/46784648
has text: between which tensors? [batch_size, seq_length, 0] and [batch_size, seq_length, 1] ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46887762
has body: Is it possible to define specific text within selenium when searching for elements containing text. I am currently using "//tr/td[contains(text.." however I am having an issue as there are duplicate names in the xpath. E.G. I want to find the xpath name 'ABC123', however selenium is also picking up xpath name 'ABC1234'. Thanks in advance.
tagged with: selenium
downvote count: 1
type: Question
score: -1
has title: Selenium - Contains Text - Is possible to search for specific/literal text
has comment: http://stackoverflow.com/comment/80723279
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46889400
has comment: http://stackoverflow.com/comment/80722735

http://stackoverflow.com/comment/80668446
type: Comment
type: QuestionComment
has text: It's tricky to generalize your current mergesort algorithm because of the `sys.maxsize` sentinels that you append to the `L` and `R` sublists. If you tried to sort a list of lists, or even a list of strings, you'd need to use a different sentinel value. (For that matter, your code won't work properly on a list of integers if any of those integers were >`sys.maxsize`). So if you want a general version you first need to re-write `merge` so that it doesn't need those sentinels, or has some way of creating those sentinels that's not tied to `sys.maxsize`.
comment on: http://stackoverflow.com/q/46860219
score: 0

http://stackoverflow.com/q/46803270
has answer: http://stackoverflow.com/a/46803307
score: 0
answer count: 1
has body: i was try to find similiar question like i want to ask right now. But, the answer not really helping me. I was try to get value, but just one value if the value is same. here my code : first, i have condition like this ids_data = [] arr_rest_ids = [('8380128579', 309), ('8380128579', 311), ('8380128579', 310), ('8380222579', 313)] if arr_rest_ids: for i in arr_rest_ids: ids_data.append(i) I have condition string and integer, the condition tell that integer have a value. I was try to create a condition if the value is same than get the value just one. I want the result be like this : ids_data = [309, 313] arr_rest_ids = [('8380128579', 309), ('8380128579', 311), ('8380128579', 310), ('8380222579', 313)] if arr_rest_ids: for i in arr_rest_ids: ids_data.append(i) the ids_data variable show the id just a different value.
has title: Python, get value just one if the value is same
has comment: http://stackoverflow.com/comment/80553123
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: loops
type: Question
accepted answer: http://stackoverflow.com/a/46803307

http://stackoverflow.com/q/46773511
accepted answer: http://stackoverflow.com/a/46773797
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80492942
type: Question
type: AnsweredQuestion
has title: How to how to avoid duplicated code in if/else statement?
has comment: http://stackoverflow.com/comment/80493244
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80493079
has comment: http://stackoverflow.com/comment/80492818
has answer: http://stackoverflow.com/a/46773903
has comment: http://stackoverflow.com/comment/80492846
answer count: 2
possible better answer: http://stackoverflow.com/a/46773903
has answer: http://stackoverflow.com/a/46773797
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/80492885
has body: I have two exactly the same logic in if/else statement: if alert.get('comment_time_created') is None: here-&gt; args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time} await self._db_alert.update_alert(alert['alert_id'], **args) else: first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ') current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ') if current_comment_time &gt; first_comment_time_creation: await self._db_alert.update_alert(alert['alert_id'], is_comment_visible=1) else: here-&gt; args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time} await self._db_alert.update_alert(alert['alert_id'], **args) Is there any way to do this logic once?
tagged with: python
has comment: http://stackoverflow.com/comment/80493153
tagged with: python-3.x

http://stackoverflow.com/comment/80794210
has text: You have to take each (5,5) slice separately. Collect them in a list and/or concatenate as needed.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46841098

http://stackoverflow.com/a/46875983
type: Answer
has body: List comprehension may make your code simpler. from collections import defaultdict def words_often(freqs, min_times): words = [(key, freqs[key]) for key in freqs if freqs[key] &gt;= min_times] # words = [('yeah', 15), ('one', 1), ('crazy', 3), ('lonely', 1)] d = defaultdict(list) for word, freq in words: d[freq].append(word) # d = {15: ['yeah'], 1: ['one', 'lonely'], 3: ['crazy']} return [(d[freq], freq) for freq in d] # Test freqs = {'yeah':15, 'one': 1, 'crazy': 3, 'lonely': 1, 'zero':0} print(words_often(freqs, 1)) # [(['yeah'], 15), (['one', 'lonely'], 1), (['crazy'], 3)]
score: 0
has comment: http://stackoverflow.com/comment/80698901
answers question: http://stackoverflow.com/q/46875867

http://stackoverflow.com/a/68671400
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/46899540
upvote count: 0
type: Answer
has body: I used pyside2-uic to generate .py from .ui. Adding this is what worked for me. From: https://doc.qt.io/qtforpython/tutorials/basictutorial/uifiles.html class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) window = MainWindow() window.show()

http://stackoverflow.com/comment/80825827
score: 0
type: AnswerComment
has text: I like your generalization.
type: Comment
comment on: http://stackoverflow.com/a/46925147

http://stackoverflow.com/q/46890548
has answer: http://stackoverflow.com/a/46890716
type: Question
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/3289601
tagged with: if-statement
has answer: http://stackoverflow.com/a/46890718
has answer: http://stackoverflow.com/a/46890726
accepted answer: http://stackoverflow.com/a/46890600
favorite count: 0
possible better answer: http://stackoverflow.com/a/46890687
has answer: http://stackoverflow.com/a/46890687
has answer: http://stackoverflow.com/a/46890695
has answer: http://stackoverflow.com/a/46890600
answer count: 7
has title: IF statement with 2 variables and 4 conditions
has body: I have 2 variables, say x and y, and I need to check which of them is None if x is None and y is None: # code here else: if x is not None and y is not None: # code here else: if x is None: # code here if y is None: # code here Is there a better approach to do this? I am looking for a shorter IF ELSE structure.
linked to: http://stackoverflow.com/q/20420934
has answer: http://stackoverflow.com/a/46890707
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80731508
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/80568279
type: AnswerComment
type: Comment
has text: why downvoting this? the _question_ isn't very good, but the answer is spot on.
comment on: http://stackoverflow.com/a/46810155
score: 0

http://stackoverflow.com/comment/80554716
score: 0
type: AnswerComment
has text: Explicit is always better than Implicit :)
comment on: http://stackoverflow.com/a/46803458
type: Comment

http://stackoverflow.com/comment/80728085
type: Comment
comment on: http://stackoverflow.com/q/46890172
type: QuestionComment
has text: @roganjosh My issue was that "set the path" is not self-explanatory.
score: 0

http://stackoverflow.com/comment/80481855
score: 6
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46768268
has text: [`relevant_tokens = [token for token in tokens if not any(c.isdigit() for c in token)]`](https://ideone.com/WYIxED)?

http://stackoverflow.com/comment/80517015
type: Comment
type: AnswerComment
has text: Sadly, I'm not well versed in data.table. But there are some here (akrun, Sotos and others), who should be able to translate this into data.table.
score: 0
comment on: http://stackoverflow.com/a/46785306

http://stackoverflow.com/comment/80537545
has text: Can you run the python script on the command line - and does it download the file as expected?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46795467
type: QuestionComment

http://stackoverflow.com/comment/80660403
comment on: http://stackoverflow.com/q/46836499
has text: @BillBell I have tried that but getting encoding problem. Trying to solve encoding problem while receiving data. I have also asked the BCI forum.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46865320
has body: You haven't saved your source file as UTF-8. Configure your editor correctly. Alternatively, adjust your coding comment at the top; the default for Python 3 is UTF-8 but if you used a different codec you need to specify it in that comment. However,tThe encoding comment should appear in the first two lines of your file. You have it set on the third line. Quoting from the PEP linked in the error message: To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file[.] (Bold emphasis mine) Re-arrange your comments to: #!/usr/bin/env python # -*- coding: &lt;your codec&gt; -*- # Chap02-03/twitter_streaming.py I moved the first comment down; the #! line must be the first line in the file for it to work. You could also just remove it altogether, since you were not using it.
score: 0
has comment: http://stackoverflow.com/comment/80722552
type: Answer
has comment: http://stackoverflow.com/comment/80723674
answers question: http://stackoverflow.com/q/46865263

http://stackoverflow.com/q/46757757
has title: Python lists and computational complexity
has comment: http://stackoverflow.com/comment/80461336
has comment: http://stackoverflow.com/comment/80462143
has comment: http://stackoverflow.com/comment/80462755
linked to: http://stackoverflow.com/q/280243
has comment: http://stackoverflow.com/comment/80460931
type: Question
has comment: http://stackoverflow.com/comment/80460792
duplicate of: http://stackoverflow.com/q/280243
has comment: http://stackoverflow.com/comment/80462156
has comment: http://stackoverflow.com/comment/80460929
has comment: http://stackoverflow.com/comment/80460806
has comment: http://stackoverflow.com/comment/80462151
tagged with: python
has body: I'm writing a program in Python. The algorithm that I use is very slow (and it can't be faster for what I want to do) so how quickly the program will execute is important (in other words: computational complexity matters) and this is what I need to do: I have a list. I need to iterate the list and do some operation on every element. When iterating the list, I need to remove some elements from the list. This can be done very easily, but the problem is that I want removing element to have computational complexity O(1), not O(n), so that the entire process of iterating the list and removing some elements has computational complexity O(n). Now, I don't know what the internal implementation of python lists is, but I'm almost sure that when I remove element like that: del list[5] or like that: list.pop(5) It will probably have to move all of the elements after fifth element one position back which results in computational complexity O(n). If it was C++, then I would use list that is implemented using pointers, so that I could go through the entire list and remove the elements that I want to remove in the most quickest way. But in Python, there are no pointers, so I can't implement this list on my own. So is there a way to do the above process in Python with computational complexity O(n)? In other words: In C++, there are two ways how you can implement a list: using pointers and using an array. The first implementation is faster for some operations, and the second is faster for other operations. I need to use the first implementation, but I don't know if it's possible in Python.
tagged with: list
tagged with: linked-list
answer count: 0
type: UnansweredQuestion
score: 0

http://stackoverflow.com/q/46856988
type: AnsweredQuestion
score: 4
has answer: http://stackoverflow.com/a/46857196
downvote count: 3
linked to: http://stackoverflow.com/q/19798153
upvote count: 7
has body: I have a array like below np.array(["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}]) and a pandas DataFrame like below df = pd.DataFrame({'A': ["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}]}) When I apply np.isreal to DataFrame df.applymap(np.isreal) Out[811]: A 0 False 1 False 2 True 3 False 4 False 5 True When I do np.isreal for the numpy array. np.isreal( np.array(["hello","world",{"a":5,"b":6,"c":8},"usa","india",{"d":9,"e":10,"f":11}])) Out[813]: array([ True, True, True, True, True, True], dtype=bool) I must using the np.isreal in the wrong use case, But can you help me about why the result is different ?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80661632
has answer: http://stackoverflow.com/a/46857112
has answer: http://stackoverflow.com/a/46857114
possible better answer: http://stackoverflow.com/a/46857112
answer count: 3
accepted answer: http://stackoverflow.com/a/46857114
tagged with: pandas
has comment: http://stackoverflow.com/comment/80661655
favorite count: 0
linked to: http://stackoverflow.com/q/46856276
tagged with: python
has title: np.isreal behavior different in pandas.DataFrame and numpy.array
has comment: http://stackoverflow.com/comment/80661596

http://stackoverflow.com/comment/80457251
comment on: http://stackoverflow.com/a/46753470
type: AnswerComment
score: 0
type: Comment
has text: `Sclass.json` does not contain valid json.

http://stackoverflow.com/q/46897957
tagged with: if-statement
has body: I'm making a tip calculator and I want to make it so that if it prints a message because the input was not a float, then it reads the fact that it prints that message and goes back to the original input and makes you try again so can i do something like: if print("No stupid use a number."): return input("Bill before tax.")
score: 0
has answer: http://stackoverflow.com/a/46898777
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: What do I do if I want to make an if statement that is dependent on an output? (Im running python)
type: Question

http://stackoverflow.com/a/58263732
answers question: http://stackoverflow.com/q/46843897
score: 2
has body: Mainter a counter for the number of circles you have drawn and write the number with the co-ordinates same as the centre of the circle. Also the command is pygame.draw.circle and not pygame.draw.circl
downvote count: 2
type: Answer
upvote count: 4

http://stackoverflow.com/q/46903324
has comment: http://stackoverflow.com/comment/80758140
downvote count: 0
tagged with: pyspark
has title: How to convert .crc files created by saveAsTextFile() to .txt file
has body: I'm trying to save my pyspark output into .txt file for future reference. So I wrote following code fileName=names1[i]+".txt" # Generating file name as fieldname.txt #data1.groupby(names1[i]).agg(F.collect_set("name")).rdd.saveAsTextFile(names1[i]+'.txt') data.groupby(names1[i]).agg(F.collect_set("name")).rdd.saveAsTextFile(fileName) But after running the code I'm seeing folders with variable filename. Say if my filename is abc.txt then I'm seeing folder name as abc.txt and under that folder lots of file with .crc extension. How can I group those .crc file into .txt file? Either by pyspark or Manually
has comment: http://stackoverflow.com/comment/80758085
linked to: http://stackoverflow.com/q/23898098
favorite count: 0
has comment: http://stackoverflow.com/comment/80753275
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80761264
upvote count: 1
tagged with: python
score: 1
type: Question

http://stackoverflow.com/q/46776979
has comment: http://stackoverflow.com/comment/80505346
has body: The Context In Python 3.5, I'm making a function to generate a map with different biomes - a 2-dimensional list with the first layer representing the lines of the Y-axis and the items representing items along the X-axis. Example: [ ["A1", "B1", "C1"], ["A2", "B2", "C2"], ["A3", "B3", "C3"] ] This displays as: A1 B1 C1 A2 B2 C2 A3 B3 C3 The Goal A given position on the map should be more likely to be a certain biome if its neighbours are also that biome. So, if a given square's neighbours are all Woods, that square is almost guaranteed to be a Woods. My Code (so far) All the biomes are represented by classes (woodsBiome, desertBiome, fieldBiome). They all inherit from baseBiome, which is used on its own to fill up a grid. My code is in the form of a function. It takes the maximum X and Y coordinates as parameters. Here it is: def generateMap(xMax, yMax): areaMap = [] # this will be the final result of a 2d list # first, fill the map with nothing to establish a blank grid xSampleData = [] # this will be cloned on the X axis for every Y-line for i in range(0, xMax): biomeInstance = baseBiome() xSampleData.append(biomeInstance) # fill it with baseBiome for now, we will generate biomes later for i in range(0, yMax): areaMap.append(xSampleData) # now we generate biomes yCounter = yMax # because of the way the larger program works. keeps track of the y-coordinate we're on for yi in areaMap: # this increments for every Y-line xCounter = 0 # we use this to keep track of the x coordinate we're on for xi in yi: # for every x position in the Y-line biomeList = [woodsBiome(), desertBiome(), fieldBiome()] biomeProbabilities = [0.0, 0.0, 0.0] # biggest bodge I have ever written if areaMap[yi-1][xi-1].isinstance(woodsBiome): biomeProbabilities[0] += 0.2 if areaMap[yi+1][xi+1].isinstance(woodsBiome): biomeProbabilities[0] += 0.2 if areaMap[yi-1][xi+1].isinstance(woodsBiome): biomeProbabilities[0] += 0.2 if areaMap[yi+1][xi-1].isinstance(woodsBiome): biomeProbabilities[0] += 0.2 if a…
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/46779008
answer count: 2
tagged with: arrays
tagged with: probability-density
favorite count: 0
has answer: http://stackoverflow.com/a/46779008
has title: Ensure that contents of list sums up to 1 for np.random.choice()
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/46778965
downvote count: 0
tagged with: probability
has answer: http://stackoverflow.com/a/46778965
type: Question

http://stackoverflow.com/q/46837378
favorite count: 0
tagged with: optimization
has answer: http://stackoverflow.com/a/46839051
type: Question
has title: How to better implement recurrence relations in code?
has body: I've been struggling with this problem for a couple days now, I'm still new to Python and more math intensive coding so any help would be appreciated, just point me in the right direction :) So the question was something like: You have a movie pass which is valid for N days. You can use it in any way you want except for 3 consecutive days or more. So basically, you can either use your pass on a given day or choose to not, meaning 2 raised to N total possibilities. The valid ways for claiming the pass are then 2 raised to N - invalidCases You have to find the number of valid cases % (10^9+7) I found a recurrence relation for the invalid cases which looked like invalidCases(at_N) = 2^(n-4) + 2*invalidCases(at_N-1) - invalidCases(at_n-4) So my first impulse was to simply use recursion: def invalidCases(n): if(n&lt;3): return 0; elif(n==3): return 1; else: return 2**(n-4)+ 2*invalidCases(n-1)- invalidCases(n-4) Very inefficient, but my equation seemed correct. My next attempt, I tried memoization, but I kept running into an error at N=1006. So I changed the recursion limit. My present attempt(with memoization and increased recursion limit) import sys sys.setrecursionlimit(10**6) T=int(input()); #2**(n-4) + 2*ans(n-1)-ans(n-4) memo={0:0,1:0,2:0,3:1,4:3,5:8,6:20,7:47} # def ans(n): #complete this function if n not in memo: memo[n]=(2**(n-4) + 2*ans(n-1)-ans(n-4)); return memo[n]; modulo = 10**9 + 7; print((2**n-ans(n))%modulo); Finally, my problem. I need this code to work for n = 999999. How do I bring its worst case down to minimum? Any pointers or tips would be great.
has comment: http://stackoverflow.com/comment/80626081
upvote count: 2
has comment: http://stackoverflow.com/comment/80632482
answer count: 2
has comment: http://stackoverflow.com/comment/80625426
tagged with: python
accepted answer: http://stackoverflow.com/a/46839051
tagged with: recursion
tagged with: mathematical-optimization
tagged with: algorithm
has answer: http://stackoverflow.com/a/46839655
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/46839655
downvote count: 0

http://stackoverflow.com/a/46816557
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46795504
type: Answer
has comment: http://stackoverflow.com/comment/80657738
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80658546
answers question: http://stackoverflow.com/q/46795504
has comment: http://stackoverflow.com/comment/80658305
has body: I don't think there is an option to interpolate where there are missing data points, and hence the line stops instead. This question on the same topic from 2016 remains unanswered. Instead, you could use plt.errorbar as suggested in the comments, or add the lines afterwards using plt.plot while still using seaborn to plot the means and error bars: import seaborn as sns tips = sns.load_dataset('tips') # Create a gap in the data and plot it tips.loc[(tips['size'] == 4) &amp; (tips['sex'] == 'Male'), 'size'] = 5 sns.pointplot('size', 'total_bill', 'sex', tips, dodge=True) # Fill gap with manual line plot ax = sns.pointplot('size', 'total_bill', 'sex', tips, dodge=True, join=False) # Loop over the collections of point in the axes and the grouped data frame for points, (gender_name, gender_slice) in zip(ax.collections, tips.groupby('sex')): # Retrieve the x axis positions for the points x_coords = [coord[0] for coord in points.get_offsets()] # Manually calculate the mean y-values to use with the line means = gender_slice.groupby(['size']).mean()['total_bill'] ax.plot(x_coords, means, lw=2)

http://stackoverflow.com/comment/80547319
has text: include your imports in your code. did you import from the `random` module, the `turtle` module? did you do exclusive imports?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46800178

http://stackoverflow.com/q/46812451
answer count: 1
has body: I want to develop a Python theme which executes Python codes and which colorize the tokens in input() while users typing some text. Recently I have started to learn readline and pygments. I can add keyword tokens to the tab completion. Also i can colorize the stdout text with pygments highlight function. But still i can't colorize the tokens in input(). Is there anyone to give me an idea to do what i want? The codes below are from an example application. import readline from pygments.token import Token from pygments.style import Style from pygments.lexers import Python3Lexer from pygments import highlight from pygments.formatters import Terminal256Formatter import keyword class Completer: def __init__(self, words): self.words = words self.prefix = None self.match = None def complete(self, prefix, index): if prefix != self.prefix: self.match = [i for i in self.words if i.startswith(prefix)] self.prefix = prefix try: return self.match[index] except IndexError: return None class MyStyle(Style): styles = { Token.String: '#ansiwhite', Token.Number: '#ansired', Token.Keyword: '#ansiyellow', Token.Operator: '#ansiyellow', Token.Name.Builtin: '#ansiblue', Token.Literal.String.Single: '#ansired', Token.Punctuation: '#ansiwhite' } if __name__ == "__main__": code = highlight("print('hello world')", Python3Lexer(), Terminal256Formatter(style=MyStyle)) readline.parse_and_bind('tab: complete') readline.set_completer(Completer(keyword.kwlist).complete) print(code) while True: _input = input("&gt;&gt;&gt; ") if _input == "quit": break else: print(_input) And this is the screenshot of how this application works. As you can see, when the program starts, a "print('hello world')" string is highlighted with pygments. And after that pressing the TAB 2 times gives the keywords. Thanks in advance.
tagged with: pygments
type: AnsweredQuestion
tagged with: readline
has answer: http://stackoverflow.com/a/46813639
type: Question
score: 0
has title: How to use pygments with readline to colorize the input text according to the tokens?
accepted answer: http://stackoverflow.com/a/46813639
tagged with: python

http://stackoverflow.com/comment/80519110
score: 1
comment on: http://stackoverflow.com/q/46786327
type: Comment
type: QuestionComment
has text: Also, your data is already sorted. I don't know that `algorithms` module (and you didn't say where it's from), but it looks like it's smart enough to terminate when the inner loop has performed no swaps. So in this case it's made a single pass over the list, which is O(n).

http://stackoverflow.com/q/46757370
has title: Populate column based on maximum value in other column (python pandas)
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
has body: I have a table with values in each column (A,B,C). I want to create another column (max_col) with the name of the column which has the maximum value. So in case the A column is greater than B or C, 'A' is populated. The following code works, but it is not very 'pythonic' or scalable in case of a lot of different columns to choose from. import pandas as pd import numpy as np table = { 'A': [1,2,3,4,5,6], 'B':[2,4,1,5,3,8], 'C':[3,1,2,4,5,6]} df = pd.DataFrame.from_dict(table) df['total'] = df.max(axis=1) df['max_col'] = np.nan df['max_col'] = np.where( df['total'] == df['A'],'A',df['max_col']) df['max_col'] = np.where( df['total'] == df['B'],'B',df['max_col']) df['max_col'] = np.where( df['total'] == df['C'],'C',df['max_col']) df Also, this code is biased towards the last column being checked, in case of row 5, the A and C values are the same, but the 'max_col' is populated with 'C' because it is the last being checked. Ideally 'max_col' would populated with 'No Max' in this case.
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/46757425
accepted answer: http://stackoverflow.com/a/46757425

http://stackoverflow.com/q/46751581
has answer: http://stackoverflow.com/a/46751784
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80450189
has comment: http://stackoverflow.com/comment/80449040
has title: list of lists to pandas dataframe
type: Question
has comment: http://stackoverflow.com/comment/80449330
has comment: http://stackoverflow.com/comment/80449217
has comment: http://stackoverflow.com/comment/80449329
has answer: http://stackoverflow.com/a/46751916
score: 0
has body: I'm trying to parse a list of nested lists to a pandas dataframe. This is a sample of the list: &gt;&gt;&gt;result[1] { "account_currency": "BRL", "account_id": "1600343406676896", "account_name": "aaa", "buying_type": "AUCTION", "campaign_id": "aaa", "campaign_name": "aaaL", "canvas_avg_view_percent": "0", "canvas_avg_view_time": "0", "clicks": "1", "cost_per_total_action": "8.15", "cpm": "60.820896", "cpp": "61.278195", "date_start": "2017-10-08", "date_stop": "2017-10-15", "device_platform": "desktop", "frequency": "1.007519", "impression_device": "desktop", "impressions": "134", "inline_link_clicks": "1", "inline_post_engagement": "1", "objective": "CONVERSIONS", "outbound_clicks": [ { "action_type": "outbound_click", "value": "1" } ], "platform_position": "feed", "publisher_platform": "facebook", "reach": "133", "social_clicks": "1", "social_impressions": "91", "social_reach": "90", "spend": "8.15", "total_action_value": "0", "total_actions": "1", "total_unique_actions": "1", "unique_actions": [ { "action_type": "landing_page_view", "value": "1" }, { "action_type": "link_click", "value": "1" }, { "action_type": "page_engagement", "value": "1" }, { "action_type": "post_engagement", "value": "1" } ], "unique_clicks": "1", "unique_inline_link_clicks": "1", "unique_outbound_clicks": [ { "action_type": "outbound_click", "value": "1" } ], "unique_social_clicks": "1" } When I transform it to a pandas dataframe, I get: &gt;&gt;&gt;df = pd.DataFrame(result) &gt;&gt;&gt;df .... unique_actions \ NaN [{u'value': u'1', u'action_type': u'landing_pa... NaN [{u'value': u'2', u'action_type': u'landing_pa... [{u'value': u'4', u'action_type': u'landing_pa... NaN Unique actions and someother filter are not normalized. How can I normalize it to the same granularity?
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/46838739
answer count: 1
has title: Tensorflow - Graph is finalized and cannot be modified
favorite count: 0
accepted answer: http://stackoverflow.com/a/46854046
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46854046
tagged with: machine-learning
tagged with: tensorflow
has body: I am trying to launch a Distributed Tensorflow and get the following error. My code looks like this: sv = tf.train.Supervisor(is_chief=(task_index == 0), logdir="/tmp/train_logs", init_op=init_op, summary_op=summary_op, saver=saver, global_step=global_step, save_model_secs=600) with sv.managed_session(server.target) as sess: step = 0 while not sv.should_stop() and step &lt; nnc.steps: mini_batches = random_mini_batches(x_train, y_train, mini_batch_size) for mini_batch in mini_batches: (batch_x, batch_y) = mini_batch _, step = sess.run([train_op, global_step], feed_dict={x: batch_x, y: batch_y}) When I get the error it's failed on random_mini_batches function. But I completely don't understand how and why. random_mini_batches function is a function written in pure python + numpy without anything related to TensorFlow. x_train and y_train were not used before. Here is the error that I get: File "/Users/curr_user/PycharmProjects/curr_project/src/nn.py", line 36, in random_mini_batches num_complete_minibatches = int(math.floor(m / mini_batch_size)) # number of mini batches of size mini_batch_size File "/Users/curr_user/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 880, in r_binary_op_wrapper x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name="x") File "/Users/curr_user/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 611, in convert_to_tensor as_ref=False) File "/Users/curr_user/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 676, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/Users/curr_user/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 121, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "/Users/curr_user/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 106, in constant attrs={"value"…
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/35094899
upvote count: 1

http://stackoverflow.com/a/46828334
has comment: http://stackoverflow.com/comment/80604273
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Use str.extract: df['Title']=df['Title'].str.extract('&lt;span class=\"o-label--tiny\"&gt;(.*)&lt;/span&gt;',expand=False) print (df) Title Num 0 VALEUR ÉNERGÉTIQUE 1 PROTÉINES 2 GLUCIDES If possible different tags or classes: df['Title'] = df['Title'].str.extract('&gt;(.*)&lt;',expand=False) print (df) Title Num 0 VALEUR ÉNERGÉTIQUE 1 PROTÉINES 2 GLUCIDES
has comment: http://stackoverflow.com/comment/80606742
type: Answer
has comment: http://stackoverflow.com/comment/80604251
accepted answer of: http://stackoverflow.com/q/46828255
score: 1
has comment: http://stackoverflow.com/comment/80605306
answers question: http://stackoverflow.com/q/46828255
has comment: http://stackoverflow.com/comment/80605414
has comment: http://stackoverflow.com/comment/80606715

http://stackoverflow.com/q/46764211
upvote count: 3
has comment: http://stackoverflow.com/comment/80474069
has body: This is what I am doing now to achieve what I want. In: a=numpy.zeros((3,2)) a[range(a.shape[0]),[0,0,1]] = 1 a Out: array([[ 1., 0.], [ 1., 0.], [ 0., 1.]]) As you can see, I used range function to select all the rows in a. Is there any other cleaner way to select every row?
linked to: http://stackoverflow.com/q/29831489
linked to: http://stackoverflow.com/q/38592324
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80473805
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/80473762
has comment: http://stackoverflow.com/comment/80473659
type: Question
tagged with: numpy
tagged with: arrays
answer count: 1
has title: How to modify a Numpy 2D array in every row but specific column indexes?
favorite count: 0
has answer: http://stackoverflow.com/a/46764677

http://stackoverflow.com/comment/80506419
type: AnswerComment
score: 0
type: Comment
has text: @Ajax1234 `**` is a syntax construct, whereas `pow` requires a function call resolution, so is slightly slower. Otherwise, they have the same complexity.
comment on: http://stackoverflow.com/a/46780068

http://stackoverflow.com/q/46812223
has body: I am trying to do in a smart way several calculation by using .groupby with pandas dataframe, with the following data: import numpy as np import pandas as pd df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) In [2]: df Out[2]: A B C D 0 foo one 0.469112 -0.861849 1 bar one -0.282863 -2.104569 2 foo two -1.509059 -0.494929 3 bar three -1.135632 1.071804 4 foo two 1.212112 0.721555 5 bar two -0.173215 -0.706771 6 foo one 0.119209 -1.039575 7 foo three -1.044236 0.271860 I would like to compute in the shorter and faster way the following Output: A B var1 var2 var3 bar one 0.000000 0.000000 0.000000 three 0.000000 0.000000 0.000000 two 0.000000 0.000000 0.000000 foo one 0.822999 19.705290 0.731207 three 0.000000 0.000000 0.000000 two 0.229541 5.509553 0.697971 For the moment I know how to do it in a separate way: # lambda functions to apply diff = lambda x: max(x)-min(x) per = lambda x: (max(x)-min(x))/max(x) ratio1 = lambda x: (max(x)-min(x))/ len(x) # grouping using col C df.groupby(['A','B'])['C'].apply(diff) # var1 #Grouping using col D df.groupby(['A','B'])['D'].apply(per) # var2 df.groupby(['A','B'])['D'].apply(ratio1) #var3 Edit: I know how to join all results in a dataframe but I am wondering how to do these 3 operations in one. Any advice is accepted even to not to do all in one because of low performance...
has answer: http://stackoverflow.com/a/46812283
tagged with: dataframe
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46812283
tagged with: python
score: 1
upvote count: 1
has title: make several operations in a dataframe at once
type: AnsweredQuestion

http://stackoverflow.com/a/46755825
downvote count: 0
upvote count: 3
answers question: http://stackoverflow.com/q/46754297
type: Answer
has body: The main advantage of anaconda is that they've taken the time to compile packages (not just Python ones) and ensure they're compatible with each other, so that everything should "just work' for the user. This is especially useful on Windows, where compiling some Python packages may be difficult (and not everything has a wheel available on PyPI). Such packages are available to install via conda install &lt;foo&gt;. Whilst you can still use pip install &lt;foo&gt; (and indeed will need to do so for any packages not available through anaconda's package manager), you should use the conda install where packages are available - otherwise you're not getting the benefit that anaconda intends to provide. So (as per anaconda's docs for mechanize) you want: conda install -c conda-forge mechanize (You explicitly requested no attempts to convince you to use a different approach - I'm taking that to mean that you want to use anaconda and python27, rather than to definitely use pip. Obviously this is no help if pip is a must for you! I believe the "real world solution" that you're after is to use conda install rather than pip install wherever possible when using anaconda - see the answers to this question for an explanation of the differences between pip and conda)
score: 3

http://stackoverflow.com/a/46890606
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/46889189
score: 2
answers question: http://stackoverflow.com/q/46889189
has body: If I understand you correctly you have the mean and standard deviation of some data. You have plotted a histogram of this and would like to plot the normal distribution line over the histogram. This line can be generated using matplotlib.mlab.normpdf(), the documentation can be found here. import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt mean = 100 sigma = 5 data = np.random.normal(mean,sigma,1000) # generate fake data x = np.linspace(min(data), max(data), 100) plt.hist(data, bins="auto",normed=True) plt.plot(x, mlab.normpdf(x, mean, sigma)) plt.show() Which gives the following figure: Edit: The above only works with normed = True. If this is not an option, we can define our own function: def gauss_function(x, a, x0, sigma): return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) mean = 100 sigma = 5 data = np.random.normal(mean,sigma,1000) # generate fake data x = np.linspace(min(data), max(data), 1000) test = gauss_function(x, max(data), mean, sigma) plt.hist(data, bins="auto") plt.plot(x, test) plt.show()
type: AcceptedAnswer

http://stackoverflow.com/comment/80672554
type: QuestionComment
has text: Do you have to keep the data that way? A dict would be much more helpful for the particular problem you're asking.
score: 0
comment on: http://stackoverflow.com/q/46862568
type: Comment

http://stackoverflow.com/comment/80470220
score: 0
comment on: http://stackoverflow.com/a/46762402
type: AnswerComment
has text: Thank you, that's working, but why "is not" statement running on windows but Ubuntu?
type: Comment

http://stackoverflow.com/q/46770225
favorite count: 0
has body: Basically imagine if I have a line like this: "Hello world I am Lucas [help me] Hi" I'd want the result of re.split() to be: ['Hello' 'world' '' 'I' 'am' 'Lucas' '[help me] '' 'Hi'] As of now I've tried using re.split(r'\s+(?=[^()]*(?:\[|\&lt;|$))', stringToSplit) but I'm uncertain on how to add '' as a newline. I've tried: result = re.split(r'\s|\n+(?=[^()]*(?:\[|\&lt;|$))', input) however this will cause problem for [help me] as it splits it into '[help' and 'me]'. Any fixes around this?
accepted answer: http://stackoverflow.com/a/46770336
has title: Python: Regex split on space (but keep elements unsplitted in [ ])and add " " in array as a symbol of Newline
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/46771215
score: 2
has answer: http://stackoverflow.com/a/46771215
upvote count: 2
has comment: http://stackoverflow.com/comment/80485837
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46770336
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/80725060
comment on: http://stackoverflow.com/q/46884612
has text: Also why not use `from pywinauto.keyboard import SendKeys; SendKeys('^{F4}')` and `app.FirstWindowName.set_focus()`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80678270
score: 0
comment on: http://stackoverflow.com/q/46857520
type: Comment
type: QuestionComment
has text: That's strange, I cannot think of something else with the single line error you provide. Maybe having a double check on everything or re-start everything could help.

http://stackoverflow.com/comment/80754693
type: AnswerComment
type: Comment
has text: It's `pipes.quote` on Python 2.
comment on: http://stackoverflow.com/a/46902218
score: 0

http://stackoverflow.com/comment/80499987
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46777178
has text: What do you mean you want to conserve pairs? Do you want '3,7' -> 37 or do you want them to be a tuple (3,7)?

http://stackoverflow.com/q/46901740
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80782553
upvote count: 0
has answer: http://stackoverflow.com/a/46923143
score: -1
answer count: 1
favorite count: 0
tagged with: alpha-beta-pruning
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/80750378
has body: I am doing my final year project on Machine Learning for checkers Computer game. In this game i have automated one player ( which moves randomly ) and i want second player to learn against the randomness and become smart by more games and trials. As i said that first player is automated so it's working quite fine, but talking about the second player , i am having some problem with it's moves. I am using target function as v(b) = w0+w1x1+w2x2+w3x3+w4x4+w5x5+w6x6 where x1=number of white piece x2=number of black piece x3=number of white king x4=number of black king x5=number of white pieces that are threatened x6=number of black pieces that are threatened and w0 to w6 are weights which are to be learned by the algorithm. Now if i take initial board state and put weights random. by putting random weights (12,-15,6,19,-5,3) we get v(b) = -36 as initially x1= 12 x2= 12 x3= 0 x4= 0 x5= 0 x6= 0 so v(b) = -36 But -36 dosen't give me a valid position to move and learn further. How to get a predictive value to be moved? It would be a great help if you can contribute to my problem and put efforts to solve it.
has title: Applying Machine learning with checkers game

http://stackoverflow.com/q/46804380
has comment: http://stackoverflow.com/comment/80556663
has answer: http://stackoverflow.com/a/46804915
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/46804915
tagged with: python
answer count: 1
tagged with: opencv
has body: I'm updating the cv2.imshow() command in a endless Loop and I want to manipulate the window position because the window is always on the top of my display and a small part is invisable. The cv2.moveWindow() command is a nice solution for my task but is there an other way to set the window position only once and not to repeat the command in every Iteration? I want to update the window every 500 ms. Is there a better way to display the image-stream with fixed window position? while true: (...) img = cv2.imread('test.jpg', cv2.IMREAD_COLOR) cv2.imshow('image',img) cv2.moveWindow('image',200,200) (...)
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: imshow
has comment: http://stackoverflow.com/comment/80555727
type: Question
has title: How to combine imshow() and moveWindow() in openCV with python?

http://stackoverflow.com/comment/80721912
has text: you should use `load` function to show loading then hide it when `document` is ready and show body.
comment on: http://stackoverflow.com/q/46887402
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80774894
has text: @RicklePick glad to help!
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46888308

http://stackoverflow.com/comment/80627330
type: Comment
has text: I swapped them only in the output order. My usage is still consistent with the **groupby** order.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46837965

http://stackoverflow.com/comment/80603217
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46827718
has text: updated the question

http://stackoverflow.com/comment/80724788
has text: you can choose a fixed number of key points for each image that would also be feasible but depending on the nature of your images it might not give a good result
type: AnswerComment
comment on: http://stackoverflow.com/a/46886622
score: 0
type: Comment

http://stackoverflow.com/q/46794054
answer count: 2
has answer: http://stackoverflow.com/a/46794760
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80534891
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80534821
tagged with: python
has title: Look up salary information by name from a list
has body: I'm writing some python code that works out a person's total pay. I am able to do this by getting the user to input their pay, however I would like them just to be able to enter their name and then the name is searched in position 0 of a list (Eg. 0,1 0,2 0,2 etc). I have tried using a tuple but it is not callable and the dictionary and list would not work for me either. counter = 0 valid = 0 employeelist = [["thomas","2","500"], ["jake","1","750"]] while True: while True: try: name = str(input("Name:")) except ValueError: print("Error") continue else: break while True: if name == employeelist[counter,0]: print(employeelist[counter]) break valid = 1 elif counter = 3: print("invalid name") break else: counter = counter + 1 if valid == 1: break months = employeelist[counter,1] pay = employeelist[counter,1] totalpay = int(months) * int(pay) Edit: I do no longer have the code with the dictionary, however I just edited the code from [counter,1] and [0,1] to [counter][1] and is working fine thank you :D
upvote count: 0
has answer: http://stackoverflow.com/a/46794397
type: Question
has comment: http://stackoverflow.com/comment/80534907
score: -1

http://stackoverflow.com/q/46868024
has answer: http://stackoverflow.com/a/46868865
type: AnsweredQuestion
tagged with: consumer
has title: Why does an async consumer called in __init__ in a Tornado RequestHandler behave differently from statically called?
tagged with: tornado
type: Question
answer count: 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/46868865
has body: I'm trying to make an async server using Tornado with a unique queue for each handler. A job is placed into a queue when the end point is called. I have a consumer function which asynchronously 'consumes' jobs from the queue. However, the behavior of consumer tends to vary depending on whether I call it as self.consumer() or AsyncHandler.consumer(). My initial guess is that it is because of instance level locking but can't find evidence for it. I fire 4 post requests consecutively. Here are the 2 snippets with their outputs. import tornado.web from tornado import gen from time import sleep, time from tornado.queues import Queue from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop class AsyncHandler(tornado.web.RequestHandler): JOB_QUEUE = Queue() EXECUTOR = ThreadPoolExecutor() def post(self): job = lambda: sleep(3) or print("{}:handler called".format(int(time()))) self.JOB_QUEUE.put(job) self.set_status(200) self.finish() @staticmethod @gen.coroutine def consumer(): while True: job = yield AsyncHandler.JOB_QUEUE.get() print("qsize : {}".format(AsyncHandler.JOB_QUEUE.qsize())) print(AsyncHandler.JOB_QUEUE) output = yield AsyncHandler.EXECUTOR.submit(job) AsyncHandler.JOB_QUEUE.task_done() if __name__ == "__main__": AsyncHandler.consumer() APP = tornado.web.Application([(r"/test", AsyncHandler)]) APP.listen(9000) IOLoop.current().start() This gives the expected output: qsize : 0 &lt;Queue maxsize=0 tasks=1&gt; 1508618429:handler called qsize : 2 &lt;Queue maxsize=0 queue=deque([&lt;function...&lt;lambda&gt; at 0x7fbf8f741400&gt;, &lt;function... &lt;lambda&gt; at 0x7fbf8f760ea0&gt;]) tasks=3&gt; 1508618432:handler called qsize : 1 &lt;Queue maxsize=0 queue=deque([&lt;function AsyncHandler.post.&lt;locals&gt;.&lt;lambda&gt; at 0x7fbf8f760ea0&gt;]) tasks=2&gt; 1508618435:handler called qsize : 0 &lt;Queue maxsize=0 tasks=1&gt; 1508618438:handler called output = yield AsyncHandler.EXECUTOR.submit(job) takes 3 seconds to return output and s…
tagged with: asynchronous
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/46777086
answer count: 2
downvote count: 0
score: 1
tagged with: interleave
tagged with: tuples
has comment: http://stackoverflow.com/comment/80499930
tagged with: python
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46777230
upvote count: 1
linked to: http://stackoverflow.com/q/952914
has answer: http://stackoverflow.com/a/46777188
tagged with: list
has body: I have this code that interleaves two words and outputs the new interleaved word as a tuple, but I need it too be a raw string. from itertools import zip_longest def interleave(word1,word2): return ''.join(list(map(str, zip_longest(word1,word2,fillvalue='')))) If inputting the words, cat and hat, this outputs ('h', 'c')('a', 'a')('t', 't'). But I need it to output hcaatt How could I go about formatting this list into a normal string
type: Question
has title: Format a list into a string Python

http://stackoverflow.com/a/46860697
type: Answer
has body: Yes you can proceed with python using a cross-platform open source library Kivy and the good things about this is you can run your app on any operating system. You can learn more from Here.
answers question: http://stackoverflow.com/q/46860616
score: 0

http://stackoverflow.com/q/46857087
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46857456
has comment: http://stackoverflow.com/comment/80661989
has comment: http://stackoverflow.com/comment/80661926
possible better answer: http://stackoverflow.com/a/46857456
tagged with: python
has answer: http://stackoverflow.com/a/46863149
type: AnsweredQuestion
has body: I am very new to web scraping and am having some trouble with scraping some NBA player data from nba.com. I first tried to scrape the page using bs4 but ran into an issue which after some research I believe is due to "XHR" from the articles I read. I was able to find a web address to the json formatted data, but my python program seems to bog down, and never load the data. Again I am very new at web scraping, but thought I'd see if I was way off track here... Any suggestions? Thanks! (Code Below) import requests import json url = "http://stats.nba.com/stats/leaguedashplayerstats?College=&amp;Conference=&amp;Country=&amp;DateFrom=&amp;DateTo=&amp;Division=&amp;DraftPick=&amp;DraftYear=&amp;GameScope=&amp;GameSegment=&amp;Height=&amp;LastNGames=0&amp;LeagueID=00&amp;Location=&amp;MeasureType=Base&amp;Month=0&amp;OpponentTeamID=0&amp;Outcome=&amp;PORound=0&amp;PaceAdjust=N&amp;PerMode=PerGame&amp;Period=0&amp;PlayerExperience=&amp;PlayerPosition=&amp;PlusMinus=N&amp;Rank=N&amp;Season=2017-18&amp;SeasonSegment=&amp;SeasonType=Regular+Season&amp;ShotClockRange=&amp;StarterBench=&amp;TeamID=0&amp;VsConference=&amp;VsDivision=&amp;Weight=" resp = requests.get(url=url) data = json.loads(resp.text) print(data)
tagged with: http://stackoverflow.com/tag/json
tagged with: web-scraping
tagged with: python-requests
type: Question
accepted answer: http://stackoverflow.com/a/46863149
has title: Scraping json webpage

http://stackoverflow.com/a/46862815
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46862768
has comment: http://stackoverflow.com/comment/80673230
type: Answer
score: 8
has body: Because all comprehensions in Python 3 are implemented using a hidden function, calling locals doesn't return the values you're expecting it to return. You can see this by printing the values out: &gt;&gt;&gt; _ = {k: print(locals()) for k in ('foo','bar','baz')} {'k': 'foo', '.0': &lt;tuple_iterator object at 0x7fdf840afa90&gt;} {'k': 'bar', '.0': &lt;tuple_iterator object at 0x7fdf840afa90&gt;} {'k': 'baz', '.0': &lt;tuple_iterator object at 0x7fdf840afa90&gt;} Assigning locals() to locale, as you do, takes care of this. You aren't calling locals inside the comprehension. Note that, in Python 2, the situation is a bit murkier. dict-comps do fail in a similar fashion but list-comps, which predate dict-comps, work just fine: &gt;&gt;&gt; _ = [locals()[k] for k in ('foo', 'bar', 'baz')] &gt;&gt;&gt; _ [20, 40, 60] this is yet another 'wart' that was addressed with Py3.
downvote count: 0
upvote count: 8
accepted answer of: http://stackoverflow.com/q/46862768

http://stackoverflow.com/q/46813921
possible better answer: http://stackoverflow.com/a/46814192
tagged with: pandas-groupby
tagged with: pandas
score: 2
has title: Pandas Groupby: How to use two lambda functions?
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/80582803
answer count: 4
has answer: http://stackoverflow.com/a/46813998
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46812223
has body: I can currently do the following in Pandas, but I get a stern finger wagging from FutureWarning: grpd = df.groupby("rank").agg({ "mean": np.mean, "meian": np.median, "min": np.min, "max": np.max, "25th percentile": lambda x: np.percentile(x, 25), "75th percentile": lambda x: np.percentile(x, 75) }) The following throws an error because I have two lambda functions: percentile_25 = lambda x: np.percentile(x, 25) percentile_75 = lambda x: np.percentile(x, 75) df = diffs"User Installs", "rank".dropna() grpd = df.groupby("shopping_rank").agg([ np.mean, np.median, np.min, np.max, percentile_25, percentile_75 ]) This throws: SpecificationError: Function names must be unique, found multiple named &lt;lambda&gt; The only way I can seem to make this work (without ignoring the warning, which I should probably just do) is with an elaborate process like the following Define my DF with one lambda function (25th percentile), and everything else I need (min, max, etc.) rename the cols to get rid of the MultiIndex Create ANOTHER DF, do ANOTHER grouping, this time with the other column I want (75th percentile) Rename cols again (thanks MultiIndex!) Join back to the original DF on the index Is there something I'm missing here? Surely there's a better way to do what I imagine is a pretty common thing (using two aggregations that aren't directly importable from numpy).
accepted answer: http://stackoverflow.com/a/46813998
has comment: http://stackoverflow.com/comment/80584631
type: Question
has comment: http://stackoverflow.com/comment/80576695
has answer: http://stackoverflow.com/a/62138482
has answer: http://stackoverflow.com/a/46814192
downvote count: 0
has answer: http://stackoverflow.com/a/47836079
has comment: http://stackoverflow.com/comment/80575291

http://stackoverflow.com/comment/80651113
type: QuestionComment
type: Comment
score: 0
has text: It is what the book was teaching... what should I use instead?
comment on: http://stackoverflow.com/q/46851600

http://stackoverflow.com/comment/80515697
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46784504
has text: If you don't mind, could you please post the IP of your instance so I can investigate it further?

http://stackoverflow.com/q/46799137
downvote count: 0
score: 9
type: Question
has answer: http://stackoverflow.com/a/46799537
accepted answer: http://stackoverflow.com/a/46799537
has title: How to supress 'star imports' warnings from Spyder IDE?
has body: While working on Spyder and importing some libraries as: from OpenGL.GL import * I get this waning message at every line containing functions from those libraries: somefunction may be undefined or defined from star imports The warnings are harmless but it is quite annoying to see all my code underlined in yellow. Is there any way to supress specifically those warnings?
tagged with: ide
tagged with: spyder
answer count: 1
has comment: http://stackoverflow.com/comment/80550911
favorite count: 0
upvote count: 9
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/46898856
favorite count: 0
has answer: http://stackoverflow.com/a/46899853
accepted answer: http://stackoverflow.com/a/46899853
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80746861
tagged with: lowercase
has body: I'm trying to make the first row/header lowercase, in multiple csv files in a directory using python. The code and error are below. Is there any way to fix the code or some other way? import csv import glob path = (r'C:\Users\Documents') for fname in glob(path): with open(fname, newline='') as f: reader = csv.reader(f) row1 = next(reader) for row1 in reader: data = [row1.lower() for row1 in row1] os.rename(row1, data) The error is: TypeError: rename: src should be string, bytes or os.PathLike, not list
type: Question
has title: Unable to lowercase the header of csv file
has comment: http://stackoverflow.com/comment/80744956
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

http://stackoverflow.com/comment/80575498
has text: Note that there is a [recursion limit](https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it) in python, so your list cannot be any longer than that, or your recursive count method will crash!
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46814083
type: Comment

http://stackoverflow.com/q/46819958
has title: Extract youtube stats for nerds through an API
favorite count: 0
tagged with: python
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/70003461
tagged with: youtube-api
tagged with: youtube
type: Question
tagged with: youtube-data-api
tagged with: javascript
has answer: http://stackoverflow.com/a/48276412
answer count: 2
upvote count: 1
has body: Is there any available youtube API to get stats for nerds? I have looked around for statistics but they point out to viewCount, likeCount etc. I am particularly looking for stats for nerds data available on right click of a video. URL: https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&amp;key=YOUR_API_KEY &amp;part=snippet,statistics&amp;fields=items(id,snippet,statistics) Description: This example adds the fields parameter to remove all kind and etag properties from the API response. API response: { "videos": [ { "id": "7lCDEYXw3mM", "snippet": { "publishedAt": "2012-06-20T22:45:24.000Z", "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw", "title": "Google I/O 101: Q&amp;A On Using Google APIs", "description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg" }, "medium": { "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg" }, "high": { "url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg" } }, "categoryId": "28" }, "statistics": { "viewCount": "3057", "likeCount": "25", "dislikeCount": "0", "favoriteCount": "17", "commentCount": "12" } } ] }

http://stackoverflow.com/q/46759464
answer count: 3
has comment: http://stackoverflow.com/comment/80464448
tagged with: pandas
has body: Suppose I have the following data: import pandas as pd import numpy as np import random from string import ascii_uppercase random.seed(100) n = 1000000 # Create a bunch of factor data... throw some NaNs in there for good measure data = {letter: [random.choice(list(ascii_uppercase) + [np.nan]) for _ in range(n)] for letter in ascii_uppercase} df = pd.DataFrame(data) I want to quickly count the global occurrence of each value in the set of all values in the dataframe. This works: from collections import Counter c = Counter([v for c in df for v in df[c].fillna(-999)]) But is very slow: %timeit Counter([v for c in df for v in df[c].fillna(-999)]) 1 loop, best of 3: 4.12 s per loop I thought this function might speed things up by using some of pandas's horsepower: def quick_global_count(df, na_value=-999): df = df.fillna(na_value) # Get counts of each element for each column in the passed dataframe group_bys = {c: df.groupby(c).size() for c in df} # Stack each of the Series objects in `group_bys`... This is faster than reducing a bunch of dictionaries by keys stacked = pd.concat([v for k, v in group_bys.items()]) # Call `reset_index()` to access the index column, which indicates the factor level for each column in dataframe # Then groupby and sum on that index to get global counts global_counts = stacked.reset_index().groupby('index').sum() return global_counts It's definitely faster (75% of the time of the previous approach), but there must be something quicker... %timeit quick_global_count(df) 10 loops, best of 3: 3.01 s per loop The results of the above two approaches are identical (with a little modification of the results returned by quick_global_count): dict(c) == quick_global_count(df).to_dict()[0] True What's a quicker way of counting global occurrences of values in a dataframe?
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/46759591
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46759949
score: 6
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80464548
has title: Fast way to count occurrences of all values in a pandas DataFrame
has answer: http://stackoverflow.com/a/46759506
accepted answer: http://stackoverflow.com/a/46759591
possible better answer: http://stackoverflow.com/a/46759506

http://stackoverflow.com/q/46846270
downvote count: 2
has comment: http://stackoverflow.com/comment/80640102
has answer: http://stackoverflow.com/a/46846385
answer count: 1
has comment: http://stackoverflow.com/comment/80640318
upvote count: 0
linked to: http://stackoverflow.com/q/9883317
has comment: http://stackoverflow.com/comment/80640119
type: UnansweredQuestion
has title: python natural logarithms print error
has body: i have an exercise to do in Python which asks the user to give 2 numbers x and y. OK i got that. then it needs to print the exponential value of e to the power of x, where e is the base of the natural logarithm. up to now i have: x=int(input('Please state the value of X: ')) y=int(input('Please state the value of Y: ')) print(math.log(x[,base])) apparently it returns an error for invalid syntax of the comma separator prior to the word base. is the coding correct or am i missing something?
duplicate of: http://stackoverflow.com/q/9883317
has comment: http://stackoverflow.com/comment/80640140
type: Question
tagged with: python
score: -2
favorite count: 0
has comment: http://stackoverflow.com/comment/80643010
has comment: http://stackoverflow.com/comment/80640255

http://stackoverflow.com/comment/80682423
type: Comment
comment on: http://stackoverflow.com/a/46866694
type: AnswerComment
score: 0
has text: how about what I just put? not sure if it will work- it's super slow

http://stackoverflow.com/q/46831085
tagged with: http://stackoverflow.com/tag/c
answer count: 2
tagged with: gnu-make
score: 0
has comment: http://stackoverflow.com/comment/80609744
has answer: http://stackoverflow.com/a/46844701
tagged with: makefile
tagged with: python
has body: I have a C project built with gnu-make. as part of the build process I run some python scripts. the scripts may return an error (with sys.exit(1) for example). I wish to stop the build process immediately after an error returned from a python script but not after a "normal" compilation error. when I run make with -k, it keeps going after an error from python or compilation, and without it it stops on the first error in all cases... any way to accomplish what I'm looking for? Thanks.
type: UnansweredQuestion
has title: how to force make to quit after external script error but not after compilation error
has answer: http://stackoverflow.com/a/46832517
type: Question
has comment: http://stackoverflow.com/comment/80609657
tagged with: build

http://stackoverflow.com/a/46784213
score: 1
answers question: http://stackoverflow.com/q/46783975
upvote count: 1
has body: I would simply use list comprehension like this: a = [a1[i:i+3] for i in range(0, len(a1), 3)] Now how to get the actual indices to the variables a1, a2, .. , an. That's another problem I don't have an answer to. Looking at your accepted answer you could also use dict comprehension: d = {'a'+str(i/3+2): a1[i:i+3] for i in range(0, len(a1), 3)} But this is quite possibly harder to read.
type: Answer
has comment: http://stackoverflow.com/comment/80516115
downvote count: 0

http://stackoverflow.com/a/47576327
upvote count: 4
has body: I chased an answer to this for days. Here's what finally worked for me. Essentially you are using testinfra's Ansible module to access the include_vars function of Ansible. import pytest @pytest.fixture() def AnsibleVars(host): ansible_vars = host.ansible( "include_vars", "file=./group_vars/all/vars.yml") return ansible_vars["ansible_facts"] Then in my tests, I included the function as a parameter: def test_something(host, AnsibleVars): This solution was taken partially from https://github.com/metacloud/molecule/issues/151 I had an interesting issue where I was trying to include the variables from my main playbook and I was receiving an error of "must be stored as a dictionary/hash" when including the playbook.yml file. Separating the variables out into the group_vars/all/vars.yml file resolved that error.
answers question: http://stackoverflow.com/q/46792370
type: Answer
downvote count: 0
score: 4

http://stackoverflow.com/q/46764230
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/46764334
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46764334
has answer: http://stackoverflow.com/a/46764265
type: AnsweredQuestion
score: 6
type: Question
upvote count: 6
tagged with: dataframe
has title: Python: Delete rows from Pandas Dataframe if selected columns are empty
has body: Let's say I have a big DataFrame but I want to concentrate on a selected part of it like 3 columns out of 4. I want to remove the entire row if at least 2 of the values of these selected 3 columns are empty. For example this is the dataframe I have and my selected columns are ['B','C','D']: A B C D 1 1 2 2 3 3 3 3 4 How to get rid of the rows if at least two of values are empty in the selected columns, which are second and fourth rows. Final dataframe is: A B C D 1 1 3 3 3 3
possible better answer: http://stackoverflow.com/a/46764265

http://stackoverflow.com/comment/80767659
has text: any updates with the model?
score: 0
comment on: http://stackoverflow.com/q/46843430
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46887569
type: Question
answer count: 2
tagged with: django-rest-framework
score: 0
has body: I am trying request.data.get('student_name') but it says that list has no attribute get. I just want to get the name of all students before passing to the serializer. I am sending the POST request data in the form of [ {"student_name": "jack", "last_name": "cale", "fathers_name":"carlos"}, {"student_name": "alex", "last_name": "magasa", "fathers_name":"greg"}, {"student_name": "sia", "last_name": "gunns", "fathers_name":"brett"}, {"student_name": "jacob", "last_name": "woods", "fathers_name":"john"} ] my views.py @api_view(['POST']) def add_students(request): student_name = request.data.get('student_name') fathers_name = request.data.get('fathers_name') serializer = StudentsSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response("success") else: return Response(serializer.errors) my serializers.py class StudentsSerializer(serializers.ModelSerializer): class Meta: model = Students fields = ('student_name', 'last_name', 'fathers_name') my models.py class Students(models.Model): student_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) fathers_name = models.CharField(max_length=100, null=True)
accepted answer: http://stackoverflow.com/a/46889175
tagged with: python
has answer: http://stackoverflow.com/a/46891745
has comment: http://stackoverflow.com/comment/80732668
tagged with: django
tagged with: request
possible better answer: http://stackoverflow.com/a/46891745
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80722200
has title: Unable in getting data from list containing many objects
has answer: http://stackoverflow.com/a/46889175

http://stackoverflow.com/comment/80572290
comment on: http://stackoverflow.com/q/46812096
type: QuestionComment
has text: ... Unicode groups by default (such as `\p{Sc}`, which is the easiest way to grab any unicode currency symbol). Also, what do you mean by ellipsis and ad-hoc tokens **etc.** do you want to grab all visible symbols? Again, unicode would be super helpful here with `\p{S}\p{P}` (symbols, punctuation)
type: Comment
score: 1

http://stackoverflow.com/comment/80703548
comment on: http://stackoverflow.com/q/46869895
score: 0
type: Comment
type: QuestionComment
has text: According to [Selenium Blog](https://seleniumhq.wordpress.com/2017/08/09/firefox-55-and-selenium-ide/), they have stopped supporting firefox 55+, so switch to other browsers.

http://stackoverflow.com/q/46874388
has body: i want to create a api using django rest framework which will do some advance search, say a list of grocery item is saved in database and user want to create a list of grocery and he enters first 2 or 3 letters and then my api will do query to get rest of the item name and will suggest to user I have seen the documentation of drf haystack but not sure whether will it fulfill my requirement. Also it does not support django LTS version 1.11 . Can you please give me some suggestion? is django rest framework itself provide any support to create such a api which will do such advance search which i mentioned above? i just need some suggestion as i am new in django rest framework.
upvote count: 2
tagged with: django
answer count: 1
has answer: http://stackoverflow.com/a/46874562
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80697810
score: 2
downvote count: 0
tagged with: django-rest-framework
tagged with: rest
type: Question
tagged with: python
favorite count: 0
has title: django rest api for advance search

http://stackoverflow.com/comment/80677960
has text: It is good to get sum(b) = 0 under the scope of Fraction instance. However, the problem would come back (or even more problems would appear) when manipulating this array. For example, assuming a 2-dim array `d=np.array([[Fraction(-8,35), Fraction(3,7), Fraction(-1,5)],[Fraction(1,3), Fraction(-2,3), Fraction(1,3)],[Fraction(1,3), Fraction(2,3), Fraction(-1,1)]])`. Then `sum(d,1)=array([Fraction(0, 1), Fraction(0, 1), Fraction(0, 1)], dtype=object)`, which is fine because I sum up the row elements and the results should be zero.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46861402
type: AnswerComment

http://stackoverflow.com/comment/80472657
type: QuestionComment
comment on: http://stackoverflow.com/q/46762884
has text: Probably way more advanced that where your class is, but this might work: https://stackoverflow.com/a/18506625
score: 0
type: Comment

http://stackoverflow.com/a/46858811
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46858780
accepted answer of: http://stackoverflow.com/q/46858780
has body: The challenge with this problem is to not only detect whether there exists a match, but to figure out what matches what, and filter accordingly. One option using str.contains in a comprehension: csv1 = csv1.iloc~csv2.str2.str.contains(x).any() for x in csv1.str1 print(csv1) id str1 1 2 def 3 4 xyz
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80680166
type: Answer
has comment: http://stackoverflow.com/comment/80679829

http://stackoverflow.com/a/46853876
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80655194
accepted answer of: http://stackoverflow.com/q/46853776
has comment: http://stackoverflow.com/comment/80655095
answers question: http://stackoverflow.com/q/46853776
has comment: http://stackoverflow.com/comment/80655112
has comment: http://stackoverflow.com/comment/80655457
has body: Edit: Using regex to identify only those with numbers at the end. import re for link in links: url = str(link.get('href')) if re.findall('/askwiki/questions/[\d]+', url): print(link)
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80655671

http://stackoverflow.com/comment/80465409
type: Comment
has text: I edited my initial post with all of the functions in the program including multiply! This is a learning exercise for looping structures, which is why I'm calling my add() function instead of just multiplying.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46758280

http://stackoverflow.com/comment/80641804
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46838709
has text: There's a link in my answer: [Where do I get SSH host key fingerprint to authorize the server?](https://winscp.net/eng/docs/faq_hostkey) It's for my WinSCP SFTP client, but most information there is valid in general.
score: 0

http://stackoverflow.com/comment/80622358
comment on: http://stackoverflow.com/q/46837384
has text: @WillemVanOnsem I think I've missed the point...
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80567033
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46809693
type: QuestionComment
has text: add more info pls. Info like : which connector are You using ? are You using any ORM or You do it by Custom-SQL ?

http://stackoverflow.com/q/46804324
has answer: http://stackoverflow.com/a/46804431
accepted answer: http://stackoverflow.com/a/46804431
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/46724482
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/80571433
tagged with: urlparse
type: Question
has comment: http://stackoverflow.com/comment/80602043
has title: Scrapy - Does urlparse.urljoin behave in the same way as str.join?
upvote count: 1
answer count: 1
favorite count: 0
has body: I am trying to use urlparse.urljoin within a Scrapy spider to compile a list of urls to scrape. Currently, my spider is returning nothing, but not throwing any errors. So I am trying to check that I am compiling the urls corectly. My attempt was to test this in idle using str.join, as below: &gt;&gt;&gt; href = ['lphs.asp?id=598&amp;city=london', 'lphs.asp?id=480&amp;city=london', 'lphs.asp?id=1808&amp;city=london', 'lphs.asp?id=1662&amp;city=london', 'lphs.asp?id=502&amp;city=london',] &gt;&gt;&gt; for x in href: base = "http:/www.url-base.com/destination/" final_url = str.join(base, x) print(final_url) A one line of what that returns: lhttp:/www.url-base.com/destination/phttp:/www.url-base.com/destination/hhttp:/www.url-base.com/destination/shttp:/www.url-base.com/destination/.http:/www.url-base.com/destination/ahttp:/www.url-base.com/destination/shttp:/www.url-base.com/destination/phttp:/www.url-base.com/destination/?http:/www.url-base.com/destination/ihttp:/www.url-base.com/destination/dhttp:/www.url-base.com/destination/=http:/www.url-base.com/destination/5http:/www.url-base.com/destination/9http:/www.url-base.com/destination/8http:/www.url-base.com/destination/&amp;http:/www.url-base.com/destination/chttp:/www.url-base.com/destination/ihttp:/www.url-base.com/destination/thttp:/www.url-base.com/destination/yhttp:/www.url-base.com/destination/=http:/www.url-base.com/destination/lhttp:/www.url-base.com/destination/ohttp:/www.url-base.com/destination/nhttp:/www.url-base.com/destination/dhttp:/www.url-base.com/destination/ohttp:/www.url-base.com/destination/n I think that from my example it is obvious that str.join does not behave in the same way - if it does then there this is why my spider is not following these links! - however, it would be good to have confirmation on that. If this is not the right way to test, how can I test this process? Update Attempt using urlparse.urljoin below: from urllib.parse import urlparse &gt;&gt;&gt; from urllib.parse import urlpar…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/80714310
comment on: http://stackoverflow.com/q/46883517
score: 0
has text: ... By accessing it through `Class2`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46887497
has comment: http://stackoverflow.com/comment/80722766
has comment: http://stackoverflow.com/comment/80770643
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/80723881
has answer: http://stackoverflow.com/a/46888132
has comment: http://stackoverflow.com/comment/80722961
type: Question
possible better answer: http://stackoverflow.com/a/46887903
has answer: http://stackoverflow.com/a/46887903
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80722388
has body: I am trying to filter from a list of dictionaries returned via json.dumps. However, since it is newline-delimited JSON (where the dictionaries are not separated by commas), I am receiving an error. >>>> print my_data >>>> {u'mykey': 1234, u'color': u'red'} {u'mykey': 5678, u'color': u'orange'} {u'mykey': 5678, u'color': u'yellow'} CODE: key = 5678 test_data = json.dumps(my_data) self.response.write(test_data) # test_data outputs {"mykey": 1234, "color": "red"} {"mykey": 5678, "color": "orange"} {"mykey": 5678, "color": "yellow"} test = filter(lambda thedata: thedata['mykey'] == key, test_data) print test ERROR: test = filter(lambda thedata: thedata['mykey'] == key, test_data) TypeError: 'NoneType' object is not iterable When I copy the same data into a Python interpreter, adding brackets and commas between each dictionary, it returns the correct output. CODE key = 5678 test_data = [ {"mykey": 1234, "color": "red"}, {"mykey": 5678, "color": "orange"}, {"mykey": 5678, "color": "yellow"}] test = filter(lambda thedata: thedata['mykey'] == key, test_data) print test OUTPUT: [{'color': 'orange', 'mykey': 5678}, {'color': 'yellow', 'mykey': 5678}] How can I fix my code or the JSON output so that I can properly filter? EDIT (Correction): I am looking for a solution using self.response.write not print. While using @Ashish Ranjan's answer, I noticed that print has a different output than self.response.write. Recommended solutions should use self.response.write: test = filter(lambda thedata: thedata['mykey'] == key, test_data) self.response.write(test) Current outputs using @Ashish's solution are: Hard-coded data: my_data = "{u'mykey': 1234, u'color': u'red'} {u'mykey': 5678, u'color': u'orange'} {u'mykey': 5678, u'color': u'yellow'}" test_data = ast.literal_eval("[" + re.sub(r'({[^\}]*})\s', r'\1,' , my_data) + "]") test = filter(lambda thedata: thedata['mykey'] == 5678, test_data) self.response.write(test_data) [{u'mykey': 1234, u'color': u'red'}, {u'mykey': 5678, u'color': …
has comment: http://stackoverflow.com/comment/80722396
has title: Filter Newline Delimited JSON
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/80722299
accepted answer: http://stackoverflow.com/a/46888132
has comment: http://stackoverflow.com/comment/80770688

http://stackoverflow.com/a/46814483
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/80576640
has comment: http://stackoverflow.com/comment/80576502
answers question: http://stackoverflow.com/q/46814083
has comment: http://stackoverflow.com/comment/80578591
has body: You can also put the purely recursive call in a specific method, and use a wrapper around it: def count(self): def count_rec(ptr): if ptr == None: return 0 else: return 1 + count_rec(ptr.next) return count_rec(self.head) IMO, this is cleaner than using a dummy object and/or default parameters (btw, specifying a default parameter in a recursive function is often a good sign that you should consider an internal recursive function and call it from your method with the correct initialization).
has comment: http://stackoverflow.com/comment/80599448

http://stackoverflow.com/a/46835812
answers question: http://stackoverflow.com/q/46835474
has comment: http://stackoverflow.com/comment/80620421
has comment: http://stackoverflow.com/comment/80620243
accepted answer of: http://stackoverflow.com/q/46835474
score: 1
has comment: http://stackoverflow.com/comment/80621248
has comment: http://stackoverflow.com/comment/80622164
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80620619
has comment: http://stackoverflow.com/comment/80621957
has body: I'm afraid I don't understand what you're trying to achieve with data1[0,3].replace("\n","") and (data2[0,3].replace("\n","") If I understand you correctly, there are multiple passwords and usernames in each of their files, and any password can be used with any username? If so, then you want to do this: if content2 in data1.split("\n") and content in data2.split("\n"): message = "You have access to something special." Note you will need to change file1.readlines() and file.readlines() to file1.read() and file.read() for this to work, or simply take the \n off the end of each line with something like: data1 = [i[:-1] for i in file.readlines()] and data2 = [i[:-1] for i in file1.readlines()] EDIT: In order to make it so the first must match the first etc. you can do this: data1 = data1.split("\n") data2 = data2.split("\n") for i in range(len(data1)): if data1[i] == content2 and data2[i] == content: message = "You have access to something special." break
has comment: http://stackoverflow.com/comment/80620185
has comment: http://stackoverflow.com/comment/80620314
has comment: http://stackoverflow.com/comment/80621681
type: Answer
has comment: http://stackoverflow.com/comment/80622458
has comment: http://stackoverflow.com/comment/80620514
has comment: http://stackoverflow.com/comment/80621146
has comment: http://stackoverflow.com/comment/80620470
has comment: http://stackoverflow.com/comment/80620002
upvote count: 1

http://stackoverflow.com/comment/80511475
type: Comment
has text: {% csrf_token %} {% crispy form %}
type: AnswerComment
comment on: http://stackoverflow.com/a/46757887
score: 0

http://stackoverflow.com/a/46861106
answers question: http://stackoverflow.com/q/46860908
accepted answer of: http://stackoverflow.com/q/46860908
has body: This should do: string1 = 'Hello how are you' string2 = 'are you doing now?' i = 0 while not string2.startswith(string1[i:]): i += 1 sFinal = string1[:i] + string2 OUTPUT : &gt;&gt;&gt; sFinal 'Hello how are you doing now?' or, make it a function so that you can use it again without rewriting: def merge(s1, s2): i = 0 while not s2.startswith(s1[i:]): i += 1 return s1[:i] + s2 OUTPUT : &gt;&gt;&gt; merge('Hello how are you', 'are you doing now?') 'Hello how are you doing now?' &gt;&gt;&gt; merge("This is a nice ACADEMY", "DEMY you know!") 'This is a nice ACADEMY you know!'
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
score: 8

http://stackoverflow.com/comment/80457938
score: 0
type: AnswerComment
has text: replace combination with permutation
type: Comment
comment on: http://stackoverflow.com/a/46752487

http://stackoverflow.com/comment/80729627
type: QuestionComment
comment on: http://stackoverflow.com/q/46891026
score: 1
has text: The laziest (but still fast) solution would be an `if` branching to `matrix[:,mask]` for `axis=0` and `matrix[:,mask]` for `axis=1`.
type: Comment

http://stackoverflow.com/q/46776193
downvote count: 0
has answer: http://stackoverflow.com/a/69147672
has body: I have a python script with each time running ,it returns a new value. Then I need to add those values to a google sheet. So every day the outcome of the scripts will be added to a new row. I tried to use “pygsheet” lib but I can not handle the addition to new row for each day. How can I add the data to the last empty row?
has title: How to update google sheet with new outcome every time python script runs?
possible better answer: http://stackoverflow.com/a/58879108
has answer: http://stackoverflow.com/a/58879108
type: AnsweredQuestion
tagged with: python
favorite count: 0
score: 4
type: Question
tagged with: pygsheets
tagged with: google-sheets-api
has answer: http://stackoverflow.com/a/46778151
accepted answer: http://stackoverflow.com/a/46778151
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/73956683

http://stackoverflow.com/a/46833042
has comment: http://stackoverflow.com/comment/80967271
upvote count: 1
has comment: http://stackoverflow.com/comment/80634866
has comment: http://stackoverflow.com/comment/80635018
has body: We can easily produce valid strings using itertools.product to produce tuples of 'a' and 'b' of the required length, join the tuples into strings, and then filter out strings that don't contain 'bbb'. We don't need to store all the strings in a list. Instead, we produce them using a generator function. To count the number of valid strings of a given length we still don't need to make a list. We can easily count the strings yielded by the generator using the built-in sum function and a generator expression. Here's a short demo. from itertools import product def make_valid(n): for s in map(''.join, product('ab', repeat=n)): if 'bbb' in s: yield s # Print all the valid strings for n = 5 for i, t in enumerate(make_valid(5), 1): print(i, t) print() # Count the number of valid strings for some small values of n for n in range(16): print(n, sum(1 for _ in make_valid(n))) print() output 1 aabbb 2 abbba 3 abbbb 4 babbb 5 bbbaa 6 bbbab 7 bbbba 8 bbbbb 0 0 1 0 2 0 3 1 4 3 5 8 6 20 7 47 8 107 9 238 10 520 11 1121 12 2391 13 5056 14 10616 15 22159 This strategy is ok for small n, but we need a formula to calculate those counts for larger n. Fortunately, this sequence can be found in the OEIS as sequence A050231, which lists a couple of useful formulae. It even has some Python code, although we can make a more efficient function using a different formula. Using this formula we can easily calculate the counts for large n, although for n &gt; 1000 we may need to increase the recursion limit (depending on what's in the cache dictionary). import sys def valid_num(n, cache={0:0, 1:0, 2:0, 3:1, 4:3}): if n in cache: return cache[n] v = cache[n] = 2 * valid_num(n-1) - valid_num(n-4) + (1 &lt;&lt; (n-4)) return v # Calculate the same counts using the formula for n in range(16): print(n, valid_num(n)) print() # Calculate some larger counts using the formula for n in (20, 100, 1000): print(n, valid_num(n)) print() # Calculate the count for n = 10000 sys.setrecursionlimit(10000) n = 10000 v…
accepted answer of: http://stackoverflow.com/q/46830743
answers question: http://stackoverflow.com/q/46830743
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/80981822
score: 1

http://stackoverflow.com/a/46845534
answers question: http://stackoverflow.com/q/46792252
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Numpy is a scikitlearn dependency. That means SKlearn is made on top of numpy. Creating a virtualenv is a great idea so as to understand what the real issue is. The same code worked for me and I can tell you the prediction is "orange". :P

http://stackoverflow.com/comment/80502107
score: 1
has text: `print(example + "World")` instead of `(List + "World")` and also change line 5 to be `for example in List:`
comment on: http://stackoverflow.com/q/46778135
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80470983
score: 0
type: Comment
has text: @GabeF. Yes, it's perfectly alright - you're just taking the columns you need, instead of every column.
comment on: http://stackoverflow.com/a/46762509
type: AnswerComment

http://stackoverflow.com/a/46868698
has body: As mentioned in the comments above- print your list: a=[] for i in range(0,10): a.append(i) print(a)
answers question: http://stackoverflow.com/q/46868593
type: Answer
score: 0

http://stackoverflow.com/q/46826539
has answer: http://stackoverflow.com/a/46826597
has answer: http://stackoverflow.com/a/46826733
tagged with: python
possible better answer: http://stackoverflow.com/a/46826597
accepted answer: http://stackoverflow.com/a/46826733
type: AnsweredQuestion
has body: I am attempt to rename files which replace 'VV' with VV alist = ["py'VV'1.File.md", "py'VV'3.Database.md", "py'VV'Projects.md", "py'VV'2.Input.md"] my desired output: newlist = ["pyVV1.File.md", "pyVV3.Database.md", "pyVVProjects.md", "pyVV2.Input.md"] My solution [i.replace("'VV'",'VV') for i in alist] Out[158]: ['pyVV1.File.md', 'pyVV3.Database.md', 'pyVVProjects.md', 'pyVV2.Input.md'] How to handle it in a magic access to disappear the quote' 'automatically. for instances: In [163]: eval('str') Out[163]: str
has comment: http://stackoverflow.com/comment/80600603
upvote count: 1
downvote count: 1
type: Question
has title: Remove quote signs from multiple strings
score: 0
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/80721653
score: 0
type: Comment
type: AnswerComment
has text: did you restart server?
comment on: http://stackoverflow.com/a/46881859

http://stackoverflow.com/comment/80717984
type: Comment
has text: just to clarify that I did not intend to have an `AdultCounter`... I wanted to have a `GuestsCounter` that would hold in it items representing amounts of adults, kids and babies...
comment on: http://stackoverflow.com/a/46829862
score: 0
type: AnswerComment

http://stackoverflow.com/comment/102751649
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47135203
has text: what theme in VS Code is that btw? looks great!

http://stackoverflow.com/comment/80701700
comment on: http://stackoverflow.com/q/46877090
score: 0
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157240/discussion-between-rajkris-and-nuradilla).

http://stackoverflow.com/comment/80543022
type: QuestionComment
has text: This is wrong for a start: ``WSGIApplicationGroup $(GLOBAL)``. Should be ``WSGIApplicationGroup %{GLOBAL}``.
comment on: http://stackoverflow.com/q/46791164
score: 0
type: Comment

http://stackoverflow.com/comment/80631300
type: Comment
comment on: http://stackoverflow.com/a/46835806
score: 0
type: AnswerComment
has text: And now we've come across a difference between Python 2 and 3 :). I was working in 2.7; in Python 3, `filter` is a generator, and thus in this case should be wrapped in `list()`.

http://stackoverflow.com/q/46874934
type: Question
has answer: http://stackoverflow.com/a/46875066
has comment: http://stackoverflow.com/comment/80697165
has comment: http://stackoverflow.com/comment/80697235
score: 0
has comment: http://stackoverflow.com/comment/80697272
has comment: http://stackoverflow.com/comment/80697330
answer count: 2
has answer: http://stackoverflow.com/a/46875094
has comment: http://stackoverflow.com/comment/80697341
has comment: http://stackoverflow.com/comment/80697190
has comment: http://stackoverflow.com/comment/80697297
type: UnansweredQuestion
has body: I started a new project in django and created a development and a testing environment with their settings in the same folder as the custom settings.py everything is going well till I created a static file directory and I tried to collect static files but got error. raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. this is my directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR), "static", "static"), ) test_settings.py # -*- coding: utf-8 -*- from .settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
tagged with: python
has title: django staticfiles collection error
has comment: http://stackoverflow.com/comment/80697210
tagged with: django
has comment: http://stackoverflow.com/comment/80697287

http://stackoverflow.com/comment/80612575
type: QuestionComment
has text: There's something I'm confused about: if the order of the path matters, why are checking a simple set intersection between two paths? That will only tell you whether the two paths include the same node, and it's not clear that's what you actually want. It's making it difficult to optimize this without understanding your logic.
score: 0
comment on: http://stackoverflow.com/q/46830943
type: Comment

http://stackoverflow.com/comment/80634286
comment on: http://stackoverflow.com/a/46843291
type: Comment
has text: Thanks. I can't seem to get that to work either: `50 <class 'str'>` `Name: zipcode, dtype: object` `This is c_data types: object` `This is c_df data types: zipcode object` `dtype: object` `zipcode object` `dtype: object` `We cleaned up our data. Let's join the dataframes.` `Final result...raise ValueError('len(right_on) must equal the number '` `ValueError: len(right_on) must equal the number of levels in the index` ` of "left"`
type: AnswerComment
score: 0

http://stackoverflow.com/a/46903355
answers question: http://stackoverflow.com/q/46902801
type: Answer
has comment: http://stackoverflow.com/comment/80796636
has body: Not sure I follow everything that's happening in your question, but it appears that you're trying to do too much in listheaders. If I understand correctly, you want to use a helper function to construct def _get_header_list(name_of_state, input_number): return ['{}{}'.format(name_of_state, str(x)) for x in range(1, input_number + 1)] first_list = _get_header_list(nameofstate[0], InputNumber) second_list = _get_header_list(nameofstate[1], InputNumber) then later... wr.writerow(['Name'] + first_list + second_list)
score: 0

http://stackoverflow.com/comment/80599952
comment on: http://stackoverflow.com/q/46825879
score: 0
type: Comment
type: QuestionComment
has text: You might want to try asking this in Superuser.

http://stackoverflow.com/q/46761067
tagged with: opencv
accepted answer: http://stackoverflow.com/a/46761449
has title: Lag while Displaying images using opecv2 and Python
has comment: http://stackoverflow.com/comment/80467926
score: 0
tagged with: image-processing
has body: I am displaying a bunch of image frames using this code snippet below: import cv2 from IPython import embed import os import glob file_list = ['/home/Sep28', '/home/Sep21', '/home/Sep29', ] count = 0 for i in file_list: file_names = glob.glob(i+"/kinect_rgb/*") file_names.sort() print "found" for j in file_names: img = cv2.imread(j) img = img[200:600,100:500] cv2.imshow("cropped",img) cv2.waitKey(50) count = count + 1 Whenever I am displaying them, the video does not flow in order, it looks like once in three frames and older frame gets inserted. I am not sure as to what could be the reason. My images look totally fine inside the folder I print the file names and they don't seem to repeat as well.
tagged with: image
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4623446
type: Question
has answer: http://stackoverflow.com/a/46761449
has comment: http://stackoverflow.com/comment/80468238
has comment: http://stackoverflow.com/comment/80467904
has comment: http://stackoverflow.com/comment/80467472
tagged with: python
answer count: 1

dtd
tags question: http://stackoverflow.com/q/46782989
type: Tag
tag name: dtd

http://stackoverflow.com/a/46843123
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46842149
type: Answer
upvote count: 4
has body: You are using that API in the wrong way. Try the following code: tips='https://api.foursquare.com/v2/venues/4b564bf1f964a520db0928e3/tips' params=dict(client_id=client_id,client_secret=client_secret,v='20170801') resp_tips=requests.get(url=tips, params=params) data_tips=json.loads(resp_tips.text) data_tips
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/80644557
accepted answer of: http://stackoverflow.com/q/46842149

http://stackoverflow.com/a/46840159
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80628793
type: Answer
accepted answer of: http://stackoverflow.com/q/46840092
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46840092
has body: From the docs (and frustratingly, not mentioned in the docs for the string type): Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters. This is normative, and accurate to the implementation. You can view the Python 3.6.3 implementation of string comparison here.
upvote count: 3

http://stackoverflow.com/comment/80699825
has text: I would suggest putting an if statement around `file_path = json.loads(response.text)['posters'][0]['file_path']` to make sure response code was 200. Just to make sure you're getting the page.
score: 0
comment on: http://stackoverflow.com/q/46876355
type: Comment
type: QuestionComment

loops
tags question: http://stackoverflow.com/q/46860234
tags question: http://stackoverflow.com/q/46832129
tags question: http://stackoverflow.com/q/46804275
tags question: http://stackoverflow.com/q/46832955
tags question: http://stackoverflow.com/q/46832256
tags question: http://stackoverflow.com/q/46901361
tags question: http://stackoverflow.com/q/46863081
tags question: http://stackoverflow.com/q/46760982
tags question: http://stackoverflow.com/q/46807716
tags question: http://stackoverflow.com/q/46866295
tags question: http://stackoverflow.com/q/46898492
tags question: http://stackoverflow.com/q/46836735
tags question: http://stackoverflow.com/q/46803270
tags question: http://stackoverflow.com/q/46807471
tags question: http://stackoverflow.com/q/46840226
tags question: http://stackoverflow.com/q/46831389
type: Tag
tags question: http://stackoverflow.com/q/46794017
tags question: http://stackoverflow.com/q/46872104
tags question: http://stackoverflow.com/q/46838614
tags question: http://stackoverflow.com/q/46823662
tags question: http://stackoverflow.com/q/46850792
tags question: http://stackoverflow.com/q/46813393
tags question: http://stackoverflow.com/q/46848614
tags question: http://stackoverflow.com/q/46851809
tags question: http://stackoverflow.com/q/46751527
tags question: http://stackoverflow.com/q/46771388
tags question: http://stackoverflow.com/q/46842849
tags question: http://stackoverflow.com/q/46904406
tags question: http://stackoverflow.com/q/46826799
tags question: http://stackoverflow.com/q/46762092
tags question: http://stackoverflow.com/q/46769257
tags question: http://stackoverflow.com/q/46875286
tags question: http://stackoverflow.com/q/46797134
tags question: http://stackoverflow.com/q/46752472
tags question: http://stackoverflow.com/q/46779264
tags question: http://stackoverflow.com/q/46842021
tags question: http://stackoverflow.com/q/46835252
tag name: loops
tags question: http://stackoverflow.com/q/46819728
tags question: http://stackoverflow.com/q/46810211
tags question: http://stackoverflow.com/q/46831819
tags question: http://stackoverflow.com/q/46789803
tags question: http://stackoverflow.com/q/46843740
tags question: http://stackoverflow.com/q/46833533
tags question: http://stackoverflow.com/q/46798399
tags question: http://stackoverflow.com/q/46826617
tags question: http://stackoverflow.com/q/46831705
tags question: http://stackoverflow.com/q/46807707
tags question: http://stackoverflow.com/q/46788960
tags question: http://stackoverflow.com/q/46749191
tags question: http://stackoverflow.com/q/46881248
tags question: http://stackoverflow.com/q/46794333

http://stackoverflow.com/q/46758872
has answer: http://stackoverflow.com/a/46759031
has comment: http://stackoverflow.com/comment/80463454
has title: expected value in python
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
tagged with: python
upvote count: 3
score: 1
has body: Update** I am working on returning the expected value E[x^2]. I have already created the function normal to sample normal values with mean mu and sigma2. I want to use this function to generate normal values and then apply fun to each of those values. Do I need to define expected value in my loop and then apply fun? Can I take the mean after I find x^2 for each x? Here's what I've been working on: def fun(x): y=x**2 return y def EV(fun,n_samples,mu,sigma2): for i in range(1,n_samples): ... u= np.random.uniform(0,1,1) ... output.append(float(y)) ... return output
tagged with: scipy
type: Question
tagged with: numpy

http://stackoverflow.com/q/46869099
accepted answer: http://stackoverflow.com/a/46869238
has title: Max value that changes as new data comes in with Python 3.5
downvote count: 1
type: Question
score: -1
tagged with: python-3.5
upvote count: 0
tagged with: max
answer count: 1
has answer: http://stackoverflow.com/a/46869238
favorite count: 0
tagged with: python
has body: I am newer to coding and this may have a simple solution, but basically I am trying to record incoming data from sensors connected to an Arduino. For my purposes I would like to not only record the data that is coming in, but also the highest value that the trial had. The code that I have results in only making the Max_Force = 0. My end goal is to have all of the values that I am recording to also save the max value. Then finally linking all of these values to a GUI for easy operator use. import serial import csv import time import numpy as np import warnings import serial import serial.tools.list_ports arduino_ports = [ p.device for p in serial.tools.list_ports.comports() if 'Arduino' in p.description ] if not arduino_ports: raise IOError("No Arduino found") if len(arduino_ports) &gt; 1: warnings.warn('Multiple Arduinos found - using the first') Arduino = serial.Serial(arduino_ports[0]) Arduino.flush() Arduino.reset_input_buffer() start_time=time.time() Distance = 0.5 # This is how long the lever arm is in feet with open('DynoData.csv', 'w') as outfile: outfileWrite = csv.writer(outfile) while True: while (Arduino.inWaiting()==0): pass try: data = Arduino.readline() dataarray = data.decode().rstrip().split(',') Arduino.reset_input_buffer() Force = round(float(dataarray[0]),3) Max_Force = 0 if Max_Force &lt; Force: Max_Force == Force else: Max_Force == Max_Force RPM = round(float (dataarray[1]),3) Torque = round(Force * Distance,3) HorsePower = round(Torque * RPM / 5252,3) Run_Time = round(time.time()-start_time,3) print (Force ,",",Max_Force ) except (KeyboardInterrupt, SystemExit,IndexError,ValueError): pass outfileWrite.writerow([Force,",",Max_Force,"lbs", RPM, "RPMs", Torque,"ft-lbs" ,HorsePower ,"HP" ,Run_Time ,"sec" ])
type: AnsweredQuestion

http://stackoverflow.com/comment/80706434
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46879416
has text: I will update my question with the actual code because maybe the problem lies outside of the general case that I made up

http://stackoverflow.com/comment/111541865
score: 0
type: Comment
has text: You are right, I maybe mixed up between criterion and splitter. I'll investigate and edit the answer this week end.
comment on: http://stackoverflow.com/a/46759065
type: AnswerComment

http://stackoverflow.com/q/46829489
has comment: http://stackoverflow.com/comment/80612930
has comment: http://stackoverflow.com/comment/80606528
accepted answer: http://stackoverflow.com/a/46830917
has comment: http://stackoverflow.com/comment/80606769
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/46830917
score: -1
has body: I am pretty new to python. I am trying to combine 2 csv files into one, selecting specific rows and columns. csv1: Host, Time Up, Time Down, Time Unreachable, Time Undetermined server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000 server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000 Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000 csv2: Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,server_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,server_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 ,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000 Here is the code which combines the two files: import csv itertools as IT filenames = ['csv1.csv', 'csv2.csv'] handles = [open(filename, 'rb') for filename in filenames] readers = [csv.reader(f, delimiter=',') for f in handles] with open('combined.csv', 'wb') as h: writer = csv.writer(h, delimiter=',', lineterminator='\n', ) for rows in IT.izip_longest(*readers, fillvalue=['']*3): combined_row = [] for row in ro…
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has title: read and parse through csv file [python3.6]
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/80613363
has comment: http://stackoverflow.com/comment/80611495
has comment: http://stackoverflow.com/comment/80611289
type: AnsweredQuestion

http://stackoverflow.com/comment/80918275
has text: Please see [how-to-ask](https://stackoverflow.com/help/how-to-ask). Providing some code sample could go a long way.
comment on: http://stackoverflow.com/q/46892798
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46965504
score: 0
type: Answer
has body: I was able to get the required answer by running a count query, where ts_list is a list of datetime elements session.query(TABLE).filter(TABLE.QueryTimestamp.in_(ts_list)).count()
answers question: http://stackoverflow.com/q/46858626

http://stackoverflow.com/a/46817456
upvote count: 6
has comment: http://stackoverflow.com/comment/80585445
type: Answer
score: 6
has body: Providing an example of how you could format a row with a particular format and then the rest of the cells with a different format. Please note that you will have to call a saved workbook for the styles I've used to work. That is, in this example I create a workbook, save it, then load it and format the cells, and then save again. There are a bunch of examples of different formats you can use in the openpyxl docs section on styles. This is a fully reproducible example using data from pandas_datareader module. import pandas as pd from openpyxl import Workbook from openpyxl import load_workbook from openpyxl.styles import Font from openpyxl.utils.dataframe import dataframe_to_rows import pandas_datareader.data as web #optional for example only #pull in your own dataframe and remove the next two lines if you want to df = web.DataReader("AMZN", 'google') df = df.tail(180) wb = Workbook() ws = wb.active for r in dataframe_to_rows(df, index=False, header=True): ws.append(r) wb.save("test.xlsx") wb = load_workbook('test.xlsx') ws = wb['Sheet'] style_1 = Font(color='0000FF00', bold=True, underline="single", size=15) style_2 = Font(color='000000FF', italic=True, size=10) for cell in ws["1:1"]: cell.font = style_1 for row in ws.iter_rows(min_row=2, max_col=5, max_row=len(df)+2): for cell in row: cell.font = style_2 #commented out my original snippet - preferred method recommended by Charlie Clark is ws.iter_rows() - above ''' for i in range(2, len(df)+2): current = "%d:%d" % (i, i) for cell in ws[current]: cell.font = style_2 ''' wb.save("test.xlsx") **UPDATE (Based on a comment by the OP asking about formatting cells appended to existing worksheet): If you're adding more to this sheet later you can do the formatting at the same time for the new cells. Add the snippet below to the original answer. wb = load_workbook('test.xlsx') ws = wb['Sheet'] ws['A182'] = "New String" for cell in ws["182:182"]: cell.font = style_1 wb.save("test.xlsx")
has comment: http://stackoverflow.com/comment/80617483
answers question: http://stackoverflow.com/q/46816397
has comment: http://stackoverflow.com/comment/80582973
downvote count: 0
has comment: http://stackoverflow.com/comment/80598017

http://stackoverflow.com/comment/80687262
has text: Thanks a lot for your great explanation! Very well described. This is exactly what I was looking for. Many thanks once again :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46867142

http://stackoverflow.com/a/46844195
upvote count: 0
answers question: http://stackoverflow.com/q/46838603
type: Answer
score: -1
downvote count: 1
has body: https://gist.github.com/bondnotanymore/9afc91cb1730c9b9f637326fafc69371 This is improved piece of code with a little more robustness added. Output C:\Python27\python.exe C:/Users/kapil/PycharmProjects/KapilsucksatPython/py/O.py 16 is not even a multiple of 3 27 is a number, which is 3th power of 3 21 is not a power of 3, but just a multiple of 3 243 is a number, which is 5th power of 3 729 is a number, which is 6th power of 3 Process finished with exit code 0

http://stackoverflow.com/a/46905053
score: 0
has body: The issue is because you're encoding the FormData itself, which is incorrect. It is binary data which cannot be encoded in the manner you're attempting. You instead need to invert the logic to add the CSRF token to the FormData you send. You also need to set processData and contentType to false so the binary data is not amended before the request is sent, and also remove the traditional property. Try this: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); form_data.append('csrfmiddlewaretoken', $("input[name='csrfmiddlewaretoken']").val()); $.ajax({ type:'POST', url: '/change_banner_image/', data: form_data, processData: false, contentType: false, cache: false, success: function(response){ console.log('Success'); }, }); });
has comment: http://stackoverflow.com/comment/80759521
type: Answer
has comment: http://stackoverflow.com/comment/80757281
has comment: http://stackoverflow.com/comment/80759009
has comment: http://stackoverflow.com/comment/80757467
has comment: http://stackoverflow.com/comment/80759064
answers question: http://stackoverflow.com/q/46905022
has comment: http://stackoverflow.com/comment/80757559
has comment: http://stackoverflow.com/comment/80759476

http://stackoverflow.com/comment/80464694
comment on: http://stackoverflow.com/a/46759630
type: AnswerComment
score: 0
type: Comment
has text: This finds the groups, but does not discount groups already used.

variables
tag name: variables
tags question: http://stackoverflow.com/q/46859181
tags question: http://stackoverflow.com/q/46801195
tags question: http://stackoverflow.com/q/46771388
type: Tag
tags question: http://stackoverflow.com/q/46856087
tags question: http://stackoverflow.com/q/46846149
tags question: http://stackoverflow.com/q/46749521
tags question: http://stackoverflow.com/q/46819728
tags question: http://stackoverflow.com/q/46888033
tags question: http://stackoverflow.com/q/46857835
tags question: http://stackoverflow.com/q/46774295
tags question: http://stackoverflow.com/q/46871767
tags question: http://stackoverflow.com/q/46766362
tags question: http://stackoverflow.com/q/46833451

http://stackoverflow.com/q/46775963
has comment: http://stackoverflow.com/comment/80497552
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80497777
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80497539
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46776199
accepted answer: http://stackoverflow.com/a/46776199
has title: Create a JSON per row of csv
downvote count: 0
has comment: http://stackoverflow.com/comment/80497896
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80497668
answer count: 1
has body: I'm trying to figure out how to tweak my code so that it will write each row of a csv to its own json, which will then be posted (with how I want to try and loop through this, the json file being overwritten each time is no issue). My code produces structured jsons as I need it to and formats everything to the correct data type, but I cannot for the life of me figure out how to loop through this row wise. I have another piece of code which can achieve this second aim, but all my attempts at combining them have failed so far. Any suggestions of how I might loop through this code? output = [] with open('Test3.csv') as csv_file: for a in csv.DictReader(csv_file): output.append({ 'OrderType': a['OrderType'], 'OrderStatus': a['OrderStatus'], 'OrderDateTime': a['OrderDateTime'], 'SettlementDate': a['SettlementDate'], 'MarketId': int(a['MarketId']), 'OrderRoute': a['OrderRoute'], 'OrderEntityType': a['OrderEntityType'], 'SecurityId': a['SecurityId'], 'CurrencyISOCode': a['CurrencyISOCode'], 'Price': float(a['Price']), 'TotalCommission': float(a['TotalCommission']), 'SettlementStatus': a['SettlementStatus'], 'QuantitySettled': float(a['QuantitySettled']), 'SecurityOrderAllocations': { 'Reference': a['Account Number'], 'InvestmentCollectiveId': a['Account Number'], 'NominalAmount': float(a['QuantitySettled']), 'InvestmentAmount': float(a['InvestmentAmount']), 'OpenNominal': float(a['QuantitySettled']), 'SettlementCurrencyISOCode': 'USD', 'SettlementAccountId': a['Account Number'], 'OrderToSettlementExchangeRate': float('1'), 'SettlementToPortfolioExchangeRate': float('1'), 'OrderToPortfolioExchangeRate': float('1') } }) output_json = json.dumps(output) with open ('Test.json', 'w') as f: f.write(output_json)

http://stackoverflow.com/a/46880300
type: Answer
accepted answer of: http://stackoverflow.com/q/46880264
answers question: http://stackoverflow.com/q/46880264
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: You have to call it with module.function() format. So in this case, it should be called like as follows: inst = lsystems.applyRules("F") You have to access all the methods from your module with the same format. For processString(Oldstr), it should be similar. test_string = lsystems.processString("Somestring")

http://stackoverflow.com/a/46891396
downvote count: 0
answers question: http://stackoverflow.com/q/46891019
score: 7
has body: You can create a Row Class with the header as fields, and use zip to loop through the list row wise and construct a row object for each row: lst = [[1, 2, 3], ['A', 'B', 'C'], ['aa', 'bb', 'cc']] from pyspark.sql import Row R = Row("A1", "A2", "A3") sc.parallelize([R(*r) for r in zip(*lst)]).toDF().show() +---+---+---+ | A1| A2| A3| +---+---+---+ | 1| A| aa| | 2| B| bb| | 3| C| cc| +---+---+---+ Or if you have pandas installed, create a pandas data frame first; You can create a spark data frame from pandas data frame directly by using spark.createDataFrame: import pandas as pd headers = ['A1', 'A2', 'A3'] pdf = pd.DataFrame.from_dict(dict(zip(headers, lst))) spark.createDataFrame(pdf).show() +---+---+---+ | A1| A2| A3| +---+---+---+ | 1| A| aa| | 2| B| bb| | 3| C| cc| +---+---+---+
upvote count: 7
type: Answer

http://stackoverflow.com/comment/80483922
score: 1
type: AnswerComment
has text: A version update fixed it! The macbook had version 0.18.2 before, now both are 0.19 and they generate identical results given a fixed seed. Thank you.I agree that a "better result" is relative in this scenario, I was referring to non-overlapping clusters.
type: Comment
comment on: http://stackoverflow.com/a/46768904

http://stackoverflow.com/comment/80637107
type: QuestionComment
comment on: http://stackoverflow.com/q/46842173
score: 0
type: Comment
has text: Welcome to Stackoverflow. Make sure you have read [ask] and [mcve]. When reporting about an undesired behaviour like an error, you need to include a [mcve] of the issue and the full error traceback, not just the last line of it. Try to use some random data inside the code. Also see [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)

http://stackoverflow.com/q/46862834
has comment: http://stackoverflow.com/comment/80675606
tagged with: text
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
tagged with: recursion
has answer: http://stackoverflow.com/a/46864223
tagged with: hierarchical-clustering
has body: I am trying to plot some data (groups of countries by their distances) with a simple text dendrogram that would display in my terminal like this: ---- Monaco ----| ---- Croatia ----| ---- Montenegro ----| ---- Serbia ----| ---- Slovenia ----| ---- Austria ----| ---- Switzerland ----| ---- Germany ----| ---- Belgium ----| ---- Netherlands ----| ---- France ----| ---- Sweden ----| ---- Denmark ----| ---- Norway I have data stored in a matrix of pairs of clusters with their distances, called draw_clusters, and it looks something like this: ['Monaco', [[[[['Croatia ', 'Montenegro ', 1.9148542155126762], ['Serbia ', 'Slovenia ', 2.469532658074352], 2.6659130840453282], ['Austria ', ['Switzerland ', 'Germany', 1.8487591643481294], 2.843561940573178], 3.3080033351363003],['...', '...']...[...]] So far I wrote this code, but I don't know how to call the function recursively so that it would plot the text dendrogram into terminal: def draw_dendrogram(draw_clusters): for cluster in range(len(draw_clusters)): dendrogram(draw_clusters[cluster], 0, 0, 0) def dendrogram(cluster, x, y, distance): node = "|" vertical_line = "---" print(cluster) Can anyone help me with any tips, because I am new to Python and I am not really sure how the recursion should work?
tagged with: dendrogram
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46864223
favorite count: 0
has title: How to display a simple text dendrogram in terminal?
tagged with: python

http://stackoverflow.com/comment/80698191
has text: use `check_output` instead, and `split(":")`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46875588

http://stackoverflow.com/comment/80625058
has text: @WillemVanOnsem Thanks for pointing that out - I fixed the code to actually call the function requested in the map. What I have now should work, since the map dict only stores the function reference, and then only said function is evaluated when the data variable is assigned in the mapper function. Unless I'm missing something else?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46838446

http://stackoverflow.com/q/46846612
has answer: http://stackoverflow.com/a/46852444
tagged with: google-app-engine
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/46852444
upvote count: 2
has body: I'm using the google cloud datastore library a flexible environment on Google App Engine. I have a run entity which I use as a parent for pathway entities: ds = datastore.Client('project-name') parent = ds.query(kind='run', order=('-timestamp',)).fetch(1) parent = list(parent)[0] print(parent.key) # &lt;Key('run', 1), project=project-name&gt; If I fetch some pathway entities, they seem to have the correct parent pathways = ds.query(kind='pathway', order=('-timestamp',)).fetch(limit=10) for pathway in pathways: print(pathway.key.parent) # &lt;Key('run', 1), project=project-name&gt; But if I try to filter with the parent like this: pathways = ds.query(kind='pathway', ancestor=parent.key, order=('-timestamp',)).fetch(limit=10) Then I get an error: google.api.core.exceptions.PreconditionFailed google.api.core.exceptions.PreconditionFailed: 412 no matching index found. recommended index is: - kind: pathway ancestor: yes properties: - name: timestamp direction: desc How do I correctly filter with the parent entity?
type: AnsweredQuestion
type: Question
has title: Querying Google Cloud datastore with ancestor not returning anything
tagged with: google-cloud-datastore
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/46864583
score: 0
has body: input_file="$1" for ((i = 2 ; i &lt; 3 ; i++ )); do echo $i python extract_random_columns.py "$input_file" "$i" done remove $ from $input_file in first line
type: Answer
has comment: http://stackoverflow.com/comment/80676710
has comment: http://stackoverflow.com/comment/80676631
answers question: http://stackoverflow.com/q/46864521

http://stackoverflow.com/comment/80740353
score: 0
comment on: http://stackoverflow.com/q/46896536
type: Comment
type: QuestionComment
has text: why on earth would you use actionscript???

http://stackoverflow.com/comment/80557995
comment on: http://stackoverflow.com/q/46805405
score: 0
has text: How would you have a grid of triplets? I mean, which would be your two axis? Would "triplets = {(0.0, 0.0, 1.0), (0.0, 0.01, 0.99), ...}` be acceptable?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80684480
type: QuestionComment
has text: @user2357112 it doesn't matter as n^x != n+x when n == x
comment on: http://stackoverflow.com/q/46868422
score: 0
type: Comment

http://stackoverflow.com/q/46867851
downvote count: 0
score: 1
has title: a becomes z, b becomes y. abcd becomes zyxw ...etc in python
type: Question
type: AnsweredQuestion
has body: def string_transf(): input('Enter a word or string') #letters = 'abcdefghijklmnopqrstvwxyz' #for i in letters: #i+= if c &gt;= 'a' and c &lt;='z': i = 'z' - c + 'a' print(i) I tried to come up with an algorithm, but I'm lost.
possible better answer: http://stackoverflow.com/a/46867944
has comment: http://stackoverflow.com/comment/80683056
has answer: http://stackoverflow.com/a/46867944
answer count: 2
upvote count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/80683245
tagged with: python
has answer: http://stackoverflow.com/a/46868222
accepted answer: http://stackoverflow.com/a/46868222
has comment: http://stackoverflow.com/comment/80683360

http://stackoverflow.com/a/46901863
score: 0
type: Answer
has body: I tried to use print(FPKM) to print everything, but it only prints the keys. I don't think so. a = {'hello': 'world'} print(a) # The entire dictionary is printed {'hello': 'world'} I also wanted to pickle out this FPKM object, but it turned out that only the keys were stored in the pickle file. See How can I use pickle to save a dict? import pickle a = {'hello': 'world'} with open('filename.pickle', 'wb') as f: pickle.dump(a, f, protocol=pickle.HIGHEST_PROTOCOL) with open('filename.pickle', 'rb') as f: b = pickle.load(f) print(a == b) # True print(b) # The original dictionary persists {'hello': 'world'}
answers question: http://stackoverflow.com/q/46901638

http://stackoverflow.com/q/46877593
has comment: http://stackoverflow.com/comment/80702314
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django
has body: I am not able to make a multiple choice filter with checkbox in Django. I researched but couldn't find anything practical either than to use django_filters.MultipleChoiceFilter. I want to show as Checkboxes the distinct values of Category column from my Book Model (e.g.: "Fiction", "Romance", "Improvement") . Using PostgreSQL model class Book(models.Model): name = models.CharField(max_length=350) author = models.CharField(max_length=350) category = models.CharField(max_length=200) def __str__(self): return self.name filter class BookFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') author = django_filters.CharFilter(lookup_expr='icontains') category = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple,) #does not contain any parameters to enter any queryset or anything class Meta: model = Book fields = ['name', 'author', 'category',] views class SearchBooksView(TemplateView): template_name = "booksearch.html" book_list = Book.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_filter = BookFilter(self.request.GET) context['book_filter'] = book_filter return context booksearch.html Book Search {{ book_filter.form.as_p }} Search {% for book in book_filter.qs %} {{ book.name }} - {{ book.author}} - {{ book.category}} {% endfor %} Can you lend a helping hand? Thank you!
type: Question
has title: MultipleChoiceFilter with distinct values Django
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80702500
favorite count: 0
tagged with: filter
tagged with: python

http://stackoverflow.com/q/46870593
has title: Query for user in AD using python
has body: I am trying to write a python script to validate if a username exists in a particular domain or not . To query : username -- &gt; anandabhis domain name --&gt; example.com Output : Successfully verified . For this I have used python-ldap module to connect to LDAP server . But I am unable to proceed further even after reading lots of documentations. import ldap def test_login(self): domain = 'EXAMPLE' server = 'ldap-001.example.com' admin_username = 'admin' admin_password = 'secret-password' connection = ldap.initialize('ldap://{0}'.format(server)) connection.protocol_version = 3 connection.set_option(ldap.OPT_REFERRALS, 0) connection.simple_bind_s('{0}\{1}'.format(domain, admin_username), admin_password) search_username = 'anandabhis'
tagged with: python
score: 0
type: Question
has comment: http://stackoverflow.com/comment/80688581
tagged with: ldap
has comment: http://stackoverflow.com/comment/80752223
linked to: http://stackoverflow.com/q/40225230
has comment: http://stackoverflow.com/comment/80694146
answer count: 1
tagged with: scripting
has answer: http://stackoverflow.com/a/46945079
type: UnansweredQuestion

http://stackoverflow.com/q/46794141
has body: I have 2 lists. One is a list of words and their frequencies and the other is a list of words. a = [('country',3478), ('island',2900),('river',5)] b = ['river','mountain','bank'] There are thousands of entries in a but only hundreds in b. How can I subset list a so that i return: c=[('river',5)] For loops would take too long given the number of entries and i imagine list comprehension is the solution but cannot get it right. My main goal is to then create a wordcloud with my final list. Any help would be appreciated **Edited because I made a mistake as pointed out by some commenters. I want to return c=[('river',5)] instead of c=['river',5] as i originally wrote. Apologies and thanks for pointing it out
accepted answer: http://stackoverflow.com/a/46794191
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80534987
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/46794234
has comment: http://stackoverflow.com/comment/80535009
has answer: http://stackoverflow.com/a/46794191
tagged with: list-comprehension
has title: How to subset an item:value list using another list with just items?
possible better answer: http://stackoverflow.com/a/46794234
answer count: 2
downvote count: 0
tagged with: word-cloud
favorite count: 0

inheritance
tags question: http://stackoverflow.com/q/46857728
tags question: http://stackoverflow.com/q/46868085
tag name: inheritance
type: Tag
tags question: http://stackoverflow.com/q/46828093
tags question: http://stackoverflow.com/q/46826267
tags question: http://stackoverflow.com/q/46891888
tags question: http://stackoverflow.com/q/46786358
tags question: http://stackoverflow.com/q/46780461
tags question: http://stackoverflow.com/q/46895924
tags question: http://stackoverflow.com/q/46853442

http://stackoverflow.com/comment/80494009
comment on: http://stackoverflow.com/a/46766472
score: 0
type: AnswerComment
has text: Would you be so kind to look at: https://stackoverflow.com/questions/46774161/assign-a-series-to-all-columns-of-the-dataframe-columnwise
type: Comment

http://stackoverflow.com/q/46845517
has comment: http://stackoverflow.com/comment/80639617
has comment: http://stackoverflow.com/comment/80640586
linked to: http://stackoverflow.com/q/44574086
has comment: http://stackoverflow.com/comment/80639287
possible better answer: http://stackoverflow.com/a/46846790
has body: I'm very new in Python and in Numpy. In fact, I'm just learning. I'm reading this tutorial, and I got stuck in these lines : &gt;&gt;&gt; x = np.arange(30).reshape(2,3,5) &gt;&gt;&gt; x array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]], [[15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]]]) &gt;&gt;&gt; b = np.array([[True, True, False], [False, True, True]]) &gt;&gt;&gt; x[b] array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]]) I can't understand how we have come up with the result of x[b]. I also try to guess the result of xFalse, False, False, True Please explain to me, I'm a very newbie.
has comment: http://stackoverflow.com/comment/80639582
downvote count: 0
accepted answer: http://stackoverflow.com/a/46846721
has comment: http://stackoverflow.com/comment/80638824
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/80639053
tagged with: python
has answer: http://stackoverflow.com/a/46846721
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80640556
has answer: http://stackoverflow.com/a/46846790
has comment: http://stackoverflow.com/comment/80639564
type: Question
tagged with: numpy
answer count: 2
has title: Boolean indexing on multidimensionnal array

http://stackoverflow.com/comment/80691234
has text: Thanks for the inputs Tim. After i made a few changes and add `session = requests.Session()` `session.trust_env = False`, i get HTTP 500 now
comment on: http://stackoverflow.com/q/46871253
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80742775
comment on: http://stackoverflow.com/a/46895751
type: AnswerComment
score: 0
has text: To be honest, it also worked the first time running it. After restarting my system it showed me this error. Can you try to restart your script? If it still works for you something on my system is probably not working correctly...I'll wait for your reply and if it's still running I will close this question here and open a new one with the new error.. ^^
type: Comment

http://stackoverflow.com/comment/80705415
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46878953
has text: @doze That led to the answer. I wasn't using the `--installed flag` on apt when I tried checking if apache2 was installed. Installing apache installed gcc and now it passes this step. Thanks. How do I give you credit for answer?

http://stackoverflow.com/comment/80673472
has text: you override `login` by defining a new `login` function.
score: 3
comment on: http://stackoverflow.com/q/46863008
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46873858
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80694728
has comment: http://stackoverflow.com/comment/80695256
type: Answer
accepted answer of: http://stackoverflow.com/q/46873827
has comment: http://stackoverflow.com/comment/80695390
answers question: http://stackoverflow.com/q/46873827
has body: Calling .seconds will only give you the seconds component of the timedelta object, which only takes into account seconds, minutes, and hours (see docs for more detail). If you want the entire timedelta in seconds, call total_seconds. &gt;&gt;&gt; (date1 - date2).total_seconds() 131105.0
has comment: http://stackoverflow.com/comment/80694721
score: 4

http://stackoverflow.com/comment/80468514
type: AnswerComment
comment on: http://stackoverflow.com/a/46760826
type: Comment
has text: think you may need to define your own [generator](https://wiki.python.org/moin/Generators) for the numbers. Can't help you without knowing how you come up with these numbers
score: 0

http://stackoverflow.com/a/46820742
has comment: http://stackoverflow.com/comment/80588933
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80588918
has body: Don't try to cram everything in one line, it won't be readable. This is a simple, easy-to-understand solution, even if it takes a couple of lines: from collections import defaultdict mywords = "May your coffee be strong and your Monday be short" ans = defaultdict(list) for word in mywords.split(): ans[len(word)].append(word)
type: Answer
has comment: http://stackoverflow.com/comment/80588966
answers question: http://stackoverflow.com/q/46820714

http://stackoverflow.com/a/46880132
type: Answer
answers question: http://stackoverflow.com/q/46880050
accepted answer of: http://stackoverflow.com/q/46880050
score: 1
has body: Scenario 1 MultiIndex series occurred_date nc_type 1.0 x 3 y 4 z 13 w 24 f 34 12.0 d 18 g 10 w 44 a 27 g 42 Name: test, dtype: int64 Call sort_values + groupby + head: df.sort_values(ascending=False).groupby(level=0).head(2) occurred_date nc_type 12.0 w 44 g 42 1.0 f 34 w 24 Name: test, dtype: int64 Change head(2) to head(5) for your situation. Or, expanding upon my comment with nlargest, you could do: df.groupby(level=0).nlargest(2).reset_index(level=0, drop=1) occurred_date nc_type 1.0 f 34 w 24 12.0 w 44 g 42 Name: test, dtype: int64 Scenario 2 3-col dataframe occurred_date nc_type value 0 1.0 x 3 1 1.0 y 4 2 1.0 z 13 3 1.0 w 24 4 1.0 f 34 5 12.0 d 18 6 12.0 g 10 7 12.0 w 44 8 12.0 a 27 9 12.0 g 42 You can use sort_values + groupby + head: df.sort_values(['occurred_date', 'value'], ascending=[True, False]).groupby('occurred_date').head(2) occurred_date nc_type value 4 1.0 f 34 3 1.0 w 24 7 12.0 w 44 9 12.0 g 42 Change head(2) to head(5) for your scenario. Scenario 3 MultiIndex Dataframe test occurred_date nc_type 1.0 x 3 y 4 z 13 w 24 f 34 12.0 d 18 g 10 w 44 a 27 g 42 Or, with nlargest. df.groupby(level=0).test.nlargest(2)\ .reset_index(level=0, drop=1) occurred_date nc_type 1.0 f 34 w 24 12.0 w 44 g 42 Name: test, dtype: int64
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/80822515
type: AnswerComment
score: 0
type: Comment
has text: I am unsure if it is fixed in Windows 10. My impression is that it likely isn't, at least without having some way to classify that packaged applications run on the Linux layer (which does not seem to be its primary purpose). In my case, Windows 7 compatibility is paramount.
comment on: http://stackoverflow.com/a/46802154

http://stackoverflow.com/a/46859389
answers question: http://stackoverflow.com/q/46859304
downvote count: 0
score: 3
upvote count: 3
has body: You could use np.roll in a loop. x = np.array([np.roll(foo, -x) for x in np.arange(foo.shape[0])]) print(x) array([[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]])
type: Answer

http://stackoverflow.com/comment/80632152
type: Comment
type: QuestionComment
has text: Replace all strings typed in code to Unicode. Like: 'ó' with u'ó'
comment on: http://stackoverflow.com/q/46842098
score: 0

http://stackoverflow.com/q/46750892
score: 0
has comment: http://stackoverflow.com/comment/80452884
has comment: http://stackoverflow.com/comment/80448086
answer count: 1
type: UnansweredQuestion
tagged with: http-redirect
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80452739
tagged with: django-views
tagged with: django-urls
has body: I've created a form and view in Django. I can see the add new post form when I go to http://localhost:8000/post/new/ but after I complete all required fields and click submit the page just refreshes itself and I am not redirected to the post details page. Here's my views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.createdAt = timezone.now() post.writer = request.user post.save() return redirect('posts:post_detail', pk=post.pk) else: form = PostForm() context = {'form':form} return render(request,"posts/post_new.html",context) Here's my urls.py: urlpatterns = [ url(r'^$', views.post_list, name="post_list"), url(r'^posts/(?P<post_title_slug>[\w\-]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), ] Here's my html: {% csrf_token %} {{ form.non_field_errors }} Title {{ form.title.errors }} Description here: Describe your post in this text box. {{ form.comment.errors }} Upload picture here {{ form.image.errors }} Post
has title: Django view does not redirect to details page
type: Question
has answer: http://stackoverflow.com/a/46751088

http://stackoverflow.com/q/46814874
score: 0
tagged with: file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80577585
has body: In my macbook air terminal I wrote python eggshell.py but I got this error python: can't open file 'eggshell.py': [Errno 2] No such file or directory s-user:/ user$ After I got that error I tried a number of things, like specifying exactly were eggshell.py is: python Users/myuser/Eggshell/eggshell.py Doing that just gave me a different Errno 2 error: OSError: [Errno 2] No such file or directory: 'modules/commands/macOS' If you have anything that can help me figure this out, I'd be incredibly grateful, thanks. P.S I'll attach an image of where the eggshell.py is located eggshell.py is actually located in a folder in my documents, but it shows up in the documents too, so I really don't know why python eggshell.py doesn't work.
has answer: http://stackoverflow.com/a/46815180
type: Question
has comment: http://stackoverflow.com/comment/80577195
answer count: 1
accepted answer: http://stackoverflow.com/a/46815180
has title: python: can't open file in macbook terminal - [Errno 2]!
tagged with: terminal
tagged with: errno
tagged with: python
tagged with: macos

eigen
tags question: http://stackoverflow.com/q/46858070
type: Tag
tag name: eigen

http://stackoverflow.com/comment/80729677
score: 0
type: AnswerComment
has text: in my code the class constructor has self.food_list = []
comment on: http://stackoverflow.com/a/46890822
type: Comment

http://stackoverflow.com/a/46940319
downvote count: 4
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/103343868
has body: A Pandas solution is several orders of magnitude faster: def hampel(vals_orig, k=7, t0=3): ''' vals: pandas series of values from which to remove outliers k: size of window (including the sample; 7 is equal to 3 on either side of value) ''' #Make copy so original not edited vals=vals_orig.copy() #Hampel Filter L= 1.4826 rolling_median=vals.rolling(k).median() difference=np.abs(rolling_median-vals) median_abs_deviation=difference.rolling(k).median() threshold= t0 *L * median_abs_deviation outlier_idx=difference&gt;threshold vals[outlier_idx]=np.nan return(vals) Timing this gives 11 ms vs 15 seconds; vast improvement. I found a solution for a similar filter in this post.
has comment: http://stackoverflow.com/comment/119506792
answers question: http://stackoverflow.com/q/46819260
score: 1
upvote count: 5
accepted answer of: http://stackoverflow.com/q/46819260

http://stackoverflow.com/comment/80696193
comment on: http://stackoverflow.com/q/46873354
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ Hope all the required info is in the Q
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46887946
has answer: http://stackoverflow.com/a/46888159
has title: Code crashes when the amount of elements in a list are odd
possible better answer: http://stackoverflow.com/a/46888426
type: Question
has comment: http://stackoverflow.com/comment/80723003
has comment: http://stackoverflow.com/comment/80722807
score: -1
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/80723059
upvote count: 1
linked to: http://stackoverflow.com/q/1157106
has comment: http://stackoverflow.com/comment/80723133
has answer: http://stackoverflow.com/a/46888426
has comment: http://stackoverflow.com/comment/80723005
has body: Ok so I am currently making a program that takes out every instant of the number 3 from an array/list. You can see below an example of when the array has an uneven amount of indexes. o =[1,2,3] b = 3 def remove(b,o): while o!= []: if b == o[0]: s = [o[1]] + remove(b,o[2:]) return s else: ss = [o[0]] + remove(b,o[1:]) return ss if o==[]: return o print remove(b,o) It should just print out [1,2] but it crashes.
favorite count: 0
accepted answer: http://stackoverflow.com/a/46888159
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/46878153
score: 0
answer count: 1
tagged with: interpolation
type: UnansweredQuestion
tagged with: python
tagged with: generator
has title: Python interpolation methods that accept generator expressions?
has answer: http://stackoverflow.com/a/46878258
has body: So I have a large set of N arrays, each of length N_pix. I would like to interpolate between all the arrays (i.e. perform N_pix interpolations, each with N data points), in Python. The problem is that each array is very large (can be up to 100sMB each, with 100s of arrays), and so I would like to be avoid reading all of them into memory. My initial though was to use a generator expression to read large files one by one, and pass that generator to a interpolation routine: def read_data_from_disc(paths): # Cycle through paths, and yield each large array for path in paths: yield np.loadtxt(path) def interpolation(xs, paths): # Iterable returns large arrays one by one. iterable = read_data_from_disc(paths) # Use some interpolation routine that can handle an # iterable and interpolate iterable over 1d array, xs. spline = interpolator(xs, iterable, axis=0) return spline However, I have been unsuccessful in finding any such interpolator. I am not familiar with the details of implementation of e.g. scipy.interpolate.interp1d or scipy.interpolate.CubicSpline (which are what I usually use), so perhaps what I am asking is not really possible. If this is the case can anyone suggest an alternative approach such that I do not have to read all of these arrays into memory at the same time?
has comment: http://stackoverflow.com/comment/80707492
tagged with: memory
type: Question
tagged with: arrays

http://stackoverflow.com/q/46862431
upvote count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has body: I'm involved in optimizing a Flask web application deployed using uWSGI through NGINX reverse proxy. The response time in uWSGI web-server logs seems fast for my application (6ms in avg) but I have HTTP 499 errors in 10 out of 1'000 requests and HTTP 502 errors in 4 out of 10'000 requests (The application have around two hundreds requests per second). According to this thread its seems typical to have 499 errors because the client closed connection (Question 1: Is it really typical in real applications?). how about 502 errors? is it typical in real applications?(Question 2) I guessed that requests queued in NGINX and waiting for Python response so they exceeded NGINX time limit. But seems it's not a true because everytime I test server using Google Chrome network analyzer I got the response (200) fast using a usual network bandwidth (60kbps). I test this by scripting load test. uWSGI Config: [uwsgi] http = 0.0.0.0:7000 wsgi-file = app.py callable = app processes = 12 lazy = true lazy-apps = true logto = /root/logs/data-gathering.log NGINX Config(selected parts): worker_connections 10000; keepalive_timeout 65; worker_rlimit_nofile 30000; worker_processes auto; The server load average is around 1.4 (with 4 CPU Core) and 70% of memory is still free.
answer count: 0
downvote count: 0
tagged with: uwsgi
type: Question
tagged with: nginx
tagged with: flask
has title: Is it typical to have 499 and 502 HTTP errors in real applications?
tagged with: optimization

http://stackoverflow.com/q/46820551
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80589168
linked to: http://stackoverflow.com/q/46820714
has comment: http://stackoverflow.com/comment/80589134
answer count: 2
duplicate of: http://stackoverflow.com/q/46820714
tagged with: python
accepted answer: http://stackoverflow.com/a/46820587
score: 0
possible better answer: http://stackoverflow.com/a/46820868
has answer: http://stackoverflow.com/a/46820587
has answer: http://stackoverflow.com/a/46820868
has body: Example: def test_get_word_len_dict(): text = "May your coffee be strong and your Monday be short" the_dict = get_word_len_dict(text) print_dict_in_key_order(the_dict) print() text = 'why does someone believe you when you say there are four billion stars but they have to check when you say the paint is wet' the_dict = get_word_len_dict(text) print_dict_in_key_order(the_dict) I want to get a dictionary with keys which are integers and corresponding values which are lists of unique words.The list of words corresponding to a key contains all the unique words from the text that have a length equal to the key value. The corresponding lists of unique words should be in sorted alphabetical order.I don't know how to fix my function def get_len_word_dict(): new_text = text.split() for k,v in new_text.items(): if len(v) = len(k): return k,v expected: 2 : ['be'] 3 : ['May', 'and'] 4 : ['your'] 5 : ['short'] 6 : ['Monday', 'coffee', 'strong'] 2 : ['is', 'to'] 3 : ['are', 'but', 'say', 'the', 'wet', 'why', 'you'] 4 : ['does', 'four', 'have', 'they', 'when'] 5 : ['check', 'paint', 'stars', 'there'] 7 : ['believe', 'billion', 'someone']
has title: Get word length in dict python
type: Question

http://stackoverflow.com/a/46858607
accepted answer of: http://stackoverflow.com/q/46858584
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/80664755
downvote count: 0
answers question: http://stackoverflow.com/q/46858584
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80664795
has body: You can use the built-in function any: result = [line for line in lines if any(substring in line for substring in l1)] Or, you might consider to use a regex for this.
type: Answer

http://stackoverflow.com/q/46845807
tagged with: pandas
has body: I want to mark the duplicate sequence in a list. For example: (1,1,1,0,2,3,2,4,2) My expected result is: (True,True,True,False,False,False,False,False,False) I tried pandas.DataFrame.duplicated(keep=False), but it marks '2' as duplicated: (True,True,True,False,True,False,True,False,True). How to mark the 'duplicated sequence' only?
tagged with: python
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/46846120
type: Question
type: AnsweredQuestion
tagged with: duplicates
has title: How to mark 'duplicated sequence' in pandas?
possible better answer: http://stackoverflow.com/a/46845843
has answer: http://stackoverflow.com/a/46845843
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46846120

http://stackoverflow.com/comment/80649209
score: 0
comment on: http://stackoverflow.com/q/46850706
has text: Nothing stops function, it should run forever because this thread checks the time, and when current time matches with time from db it should run some other functions. But that works correctly, just that output is the problem. @quamrana
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46902553
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46902029
type: Answer
has comment: http://stackoverflow.com/comment/80814502
has body: The same code works for me in Python 2. from dateutil.parser import parse print(parse("2017-09-19T04:31:43Z").strftime('%s')) # 1505813503 or import dateutil.parser print(dateutil.parser.parse("2017-09-19T04:31:43Z").strftime('%s')) # 1505813503 The OP claims that this does NOT work, giving the same ValueError: Invalid format string error. One explanation is that, according to this post, your option %s doesn't exist. See valid options of time.strftime here. Why did %s work on my system? Great answer by Darren Stone from this post In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us: "Other codes may be available on your platform. See documentation for the C library strftime function." So now if we man strftime (on BSD systems such as Mac OS X), you'll find support for %s: %s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))." What can you do? It seems you want the Unix timestamp. As suggested by @jleahy here, If you want to convert a python datetime to seconds since epoch you should do it explicitly: datetime.datetime(2012,04,01,0,0).strftime('%s') # '1333234800' (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds() # 1333238400.0 In Python 3.3+ you can use timestamp() instead: datetime.datetime(2012,4,1,0,0).timestamp() # 1333234800.0
answers question: http://stackoverflow.com/q/46902029
upvote count: 1
has comment: http://stackoverflow.com/comment/80769324
score: 1
has comment: http://stackoverflow.com/comment/80758642

http://stackoverflow.com/a/65883165
type: Answer
has body: I had this problem, 3 years too late however move the req file into downloads and then try it again
score: 0
answers question: http://stackoverflow.com/q/46854451
has comment: http://stackoverflow.com/comment/116486976

http://stackoverflow.com/comment/80484606
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46769067
has text: I don't think that the `signals` are going to help me. Can you explain how is it possible with signals?

http://stackoverflow.com/comment/80780849
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46912759
has text: @akeg Today I do not have time, maybe tomorrow I will help you, I would like you to try to solve this problem so that you learn some things because other problems will come and you will not be able to solve it.
score: 0

http://stackoverflow.com/a/46772745
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46772176
type: Answer
upvote count: 1
has body: When creating request you should: provide Content-Type header provide data in format that matches Content-Type header make sure application supports the format Both curl and python examples you gave sends request with Content-Type: application/x-www-form-urlencoded, the default one. The difference is curl passes string and python passes an array. Let's compare curl and requests and what is really posted: Curl $ curl localhost -X POST -d "{\"action\": \"deckNames\", \"version\": 5}" Headers: Host: localhost User-Agent: curl/7.52.1 Accept: */* Content-Length: 37 Content-Type: application/x-www-form-urlencoded Posted data: [ '{"action": "deckNames", "version": 5}' ] Python import requests r = requests.post("http://127.0.0.1", data={'action': 'guiAddCards', 'version': 5}) print(r.text) Headers: Host: 127.0.0.1 Connection: keep-alive Accept-Encoding: gzip, deflate Accept: */* User-Agent: python-requests/2.10.0 Content-Length: 28 Content-Type: application/x-www-form-urlencoded Posted data: [ 'action' -&gt; 'guiAddCards', 'version' -&gt; '5', ] As you can see, incorrect post data format breaks your app. To be sure, that posted JSON data will be properly read by application you should make requests like that: Curl $ curl localhost:8765 -H 'Content-Type: application/json' -d '{"action": "deckNames", "version": 5}' Python import requests r = requests.post("http://127.0.0.1:8765", json={'action': 'guiAddCards', 'version': 5}) print(r.text)

http://stackoverflow.com/a/46906089
score: 0
type: Answer
has body: Try this version: import numpy as np from keras.models import Sequential from keras.layers import Conv1D, MaxPooling1D, Dropout, Dense, Flatten # This generates some test sample for me to check your code X_train = np.random.rand(100, 4, 400) Y_train = np.random.rand(100, 2) model = Sequential() model.add(Conv1D(32, 3, activation='relu', input_shape=(4, 400))) model.add(MaxPooling1D(2)) model.add(Dropout(0.5)) model.add(Flatten()) # &lt;- You need a flatten here model.add(Dense(128, activation='relu')) model.add(Dense(2, activation='sigmoid')) # &lt;- the last dense must have output 2 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, Y_train, batch_size=16, epochs=10) I added a Flatten layer after the Dropout (remember to import it) Since the output is (2,), you need to have the second Dense layer to be Dense(2) If you change your output to have dimensions (1,), then put again in a Dense(1), but also change the loss from categorical_crossentropy to binary_crossentropy
has comment: http://stackoverflow.com/comment/80847737
answers question: http://stackoverflow.com/q/46905701

awk
tag name: awk
tags question: http://stackoverflow.com/q/46827087
type: Tag
tags question: http://stackoverflow.com/q/46882557
tags question: http://stackoverflow.com/q/46784727
tags question: http://stackoverflow.com/q/46771365

http://stackoverflow.com/q/46858688
has title: Why this np.where(x == np.array([1,2,3])) is returning an empty tuple?
has comment: http://stackoverflow.com/comment/80664986
upvote count: 0
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/46858760
tagged with: python
has body: Let x = np.array([9323, 11939, 231, ..., 5192, 12172, 235 ]). How I suppose to get all the different indexes in np.where(x == [0,1,2,3,4,5...9323]) ?? The command below is giving me an empty tuple : np.where(x == np.array([1,2,3])) (array([], dtype=int64),) I have to find all the exact indexes(position) for: x == [0:max(x)] please help...
favorite count: 0
type: UnansweredQuestion
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/80665010

http://stackoverflow.com/q/46831127
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46729667
upvote count: 1
has answer: http://stackoverflow.com/a/46905596
tagged with: tensorflow
type: Question
has title: pip cannot install module due to html5lib error
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46905596
score: 1
favorite count: 0
has body: I am trying to set up a tensorflow environment in win7. I followed the instructions here and I guess I have installed tensorflow. I managed to run the small script in the previous link but only inside the console of Anaconda tensorflow environment. Since the windows' console is a bit primitive (to be polite) I would like to install Ipython. The problem is I am getting an error when trying to use pip. For example: pip install pyreadline gives this Traceback (most recent call last): File "D:\Software\Anaconda3\Scripts\pip-script.py", line 6, in from pip import main File "D:\Software\Anaconda3\lib\site-packages\pip__init__.py", line 28, in from pip.vcs import git, mercurial, subversion, bazaar # noqa File "D:\Software\Anaconda3\lib\site-packages\pip\vcs\subversion.py", line 9, in from pip.index import Link File "D:\Software\Anaconda3\lib\site-packages\pip\index.py", line 33, in from pip._vendor import html5lib, requests, six ImportError: cannot import name 'html5lib' Using some instructions I also tried this one: python -m pip install pyreadline with the same output. pyreadline is considered prerequirement for Ipython I think. If my console is elevated or not does no difference. Generally speaking it seems all modules' installation attempts produce the same message. Even: pip install --ignore-installed --upgrade html5lib does so. My system is win7, python 3.6.2 and I installed tensorflow using the instruction for Anaconda. From Anaconda Navigator I see html5lib as installed. So, how can bypass this problem to be able to install new modules? Edit: I followed the instructions here which had a similar to mine problem but although accepted as an answer there it didn't solve the problem. html5lib seems to be reinstalled but other modules are not.
tagged with: python

http://stackoverflow.com/q/46753989
has comment: http://stackoverflow.com/comment/80453771
favorite count: 0
has body: Lets say we want to extract the link in a tag like this: input: some text desired output: http://www.google.com/home/etc the first solution is to find the match with reference using this href=[\'"]?([^\'" >]+) regex but what I want to achieve is to match the link followed by href. so trying this (?=href\")... (lookahead assertion: matches without consuming) is still matching the href itself. It is a regex only question.
type: UnansweredQuestion
tagged with: python
tagged with: regex
has title: how to look behind in regex without matching a pattern itself?
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80453604
type: Question
has comment: http://stackoverflow.com/comment/80453805
has comment: http://stackoverflow.com/comment/80453662
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/80453755
has answer: http://stackoverflow.com/a/46754067
answer count: 3
has answer: http://stackoverflow.com/a/46754824
has answer: http://stackoverflow.com/a/46757358

http://stackoverflow.com/comment/80563553
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46805966
has text: Have a look at this question this might help you: https://stackoverflow.com/questions/9645188/how-can-i-create-byte-values-from-integers-in-python

http://stackoverflow.com/comment/80578437
has text: I see the same behavior. You should use `C-c C-d`/`M-x comint-send-eof` to send EOT instead of `C-q C-d`, but that doesn't work either. ghci is clearly getting EOT, but isn't interpreting it correctly. One difference is that TERM=dumb in shell-mode, but running `TERM=dumb ghci` still honors EOT in a normal terminal. It might have something to do with this: https://ghc.haskell.org/trac/ghc/ticket/3256.
comment on: http://stackoverflow.com/q/46782528
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46780367
tagged with: python
has title: Variable width barplot with seaborn
has answer: http://stackoverflow.com/a/46796963
upvote count: 3
has body: I am trying to create a bar plot with variable width x-axis bins in Seaborn. Similar to this chart: All of my x widths will add up to 100%, but I can't seem to find an example of how to accomplish this goal via Seaborn. Any ideas?
has comment: http://stackoverflow.com/comment/80545367
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46802028
linked to: http://stackoverflow.com/q/36824229
score: 3
downvote count: 0
duplicate of: http://stackoverflow.com/q/36824229
favorite count: 0
type: Question
tagged with: seaborn
answer count: 2

http://stackoverflow.com/a/46804289
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46801543
has body: Here's my minimalist approach to this problem (well, not totally, I did throw in a couple of niceties): from turtle import Turtle, Screen FONT_SIZE = 24 FONT = ('Arial', FONT_SIZE, 'normal') def turtle_drag(turtle, other, x, y): turtle.ondrag(None) # disable event hander in event hander turtle.goto(x, y) display.undo() # erase previous distance distance = turtle.distance(other) display.write('Distance: {:.1f}'.format(distance), align='center', font=FONT) turtle.setheading(turtle.towards(other)) # make them always look other.setheading(other.towards(turtle)) # lovingly at each other turtle.ondrag(lambda x, y: turtle_drag(turtle, other, x, y)) # reenable screen = Screen() screen.setup(500, 500) display = Turtle(visible=False) display.penup() display.goto(0, screen.window_height() / 2 - FONT_SIZE * 2) display.write('', align='center', font=FONT) # garbage for initial .undo() Alex = Turtle('turtle') Alex.speed('fastest') Alex.color('blue') Alex.penup() Alice = Turtle('turtle') Alice.speed('fastest') Alice.color('red') Alice.penup() turtle_drag(Alex, Alice, -50, -50) # initialize position and event hander turtle_drag(Alice, Alex, 50, 50) screen.mainloop() As you drag Alex or Alice, their center to center distance at the top of the screen updates. This uses a separate, invisible, stationary turtle handling the display who does .undo() to erase a previous value and .write() to display a new one. Making the turtles turn towards each other after the distance display is updated ensures they don't get trapped underneath the invisible display turtle (i.e. undragable) so they can even be postitioned atop the text:

http://stackoverflow.com/q/46865565
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
has body: This is perhaps a micro-optimization, but I would like to check that a stream of given bytes is valid UTF-8 as it passes through my application, but I don't want to keep the resulted decoded code points. In other words, if I were to call large_string.decode('utf-8'), assuming the encoding succeeds I have no desire to keep the unicode string returned by decoding, and would prefer not to waste memory on it. There are various ways I could do this, for example read a few bytes at a time, attempt to decode(), then append more bytes until decode() succeeds (or I've exhausted the maximum number of bytes for a single character in the encoding). But ISTM it should be possible to use the existing decoder in a way that simply throws away the decoded unicode characters and not have to roll my own. But nothing immediately comes to mind scouring the stdlib docs.
has answer: http://stackoverflow.com/a/46865661
tagged with: character-encoding
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80679360
accepted answer: http://stackoverflow.com/a/46865661
has title: Validate that a stream of bytes is valid UTF-8 (or other encoding) without copy

http://stackoverflow.com/q/46831625
has comment: http://stackoverflow.com/comment/80610800
has comment: http://stackoverflow.com/comment/80610793
has answer: http://stackoverflow.com/a/46832046
has comment: http://stackoverflow.com/comment/80610933
score: 0
has answer: http://stackoverflow.com/a/46831888
has answer: http://stackoverflow.com/a/46831803
has comment: http://stackoverflow.com/comment/80611208
has comment: http://stackoverflow.com/comment/80610929
has comment: http://stackoverflow.com/comment/80611363
possible better answer: http://stackoverflow.com/a/46831803
has body: For some reason a dictionary I am producing from a list doesnt seem to be adding a new key pair each time but instead just overwritting the same pair. Im pretty sure it probably obvious to many whats wrong here but Im just not seeing it, any help pointed would be appreciated. Below is the data and code snippets forest_root = 'domain4.co.uk' domains = ['domain:domain1.co.uk', 'domain:domain2.co.uk', 'domain:domain3.co.uk', 'domain:domain4.co.uk'] dict1 = {forest_root: [dict(domain.split(":", 1) for domain in domains)] } print dict1 OUTPUT {"domain4.co.uk": [{"domain": "domain4.co.uk"}]} Expected OutPut {"domain4.co.uk": [ "domain": "domain4.co.uk", "domain": "domain1.co.uk", "domain": "domain2.co.uk", "domain": "domain3.co.uk", ] } Post Answer Thanks all, I can now see what I was doing wrong and understand how to achieve my expected outcome.
has comment: http://stackoverflow.com/comment/80610688
tagged with: python
tagged with: dictionary
answer count: 4
has comment: http://stackoverflow.com/comment/80610891
has comment: http://stackoverflow.com/comment/80611075
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80610797
has answer: http://stackoverflow.com/a/46831850
accepted answer: http://stackoverflow.com/a/46831850
has comment: http://stackoverflow.com/comment/80610738
has title: Python dictionary creation through comprehension
has comment: http://stackoverflow.com/comment/80610843
type: Question
has comment: http://stackoverflow.com/comment/80611304
has comment: http://stackoverflow.com/comment/80611036

visualization
tags question: http://stackoverflow.com/q/46890266
tag name: visualization
tags question: http://stackoverflow.com/q/46844654
tags question: http://stackoverflow.com/q/46772282
type: Tag
tags question: http://stackoverflow.com/q/46859431
tags question: http://stackoverflow.com/q/46796795
tags question: http://stackoverflow.com/q/46831371
tags question: http://stackoverflow.com/q/46841795
tags question: http://stackoverflow.com/q/46750152

http://stackoverflow.com/a/50776854
answers question: http://stackoverflow.com/q/46862722
has body: Try this with recent versions of tensorflow: from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import LSTM, TimeDistributed, Dense, ...
score: 2
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/q/46865865
has title: Merging 3 databases with same names, and renaming them in python
type: Question
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/46866058
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/46866058
tagged with: python
tagged with: merge
has body: I have 3 df with 25 columns each. All the columns are same in the 3 df. I want to merge the 3 df, and change the column name to "_a" for 25 columns of df1, change to "_b" for 25 columns of df2, and change to "_c" for 25 columns of df3. I am using the below code: pd.merge(pd.merge(df1,df2,'left',on='year',suffixes=['_a','_b']),df3,'left',on='year') How do I use a rename or some other function, to change all the 25 columns of df3 in the code above? Thanks.
type: AnsweredQuestion
score: 2
tagged with: rename

http://stackoverflow.com/a/46903478
downvote count: 0
has comment: http://stackoverflow.com/comment/81110405
has body: You could use conditional_probability_alive method from lifetimes package. You need to pass frequency, recency, and T for each customer. For example for BetaGeoFitter (BG/NBD model): from lifetimes import BetaGeoFitter from lifetimes.datasets import load_cdnow_summary # load data data = load_cdnow_summary(index_col=[0]) print(data.head()) # fit lifetimes model bgf = BetaGeoFitter(penalizer_coef=0.0) bgf.fit(data['frequency'], data['recency'], data['T']) print(bgf) # predict p_alives for customers p_alive1 = bgf.conditional_probability_alive(2, 30.43, 38.86) p_alive2 = bgf.conditional_probability_alive(1, 30, 30) print(p_alive1, p_alive2) Output: frequency recency T ID 1 2 30.43 38.86 2 1 1.71 38.86 3 0 0.00 38.86 4 0 0.00 38.86 5 0 0.00 38.86 &lt;lifetimes.BetaGeoFitter: fitted with 2357 subjects, a: 0.79, alpha: 4.41, b: 2.43, r: 0.24&gt; 0.7266084620654866 0.753658243186767
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46857571
score: 1

http://stackoverflow.com/comment/80754298
score: 0
type: AnswerComment
type: Comment
has text: just increase rectangles (x,y,w,h), if you increase w and h it will be bigger but the corner (top left) in the same position if you decrease x and y and increase w and h the ellipse/rectangle will be bigger
comment on: http://stackoverflow.com/a/46886742

http://stackoverflow.com/q/46885861
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46917480
downvote count: 5
type: Question
tagged with: minidom
has body: I am getting the below error while running this script ("from xml.dom import minidom") from chaquopy androi application python console. PyException: ImportError: No module named domreg
tagged with: chaquopy
answer count: 1
score: -4
favorite count: 0
tagged with: android
has title: PyException: ImportError: No module named domreg
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion

http://stackoverflow.com/comment/95930281
type: AnswerComment
type: Comment
score: 1
has text: @vinitkantrod, it is not in the scope of this question. It will be better if you can create a new question regarding S3 bucket image usage in Flask. I think future readers will be benefited.
comment on: http://stackoverflow.com/a/46794505

neural-network
tags question: http://stackoverflow.com/q/46825257
tags question: http://stackoverflow.com/q/46750772
tags question: http://stackoverflow.com/q/46866208
tags question: http://stackoverflow.com/q/46871302
tags question: http://stackoverflow.com/q/46903528
tags question: http://stackoverflow.com/q/46806127
tags question: http://stackoverflow.com/q/46899457
tags question: http://stackoverflow.com/q/46750355
tags question: http://stackoverflow.com/q/46886770
tags question: http://stackoverflow.com/q/46840539
tags question: http://stackoverflow.com/q/46814984
tags question: http://stackoverflow.com/q/46819731
tags question: http://stackoverflow.com/q/46872718
tags question: http://stackoverflow.com/q/46808842
tags question: http://stackoverflow.com/q/46800774
tags question: http://stackoverflow.com/q/46803186
tags question: http://stackoverflow.com/q/46806112
tags question: http://stackoverflow.com/q/46785169
tags question: http://stackoverflow.com/q/46842321
tags question: http://stackoverflow.com/q/46799667
tags question: http://stackoverflow.com/q/46835602
tags question: http://stackoverflow.com/q/46832151
tags question: http://stackoverflow.com/q/46846081
tags question: http://stackoverflow.com/q/46804151
tags question: http://stackoverflow.com/q/46777793
tags question: http://stackoverflow.com/q/46861199
tags question: http://stackoverflow.com/q/46897088
tags question: http://stackoverflow.com/q/46840037
tags question: http://stackoverflow.com/q/46822207
type: Tag
tags question: http://stackoverflow.com/q/46894615
tags question: http://stackoverflow.com/q/46834680
tags question: http://stackoverflow.com/q/46790654
tags question: http://stackoverflow.com/q/46770457
tags question: http://stackoverflow.com/q/46802409
tags question: http://stackoverflow.com/q/46759500
tags question: http://stackoverflow.com/q/46805647
tags question: http://stackoverflow.com/q/46876213
tag name: neural-network
tags question: http://stackoverflow.com/q/46878201
tags question: http://stackoverflow.com/q/46818376
tags question: http://stackoverflow.com/q/46807597
tags question: http://stackoverflow.com/q/46890266

http://stackoverflow.com/comment/80562927
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46806820
type: Comment
has text: Thank you very much if you could do something like that, it would be awesome. Looking online, quite some people are looking for this kind of example!

http://stackoverflow.com/comment/80546946
has text: Which package it is and how did you installed it?
type: Comment
comment on: http://stackoverflow.com/q/46797922
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80625994
has text: The error you see is because you are trying to search for the pattern in the inner list. re.search only works when you search for pattern in a string.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46839014

http://stackoverflow.com/comment/80688914
has text: a class with a persons Id, weigh, height, age, and meters walked
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46870718

http://stackoverflow.com/comment/80617828
comment on: http://stackoverflow.com/q/46791359
score: 0
type: Comment
type: QuestionComment
has text: ...wait, you're passing a single tuple to amap, not a list of tuples. That seems completely wrong; something with `map` in the name should take an iterable to map the function over, not a single argument tuple.

http://stackoverflow.com/comment/80689184
has text: Awesome super sir. you can also add the groupby method na. Op wants that for multiple test cases
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46870945

http://stackoverflow.com/a/46878360
score: 2
has comment: http://stackoverflow.com/comment/80704624
has body: Your default login shell is bash. subprocess.Popen, though, uses the system default shell /bin/sh, which does not recognize the &amp;&gt; operator. If you want to force it to use bash, use the executable option: a = subprocess.Popen("sleep 5 &amp;&gt; a.txt", shell=True, executable="/bin/bash") Alternatively, you can handle the redirection yourself in Python: with open("a.txt", "w") as fh: a = subprocess.Popen(["sleep", "5"], stdout=fh, stderr=fh)
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/80704354
answers question: http://stackoverflow.com/q/46878275
has comment: http://stackoverflow.com/comment/80704110
type: Answer
has comment: http://stackoverflow.com/comment/80705115

http://stackoverflow.com/comment/80501529
has text: I can also read stdout, but I am not sure if I'm reading it correctly. since readline() will not work because input() example do not send line break. I can read(size) but I don't know that is the "size" I need to read. assuming I don't really know the size of "input()" string size.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46750620
score: 0

http://stackoverflow.com/a/46866526
has comment: http://stackoverflow.com/comment/80793348
upvote count: 2
has comment: http://stackoverflow.com/comment/81078534
has comment: http://stackoverflow.com/comment/81120646
answers question: http://stackoverflow.com/q/46866387
has comment: http://stackoverflow.com/comment/81120994
downvote count: 0
has comment: http://stackoverflow.com/comment/80877067
has comment: http://stackoverflow.com/comment/80682021
has comment: http://stackoverflow.com/comment/81027300
has comment: http://stackoverflow.com/comment/81040926
type: Answer
has body: Change def newwin(): win=Tk() ... to def newwin(): win=Toplevel(root) ... Edit (clarification): Your code would also run if you change def newwin(): win=Tk() s=StringVar() ... to def newwin(): win=Tk() s=StringVar(win) ... but you shouldn't run multiple Tk() instances. See a good explanation here Edit: As for restricting selection of old window as asked by OP in a comment, I suggested to add a line to newwin(): def newwin(): win=Tk(Toplevel(root)) s=StringVar() button=Button(win,text='click',command=lambda:get(s)).grid(row=1) ent=Entry(win,textvariable=s).grid() win.grab_set() # win will catch all events, until you close it # so user cannot interact with root window widgets # root.widthdraw() # alternative approach hides root window # until Toplevel closes root=Tk() but=Button(root,text='New',command=newwin).grid() Edit: (further enhancement with code rewrite. I think I already answered the OP question but the comments with additional questions can be confusing. Please try to ask a single question at a time in order for you to select the best answer for that question) Now I just rewrote the thing to look like a more coehrent answer. Look that using grid or pack is not relevant here. I hope you find it educational. Notice the different imports. You can import differently, but this way you do not import all the tkinter module names. ttk widgets are just modern versions of the classic ones. I subclassed Toplevel, assured parent __init__ is called and kept the new window related things together in that class. Note also the use of grab_set and the event callback for when the child toplevel loses focus. This way root window never regains focus unless you close the child. So no window select. This is adapted from selected answer here Note also that I do not keep any reference to the newly created window. If you need so, you have to adapt (maybe store the result of MyWinddow(root) in a global var) import tkinter as tk from tkinter import Tk, ttk class MyWindow(tk.Toplevel):…
has comment: http://stackoverflow.com/comment/81027545
has comment: http://stackoverflow.com/comment/81041005
has comment: http://stackoverflow.com/comment/81030098
score: 2

http://stackoverflow.com/comment/80447689
type: Comment
has text: Thanks for the tips. They answer a lot of questions that were in my head concerning why the game kept running through every difficulty.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46750867

http://stackoverflow.com/q/46794890
type: AnsweredQuestion
tagged with: pydot
has title: Drawing graphs in python - pydotplus error
tagged with: networkx
type: Question
has body: I am lost in all the python libraries for drawing graphs. I wish I knew one that is flexible and with documentation... I have spent substantial time playing with networkx to find out that it is not as good for my task (e.g. overlapping labels for bigger graphs). Now, I am trying to use pydot or pydotplus, but there is no documentation, no reasonable examples out there. Or am I missing something? Pydotplus website provides a reference, but that is not entirely helpful for a beginner. Now, I am able to draw a graph with pydotplus, but I want to change the node positions (Fruchterman-Reingold algorithm) and especially use colors and sizes with nodes, but I have no idea how. Sample code: import pydotplus as ptp graph = ptp.Dot(graph_type='graph') edges = [(1,2), (1,3), (2,4), (2,5), (3,5)] nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")] for e in edges: graph.add_edge(ptp.Edge(e[0], e[1])) for n in nodes: node = ptp.Node(name=n[0], attrs={'label': n[1], 'fillcolor': n[2]} ) graph.add_node(node) graph.write_png("file.png") This throws an exception: InvocationException: Program terminated with status: 1. stderr follows: Error: /tmp/tmpznciMx: syntax error in line 7 near '{'
tagged with: graphviz
has comment: http://stackoverflow.com/comment/80536736
score: 0
accepted answer: http://stackoverflow.com/a/46795569
has comment: http://stackoverflow.com/comment/80536816
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46795569
tagged with: python

http://stackoverflow.com/comment/80727101
score: 0
type: Comment
has text: you probably serialized a string, not a dict. So `json.loads` returns a string
type: QuestionComment
comment on: http://stackoverflow.com/q/46889849

http://stackoverflow.com/comment/80689500
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46870841
has text: What is the wrong output? Provide example input, desired output, and actual output - it's hard to help without seeing exactly what the problem is.

http://stackoverflow.com/comment/80718195
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46884428
has text: what dose it mean that row=2 path=2 result=2 ?
type: Comment

http://stackoverflow.com/q/46783230
has body: I have a checkbox in Manufacturing module-> Products form (Named "Raw Materials") If I select the checkbox and save the data it should not get saved in the products form but else it should be saved in a separate menu called Raw materials which I created manually in Manufacturing module. How to achieve this in Odoo v10? This is my xml file...... raw.form.inherit.button product.template product.template.search product.template <separator/> <filter string="Raw Materials" name="filter_to_raw" domain="[('raw','=',True)]"/> <separator/> Raw Materials ir.actions.act_window product.template kanban,tree,form form {"search_default_filter_to_raw":1} Click to define a new product. You must define a product for everything you sell, whether it's a physical product, a consumable or a service you offer to customers. The product form contains information to simplify the Raw Materials: price, notes in the quotation, accounting data, procurement methods, etc. <menuitem id="menu_mrp_product_form" name="Raw Materials" action="mrp.product_template_action" parent="mrp.menu_mrp_bom" sequence="8"/> Thanks in advance
type: Question
tagged with: odoo
has answer: http://stackoverflow.com/a/46786612
has comment: http://stackoverflow.com/comment/80513116
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80515024
favorite count: 0
has answer: http://stackoverflow.com/a/46845702
has answer: http://stackoverflow.com/a/46783571
has title: Filtering data from one menu to another menu
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 2
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/46776026
has answer: http://stackoverflow.com/a/69985434
type: Question
score: 0
tagged with: mongodb
possible better answer: http://stackoverflow.com/a/46778881
has answer: http://stackoverflow.com/a/46778881
has answer: http://stackoverflow.com/a/46788512
has body: I have few documents stored in MongoDB, where one of the fields has the below format: Document Field {field1:{inner_field1:inner_value1, inner_field2:inner_value2, inner_field3:inner_value3}} I know that to query documents based on inner_value1, I need to use the dot notation in Mongo query like below: {field1.innerfield1:inner_value1} In my case, the fields on which I need to search the documents from MongoDB will be provided by an external party and they may or may not be nested. In this scenario, how can I dynamically create "dot notation" based query if I have the original field as mentioned as in "Document Field" above? The original field value may or may not be nested.
answer count: 3
tagged with: python
has title: How to create a dot notation based PyMongo Query dynamically?
accepted answer: http://stackoverflow.com/a/46788512
tagged with: pymongo
type: AnsweredQuestion

http://stackoverflow.com/q/46860663
upvote count: 1
has answer: http://stackoverflow.com/a/46865962
answer count: 1
tagged with: http
has comment: http://stackoverflow.com/comment/80681369
has title: Multithread Socket in Python, Message Error UniUnicodeDecodeError
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80680921
downvote count: 0
accepted answer: http://stackoverflow.com/a/46865962
has comment: http://stackoverflow.com/comment/80679534
has body: UniUnicodeDecodeError (While Sending Message to Client) I'm implementing a server/client socket in python, and the following code sometimes raise the UniUnicodeDecodeError exception. I don't know why sometimes works and sometimes not. Please help... Server conn.sendall('200 OK'.encode('utf-8')) while l: self.conn.sendall(l) l = f.read(BUFFER_SIZE) if not l: f.close() self.conn.close() break Client HTTP_RCV_CODE = tcp_sock.recv(BUFFER_SIZE) HTTP_RCV_CODE = HTTP_RCV_CODE.decode('utf-8') When Works Server answer: 200 OK Connection close. UniUnicodeDecodeError Traceback (most recent call last): File "navegador.py", line 40, in HTTP_RCV_CODE = HTTP_RCV_CODE.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9b in position 49: invalid start byte [Solution] Just adding a time delay solve my problem, apparently the server was sending the 200 OK message and some parts of the file together. Server conn.sendall('200 OK'.encode('utf-8')) time.sleep(0.1) while l: self.conn.sendall(l) l = f.read(BUFFER_SIZE) if not l: f.close() self.conn.close() break
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80679491
type: Question
tagged with: sockets
tagged with: multithreading
has comment: http://stackoverflow.com/comment/80679374
tagged with: python
tagged with: tcp

http://stackoverflow.com/comment/80574061
comment on: http://stackoverflow.com/a/46807741
has text: And I just gather enough points to be able to vote answers now, which is soooo cooool!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80564286
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46808459
has text: @Abhijit why? For just two processes exchanging byte streams, simple pipes do the job perfectly well.
type: Comment

http://stackoverflow.com/comment/80746976
comment on: http://stackoverflow.com/q/46899900
has text: Your while loop isn't breaking anywhere.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/80745897
type: AnswerComment
comment on: http://stackoverflow.com/a/46897107
type: Comment
has text: @SRD1707 It is just the syntax alias for the context manager. Think of it as a sentence that reads `"With the file opened with the nickname of F, do the following with F"`. Thus we can do things like `f.read()` and `f.write()`.
score: 0

http://stackoverflow.com/q/46800142
tagged with: pywin32
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47260654
has body: I'm trying to use the win32job API that is part of the PyWin32 package. I want to do this: win32job.CreateJobObject(None, NULL) I want to pass NULL as the second parameter as documented here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682409(v=vs.85).aspx If lpName is NULL, the job is created without a name. How do I pass in NULL? Here's what I hoped would work, but doesn't: win32job.CreateJobObject(None, None) Error: TypeError: None is not a valid string in this context (Side question... if anyone knows how to view JobObjects associated with a process in Windows, that would be helpful.)
upvote count: 2
has comment: http://stackoverflow.com/comment/80547157
type: Question
accepted answer: http://stackoverflow.com/a/47260654
answer count: 1
tagged with: window
downvote count: 0
favorite count: 0
has title: In python with pywin32, win32job, the CreateJobObject function, how do I pass NULL for the name parameter?

http://stackoverflow.com/comment/80590639
has text: Thaks for your contribuition Timofey.
comment on: http://stackoverflow.com/a/46802226
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80543863
comment on: http://stackoverflow.com/q/46798448
score: 0
has text: And what do you see if you `print(os.listdir("C:\Users\Tory\Desktop\Delete_Test"))`? Is it a list of absolute paths?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46784055
downvote count: 0
type: Answer
upvote count: 3
has body: You can use more-itertools' sliced() to slice the string into equal chunks: &gt;&gt;&gt; import more_itertools &gt;&gt;&gt; a1 = '1234567891122334455667788' &gt;&gt;&gt; list(more_itertools.sliced(a1, 3)) ['123', '456', '789', '112', '233', '445', '566', '778', '8']
has comment: http://stackoverflow.com/comment/80514561
score: 3
answers question: http://stackoverflow.com/q/46783975

http://stackoverflow.com/comment/80572214
has text: How will the filename.csv first row look like when you wrote the row you just posted? The desired output not the actual output.
comment on: http://stackoverflow.com/q/46811986
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/46793190
has body: I just started using Sklearn (MLPRegressor) and Keras (Sequential, with Dense layers). Today I read this paper describing how using cosine similarity instead of the dot product improves the performance. This basically says that if we replace f(w^Tx) with f((w^Tx)/(|x||w|)), i.e. we don't just feed the dot product to the activation function but we normalize it, we get a better and quicker performance. Is there a way of doing this in Python, specifically in MLPRegressor in SKlearn (or another), or in Keras? (maybe TensorFlow?)
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/46794353
score: 2
downvote count: 0
has title: Is there a way of using cosine similarity instead of dot product in python (sklearn/keras)
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80563681
answer count: 1
tagged with: deep-learning
linked to: http://stackoverflow.com/q/43357732
favorite count: 0

http://stackoverflow.com/comment/80512035
type: AnswerComment
type: Comment
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156874/discussion-between-vinayak-kaniyarakkal-and-dirtysocks45).
comment on: http://stackoverflow.com/a/46771657

http://stackoverflow.com/q/46757725
has comment: http://stackoverflow.com/comment/80461602
tagged with: django
tagged with: django-crispy-forms
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46757887
accepted answer: http://stackoverflow.com/a/46757887
has comment: http://stackoverflow.com/comment/80461007
has comment: http://stackoverflow.com/comment/80461533
type: Question
tagged with: forms
has body: I have built a crispy form from a tutorial (https://godjango.com/29-crispy-forms/) and am getting an error that I believe means I need to define a URL in the urls.py. I also get the sense that there may be more than one issue going on - I am still trying to make this work and will continue to research it but I am quite new to Django and Python so struggling on this. Any guidance gratefully received. Here's the error: Failed lookup for key [form] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'view': &lt;django.views.generic.base.TemplateView object at 0x10faa03c8&gt;, 'home_url': '/'}]" For reference here are the files: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions) class SimpleForm(forms.Form): username = forms.CharField(label="Username", required=True) password = forms.CharField( label="Password", required=True, widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember Me?") helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('login', 'login', css_class='btn-primary')) class CartForm(forms.Form): item = forms.CharField() quantity = forms.IntegerField(label="Qty") price = forms.DecimalField() helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( 'item', PrependedText('quantity', '#'), PrependedAppendedText('price', '$', '.00'), FormActions(Submit('login', 'login', css_class='btn-primary')) ) class CreditCardForm(forms.Form): fullname = forms.CharField(label="Full Name", required=True) card_number = forms.CharField(label="Card", required=True, max_length=16) expire = forms.DateField(label="Expire Date", input_formats=['%m/%y']) ccv = forms.IntegerField(label="ccv") notes = forms.CharField(label="Order Notes", widget=forms.Textarea()) helper = FormHelper() helper.form_method = 'POST' helper.form_class = 'form-horizontal' helper.…
upvote count: 1
answer count: 1
tagged with: cookiecutter-django
favorite count: 0
has title: Django crispy forms - creating a form in home.html and getting an error

http://stackoverflow.com/comment/80757130
has text: Use `SSH` , don't waste your time !
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46905201
score: 1

http://stackoverflow.com/comment/80449423
comment on: http://stackoverflow.com/q/46750954
score: 0
has text: Finally the Cobol is invalid, DIGIT-TAB2 redefines DIGIT-TAB1 which does not exist
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80664809
comment on: http://stackoverflow.com/a/46858494
has text: Why not just `thread.join(timeout)` instead of the while-loop?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/46815970
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46815807
has body: You're using the _str attribute on paths, which is undocumented and not guaranteed to be set. In general, an underscore prefix indicates that this is a private attribute that should not be used by user code. If you want to convert a path to a string, just use str(the_path) instead. But in this case, you don't need to do so: Path objects have an is_file method which you can call instead. Another possibility is to pass the Path object itself to the os.path.isfile function, which is supported on Python 3.6.
accepted answer of: http://stackoverflow.com/q/46815807
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80579256

http://stackoverflow.com/q/46792348
type: Question
tagged with: python
has title: How to retrieve user.uid data from Firebase in python
has comment: http://stackoverflow.com/comment/80531455
score: 0
tagged with: firebase-realtime-database
has body: I have some doubts about Firebase in python (Pyrebase Library). The first doubt is if I can retrieve the data of the user.uid from firebase in python script because my database const of this users/+user.uid+/.../. And the other doubt is if I can listen to child live changes in Pyrebase, I know that it has the streaming method, but I don't know if I can obtain the path and the data of the exact child which change. Thank you for help.
tagged with: firebase
tagged with: firebase-authentication
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80548092
answer count: 0
tagged with: python-2.7

linefeed
tags question: http://stackoverflow.com/q/46900610
tag name: linefeed
type: Tag

http://stackoverflow.com/comment/80476615
type: Comment
comment on: http://stackoverflow.com/a/46757690
type: AnswerComment
has text: @WinterZ As I said in my comment earlier - [`Produce a sample with minimal representative data?`](https://stackoverflow.com/questions/46757318/python-generate-rolling-window-to-calculate-correlation/46757690?noredirect=1#comment80460007_46757318).
score: 0

http://stackoverflow.com/a/46806105
type: Answer
accepted answer of: http://stackoverflow.com/q/46804725
has body: I have resolved this issue. It was created by my trying to juggle different Python 2 and 3 versions and multiple trial virtual environments. I had ended up with an old user-specific anaconda installation and a new anaconda root for all users. The discovery was made by finding that import sys sys.path gave different reports when I ran these from Python shell and from inside the notebook. I cleared the user-specific anaconda installation, re-installed the latest anaconda version, added the relevant packages, and installed parallel ipython kernels (as described here). The issue is resolved and serves as a lesson in the importance of keeping the root python install clean and properly using virtual environments.
answers question: http://stackoverflow.com/q/46804725
type: AcceptedAnswer
score: 0

game-loop
tag name: game-loop
tags question: http://stackoverflow.com/q/46752145
type: Tag

http://stackoverflow.com/a/46868669
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: The inplace=True argument modifies the data frame in place, meaning it won't return anything as a result of the operation. You can either: - Return the .rename() without inplace=True, or - Don't return anything and use the pass-by-reference property to make the update.
answers question: http://stackoverflow.com/q/46868447

http://stackoverflow.com/comment/111617606
comment on: http://stackoverflow.com/a/46862429
score: 0
type: Comment
has text: Hi, what if I want to know the count of each element in a list, as the results would be: [2, 2, 0]
type: AnswerComment

http://stackoverflow.com/comment/80510731
has text: I believe I get it a bit now. By doing 'board = []', I'm creating a new object called 'board', and any modification done is made to this newly created object.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46782135
type: Comment

http://stackoverflow.com/a/46765770
answers question: http://stackoverflow.com/q/46753436
has body: As soon as you are working with tables (csv being one) think pandas (my opinion). In this case we can use pandas json_normalize to interpret your json file. import json from pandas.io.json import json_normalize with open("Sclass.json.json") as f: df = json_normalize(json.load(f)) cols = ["id","timestamp_ms","user.name", "user.statuses_count","user.friends_count","user.followers_count", "place.bounding_box.coordinates","text"] df[cols].to_csv("Hasil_Tweets.csv",sep=",",index=False) # outputs to csv Pandas come with many output options, one of them being a html table. I will use this to show the outut: print(df[cols].to_html(index=False)) # outputs to html to show result Output id timestamp_ms user.name user.statuses_count user.friends_count user.followers_count place.bounding_box.coordinates text 918032510927355904 1507710981481 Mutiara Sisyanni D 6507 237 354 [[[106.817351, -6.24152], [106.817351, -6.2011... @irfanzayo @puisisi @tasyak Lo tuh kebiasaan o...
has comment: http://stackoverflow.com/comment/80670980
has comment: http://stackoverflow.com/comment/80671673
type: Answer
has comment: http://stackoverflow.com/comment/80673534
score: 0

http://stackoverflow.com/q/46880865
downvote count: 3
answer count: 1
tagged with: ip
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/47109998
tagged with: cisco
upvote count: 0
has title: Using Python for Cisco network admin
favorite count: 0
type: Question
tagged with: python
has body: I started learning Python and I am trying to find a usage in networking and writing scripts. My question is more of a newbie in dev. I'm learning how to access SSH with Paramiko, then collect info from a device, manipulate data, and push some commands. Is there any ideas or ways of what can be done and/or automated using Python?

http://stackoverflow.com/q/46792638
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46804506
type: Question
has title: Load an In Memory ZipFile Object to as a KivyImage
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/46804506
score: 1
tagged with: python-zipfile
favorite count: 0
has body: I am testing out the ability of loading a zipfile containing multiple images to a kivy image and proofing out that it will cycle through all the images. I have previously tried out these examples: https://groups.google.com/forum/#!topic/kivy-users/t_iKvpgLIzE https://kivy.org/docs/api-kivy.core.image.html I can get these to work, however, I cannot find an example of loading a .zip file or .gif file under those circumstances. I request to see if it is possible to load a zipfile containing images if the zipfile is located in memory. Or if it's possible to create the animation from images loaded from memory. import io import zipfile from kivy.core.image import Image as CoreImage from kivy.uix.image import Image from kivy.app import App from kivy.uix.boxlayout import BoxLayout class testApp(App): def get_image_from_memory(self): with io.BytesIO(open("archer_F_idle.zip", "rb").read()) as f: imgzip = f.read() print(imgzip) zipped_imgs = zipfile.ZipFile(f) print(zipped_imgs, zipped_imgs.namelist(),zipped_imgs.filename) return Image(source=zipped_imgs) def build(self): self.b = BoxLayout() self.b.add_widget(self.get_image_from_memory()) return self.b if __name__ == '__main__': testApp().run() Here is the following error: ValueError: Image.source accept only str
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/46819035
has comment: http://stackoverflow.com/comment/80586328
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80587065
has comment: http://stackoverflow.com/comment/80587785
tagged with: dataframe
has title: Python - Add comment and a column to txt (tsv) file
type: Question
has comment: http://stackoverflow.com/comment/80585697
score: 0
has body: There is a txt file (tap separated) with comments like: [header] This file is generated by Bingbong Kim user name : user user gender : male user age : 45 [data] user_item color price item1 red 10 item2 black 20 item3 green 10 item4 blue 15 I would like to add one more comment(#user country) and insert a new column that all values are same like: [header] This file is generated by Bingbong Kim user name : user user gender : male user age : 45 user country : US [data] user_item color price check item1 red 10 true item2 black 20 true item3 green 10 true item4 blue 15 true Now I did : import pandas as pd # save the comments in a list header_list = [] temp_report = open('report.txt') for i, line in enumerate(temp_report): header_list.append(line) if i == 7: temp_report.close() break # create a dataframe without the comments report = pd.read_csv('report.txt', skiprows=6, sep='\t') # insert a column to the dataframe report['check'] = "true" #all values are same # write the comment first and then write the changed dataframe f = open('new_report.txt', 'a') for comment in header_list: f.write(comment) report.to_csv(f, sep='\t', index=False) f.close() I think there seems to be another good way. It takes about 50 second per a txt file because the txt file is too big. How can I improve it?

http://stackoverflow.com/comment/80495152
has text: You beat me to it... I don't think the first bit will work because you can't `get_attribute()` on an invisible element using Selenium. I was going to suggest that he use JSE, e.g. `.execute_script("return arguments[0].innerText", name)` in your case.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46774501

http://stackoverflow.com/a/46833366
answers question: http://stackoverflow.com/q/46831933
score: 0
type: Answer
has body: You need to pass the x and y values for the entire line when you call plt.plot(). Therefore, one possible (though quite messy) way of doing it is to append the values to a list, plot the line, then clear the list. fig = plt.figure(figsize = (12, 6)) ax = plt.subplot(111) x = list(range(10, 101, 10)) y = list(range(20, 150, 13)) for i in range(0,10): if i != 0: ax.plot(x_list, z_list) z_list = [] x_list = [] for j in range(0,10): z = x[i] + y[j] z_list.append(z) x_list.append(y[j]) plt.show() Which produces the following figure:
accepted answer of: http://stackoverflow.com/q/46831933
type: AcceptedAnswer

http://stackoverflow.com/comment/80657869
type: Comment
score: 0
has text: Please clean up your code a bit. Some of it is malformed (missing indentation, etc.)
type: QuestionComment
comment on: http://stackoverflow.com/q/46855180

http://stackoverflow.com/q/46876426
type: Question
tagged with: filtering
has comment: http://stackoverflow.com/comment/80699890
has answer: http://stackoverflow.com/a/46877877
tagged with: dataframe
has title: Filter by monthday Pandas Dataframe
has comment: http://stackoverflow.com/comment/80699853
score: 0
tagged with: filter
has comment: http://stackoverflow.com/comment/80700294
tagged with: pandas
has comment: http://stackoverflow.com/comment/80700283
answer count: 1
has comment: http://stackoverflow.com/comment/80699866
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80699742
has body: I would like to filter a pandas dataframe between months for a number of years. I have a dataframe with data from 2000-2016, and I want to filter between October 22nd and November 15th for each of the years. To keep this simple let's say I have 4 columns. The date index, the month index, the day index, and price. What I have attempted so far is to concatenate the month column and the day column. Ie. October 22 becomes 1022 and November 15th becomes 1115. The problem arises when I look at dates before #10. Ie. November first is 111 rather that 1101. So when I do a conditional filter specifying df['monthday'] > 1015 &amp; df['monthday'] &lt; 1115 it entirely fails to capture all the November dates from November first to November 9th because 111 through to 119 &lt; 1015. I have also tried to compare this number as a string, so I have succesfully converted 111 to str(1101). But then this is not comparable to int(1101). This is a seemingly easy problem that I have had no luck solving. Any help is appreciated. Code snippets below. Thank you, df = web.DataReader('SPY', 'yahoo',datetime.datetime(2015 ,1, 1), datetime.datetime.today()) #this adds zeroes but really doesn't help me df['Day of Month'] = df['Day of Month'].astype(str).str.zfill(2) df['month'] = df['month'].astype(str).str.zfill(2) #This one converts it to str but can't compare str to int df['monthday'] = df['month'].map(str) + df['Day of Month'].map(str) #This one converts it to a # but can't use 111 as November 1st because it is #smaller than 1015 ie October 15th and I want to filter between those dates. df['monthday'] = pd.to_numeric(df.monthday, errors='coerce') #here is where I attempt my intermonth filter for each year since 2000 df = df[(df['month'] &gt;= 10) &amp; (df['month'] &lt;= 11) &amp; (df['monthday'] &gt;= 1021) &amp; (df['monthday'] &lt;=1115)] Thank you for your support.
tagged with: python
has comment: http://stackoverflow.com/comment/80699789
has comment: http://stackoverflow.com/comment/80699922

http://stackoverflow.com/comment/81763318
type: AnswerComment
has text: xie xie a lot,it is a late prefect answer , im a newer in python ,so i use a unskillful method solved this by follow jdk source code,this part of my code def long7(x): b= struct.pack('>I', x >> 56) return b[len(b)-1] def long6(x): b= struct.pack('>I', x >> 48) return b[len(b)-1]
type: Comment
comment on: http://stackoverflow.com/a/47399380
score: 1

http://stackoverflow.com/q/46756322
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80462133
has body: I have created my first python script for page scraping --> in order to visit a webpage, login, redirect to another page (navigate) and then copy a text from a specific part. When I am trying the following it works fine: copiedText = driver.find_element_by_id("random").text print(copiedText ) but it is a bit more complex as the div of the text I want to copy does not have an ID. It has a class but it is not unique. When I copy the xPath in Chrome, it returns something like this: //*[@id="random"]/div[12]/div[5]/div/div[2]/span which is not the same everyday. The numbers 12 and 5 might be different depending on the data shown in the page (more rows in an HTML table). So, as a plan B, I tried to use the CSS selector instead after copying it from Chrome. but I am getting an error: Message: no such element: Unable to locate element: Is there any chance that Chrome does not give me the right one? How can I convert the outerHTML to a CSS selector in order to be 100% sure that it is correct? The outerHTML is given below: 7,363.31 and the selector after copying from Chrome dev tools is here: #media-grid-right > div.nxm-tr.nxm-drop.media-plan-drop.mpSummary.summary-row.no-filter > div.nxm-td.col-total.text-right UPD The following works fine: Dates = wait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#summary > li:nth-child(1)"))).text and this one returns no error but I am not seeing any text in the cmd: copiedText = wait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#media-grid-right > div.nxm-tr.nxm-drop.drop.mpSummary.summary-row.no-filter > div.nxm-td.col-total.text-right > div > span.summary.number"))).text
has comment: http://stackoverflow.com/comment/80462559
has comment: http://stackoverflow.com/comment/80463431
has comment: http://stackoverflow.com/comment/80458235
has comment: http://stackoverflow.com/comment/80462719
answer count: 1
has answer: http://stackoverflow.com/a/46756479
has comment: http://stackoverflow.com/comment/80462450
favorite count: 0
has comment: http://stackoverflow.com/comment/80462338
score: 0
has comment: http://stackoverflow.com/comment/80463329
tagged with: python
has comment: http://stackoverflow.com/comment/80463051
has comment: http://stackoverflow.com/comment/80462026
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/46756479
has title: Copy text from specific class in selenium
tagged with: selenium
has comment: http://stackoverflow.com/comment/80460173
upvote count: 1
has comment: http://stackoverflow.com/comment/80461333
has comment: http://stackoverflow.com/comment/80462698
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80496195

http://stackoverflow.com/a/46896058
downvote count: 0
score: 3
has body: Use the datetime module and you can add a timedelta of 90 days very easily: &gt;&gt;&gt; import datetime &gt;&gt;&gt; print datetime.datetime.now() 2017-10-23 19:24:19.549670 &gt;&gt;&gt; print datetime.datetime.now() + datetime.timedelta(days=90) 2018-01-21 19:24:21.583689
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46896024
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46896024
type: Answer

http://stackoverflow.com/comment/80476471
has text: You might want to do horizontal bars given that you have many elements. Also make their width similar to the number you're printing. And last, use a better designed color palette. In my opinion, printing all those numbers is very dirty, particularly given the amount of lines, maybe you can increase the granularity of the ticks in your dependant variable and perhaps add some horizontal (or vertical if you do the horizontal bars) guidelines/gridlines.
type: QuestionComment
comment on: http://stackoverflow.com/q/46765518
type: Comment
score: 0

http://stackoverflow.com/q/46820254
answer count: 1
downvote count: 0
has body: I'm starting to learn PyOpenGL, and I'm following this tutorial. At one point the instructor creates a single array from which he extracts the information to construct a triangle: vetices and their color (I added the Numpy line here): #-----------|-Vertices pos--|---Colors----|----------- vertices = [-0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 1.0] vertices = np.array(vertices, dtype = np.float32) The information of this array is passed to glVertexPointer() and glColorPointer() in the display function: def display(): glClear(GL_COLOR_BUFFER_BIT) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glVertexPointer(3, GL_FLOAT, 12, vertices) glColorPointer(3, GLFLOAT, 12, vertices + 3) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_COLOR_ARRAY) glutSwapBuffers() My problem is with the last argument of those functions, in the tutorial (since he is using C++), he can write vertices + 3 in order to tell the program to start reading from the third position of the array, I cannot do this in python. Can some one guide me on how can I define this pointer? Or how can extract the information from my array. Note: I'm aware that I can split the information of vertices and colors in differnt arrays, but I want to know if it is possible to do it using one array. EDIT - Adding the complete code: from OpenGL.GL import * from OpenGL.GLUT import * import numpy as np import ctypes #-----------|-Vertices pos--|---Colors----|----------- vertices = [-0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 1.0] vertices = np.array(vertices, dtype = np.float32) buffer_offset = ctypes.c_void_p float_size = ctypes.sizeof(ctypes.c_float) #----------------------------------------------------- def display(): glClear(GL_COLOR_BUFFER_BIT) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glVertexPointer(3, GL_FLOAT, 24, buffer_offset(…
favorite count: 0
has answer: http://stackoverflow.com/a/46821740
tagged with: python
accepted answer: http://stackoverflow.com/a/46821740
type: AnsweredQuestion
has title: How to extract data for glVertexPointer() and glColorPointer() from a single array in PyOpenGL?
tagged with: opengl
score: 1
upvote count: 1
tagged with: pyopengl
type: Question
tagged with: pointers

http://stackoverflow.com/comment/80453433
type: Comment
type: QuestionComment
has text: You should use the `csv`-module, you should use `for`-loops.
comment on: http://stackoverflow.com/q/46753845
score: 0

http://stackoverflow.com/a/46839404
has comment: http://stackoverflow.com/comment/80626926
has comment: http://stackoverflow.com/comment/80626880
score: 1
has comment: http://stackoverflow.com/comment/80626834
upvote count: 1
answers question: http://stackoverflow.com/q/46837379
has comment: http://stackoverflow.com/comment/80628198
downvote count: 0
has body: From my research the most logical error is there is a dependent module found within __init__ self.handle = _dlopen(self._name, mode) that is not within the same folder as your active DIR. The only other possibility I can think of is self._name is a string variable that is passed a name of a file that is not found in the active DIR. Also, confirm that /home/me/test/mylib.so is a true directory, I only mention this because .so would describe a file type. so it may be that the file you are looking for is a different type of file. All of these instances are something you want to check are accurate when receiving this type of error.
has comment: http://stackoverflow.com/comment/80733396
has comment: http://stackoverflow.com/comment/80626777
type: Answer
has comment: http://stackoverflow.com/comment/80626696

opengl
tags question: http://stackoverflow.com/q/46834905
type: Tag
tags question: http://stackoverflow.com/q/46820254
tags question: http://stackoverflow.com/q/46801701
tag name: opengl

http://stackoverflow.com/comment/80650327
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46850452
has text: You asked the same question yesterday. The answer is still the same.
score: 0

http://stackoverflow.com/comment/80511893
comment on: http://stackoverflow.com/a/46778965
score: 0
type: AnswerComment
has text: Well here the ' ' (whitespace) biome is also a biome. The problem is that adding new biomes overwrite the default one, and the ones drawn just before, so reaching the ratio of biomes you want with this method is going to be difficult.
type: Comment

http://stackoverflow.com/q/46850111
answer count: 3
has answer: http://stackoverflow.com/a/46850531
has comment: http://stackoverflow.com/comment/80650594
tagged with: pandas
has answer: http://stackoverflow.com/a/47384644
has comment: http://stackoverflow.com/comment/80649250
has comment: http://stackoverflow.com/comment/80649419
tagged with: python
tagged with: collaborative-filtering
has comment: http://stackoverflow.com/comment/80648943
has comment: http://stackoverflow.com/comment/80648555
has comment: http://stackoverflow.com/comment/80648453
type: UnansweredQuestion
has title: Fill NA values in Pandas Dataframe using Collaborative Filtering
tagged with: data-cleaning
tagged with: machine-learning
type: Question
has body: I am working on a database of Organic Compounds, and some of the cells have NA values (look at the HFUS column in the second pic): For the purposes of my project, I would like to fill these blank spaces using collaborative filtering, instead of simple mean or median imputation. That is, for the column whose NA value will be filled, we are supposed to find the most similar row(s) comprising the other columns, and then fill in that attribute from those rows. I would like to do this recursively and fill in all the NA values. How do I go about doing this? I found code to do a corr() with the other columns in this link , but I could not get much past creating the corr values. Here's the CSV (33kb) that can be loaded to Pandas: features.csv
has comment: http://stackoverflow.com/comment/80649157
has comment: http://stackoverflow.com/comment/80649348
has answer: http://stackoverflow.com/a/46853362
score: 0

http://stackoverflow.com/q/46902481
has body: This is a working code for a well design flat list to obtain a tree : data = [('john','marry'),('mike','john'),('mike','hellen')('john','elisa')] roots = set() mapping = {} for parent,child in data: childitem = mapping.get(child,None) if childitem is None: childitem = {} mapping[child] = childitem else: roots.discard(child) parentitem = mapping.get(parent,None) if parentitem is None: mapping[parent] = {child:childitem} roots.add(parent) else: parentitem[child] = childitem tree = {id : mapping[id] for id in roots} print (tree) Unfortunately, my flat list is sometimes swap, like this : data = [('marry','john'),('john','mike'),('mike','hellen'),('john','elisa')] So how can I make a recursive validation and swap 'lines' when it's needed for a known head and n child ?
has title: Flat list to tree : handle bad links to make a valid one
tagged with: python
tagged with: tree
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/80825293
has comment: http://stackoverflow.com/comment/80800037
score: 0

http://stackoverflow.com/comment/80632751
score: 0
has text: Please do a favor to cancel downvote. @juanpa.arrivillaga
type: Comment
comment on: http://stackoverflow.com/q/46842099
type: QuestionComment

http://stackoverflow.com/a/46872823
type: AcceptedAnswer
has body: Just do : &gt;&gt;&gt; out = [] &gt;&gt;&gt; for ele in Reference['Data']: out.append(ele['red']) &gt;&gt;&gt; out =&gt; ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364'] Or, a single liner using List comprehension : &gt;&gt;&gt; [ ele['red'] for ele in Reference['Data'] ] =&gt; ['WA-1a9asd4sdfdas', 'WA-150824979asd4', 'WA-1508249792364']
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46872756
answers question: http://stackoverflow.com/q/46872756
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/106284377
type: Comment
comment on: http://stackoverflow.com/a/47135203
has text: @cryanbhu thats pycharm IDE.
score: 1
type: AnswerComment

http://stackoverflow.com/q/46866650
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80682548
type: Question
accepted answer: http://stackoverflow.com/a/46866694
score: 0
has body: At the moment I have tens of thousands of records of the following form: 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000000 82557 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000001 128805 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000002 94990 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000003 121020 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000004 58111390 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000005 167079 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000006 130795 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000007 236926 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000008 24754217 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000009 75407 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000010 136461 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000011 136748 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000012 146258 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000013 381091 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B_000014 129815 In simple spreadsheet programs it's trivial to visualize this data for a few records as done here: I've been trying to adapt this code to visualize it, but thus far- unsuccessfully: # Call like this: # # python opcode-farmer.py 'tst21' '6005600401' # import re import numpy as np import matplotlib.pyplot as plt import csv import sys import pprint import itertools import subprocess import collections def my_test_func(filename, data): with open(filename, 'w') as fd: fd.write(data) fd.write('\n') return subprocess.check_output(['evm', 'disasm', filename]) if '__main__' == __name__: file_name = sys.argv[1] byte_code = sys.argv[2] status = my_test_func(file_name, byte_code) opcodes_list = list() for element in status.split('\n'): result = re.search(r"\b[A-Z].+", element) if result: # eliminate individual 0x05 specification simple_opcode = re.sub(r'\s(.*)', '', result.group(0)) opcodes_list.append(simple_opcode) # Count up the values cnt = collections.Counter() for word in opcodes_list: cnt[word] += 1 print(cnt) # THRESHOLD threshold = 30 cnt = collections.Count…
answer count: 1
tagged with: histogram
has comment: http://stackoverflow.com/comment/80682754
has comment: http://stackoverflow.com/comment/80682263
has comment: http://stackoverflow.com/comment/80682306
tagged with: data-visualization
tagged with: python
has answer: http://stackoverflow.com/a/46866694
has title: Regex processing of input data, subsequent visualization using Python and histogram

http://stackoverflow.com/q/46825434
accepted answer: http://stackoverflow.com/a/46826290
has comment: http://stackoverflow.com/comment/80598823
has comment: http://stackoverflow.com/comment/80599188
has title: How to assign every element of a data frame at once?
tagged with: pandas
has body: I have OG_df which is: Symbol Order Shares Date 2011-01-10 AAPL BUY 1500 2011-01-13 AAPL SELL 1500 2011-01-13 IBM BUY 4000 2011-01-26 GOOG BUY 1000 2011-02-02 XOM SELL 4000 2011-02-10 XOM BUY 4000 2011-03-03 GOOG SELL 1000 2011-03-03 GOOG SELL 2200 2011-05-03 IBM BUY 1500 2011-06-03 IBM SELL 3300 2011-06-10 AAPL BUY 1200 2011-08-01 GOOG BUY 55 2011-08-01 GOOG SELL 55 2011-12-20 AAPL SELL 1200 2011-12-21 AAPL BUY 20 2011-12-27 GOOG BUY 2200 2011-12-28 IBM SELL 2200 I also have df_prices which is: AAPL IBM GOOG XOM SPY CASH 2011-01-10 340.99 143.41 614.21 72.02 123.19 1.0 2011-01-11 340.18 143.06 616.01 72.56 123.63 1.0 ... ... ... ... ... ... ... 2011-11-15 387.17 186.44 616.56 77.62 124.10 1.0 2011-11-16 383.13 184.33 611.47 76.79 122.13 1.0 2011-11-17 375.80 183.45 600.87 76.41 120.19 1.0 2011-11-18 373.34 182.97 594.88 76.45 120.06 1.0 2011-11-21 367.43 179.26 580.94 75.48 117.78 1.0 2011-11-22 374.90 179.09 580.00 74.61 117.31 1.0 [245 rows x 6 columns] I set date_range = pd.date_range(OG_df.index.min(), OG_df.index.max()) and then df1 = pd.DataFrame(0, df_prices.index, columns=list(df_prices)) Say you have vals = df1.values which is: [[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]] with shape (245, 6) I can also get cols = np.array([df1.columns.get_loc(c) for c in OG_df.Symbol]) cols returns [0 0 1 2 3 3 2 2 1 1 0 2 2 0 0 2 1] OG_df.Symbol is ['AAPL' 'IBM' 'GOOG' 'XOM'], so as you can see, there are 4 different columns for 17 different rows in OG_df. I also have rows = np.arange(len(df1)) I want to do something like vals[rows, cols] = some_variable but that returns: IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (245,) (17,) because rows is length 17 and cols is length 245. I want to fill every cell in df1 based on some_variable (which is different every time). order = np.where(orders_df.Order.values == 'BUY', -1, 1) some_variable = OG_df.Shares.values * order len(some_variable) =…
has comment: http://stackoverflow.com/comment/80598571
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46826290
has comment: http://stackoverflow.com/comment/80600080
has comment: http://stackoverflow.com/comment/80598748
favorite count: 0
has comment: http://stackoverflow.com/comment/80599048
has comment: http://stackoverflow.com/comment/80598649
has comment: http://stackoverflow.com/comment/80599359
has comment: http://stackoverflow.com/comment/80599638
has comment: http://stackoverflow.com/comment/80598421
has comment: http://stackoverflow.com/comment/80598804
tagged with: python
tagged with: vectorization
tagged with: indexing
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80599432
has comment: http://stackoverflow.com/comment/80599697
has comment: http://stackoverflow.com/comment/80598586
has comment: http://stackoverflow.com/comment/80599821
has comment: http://stackoverflow.com/comment/80600034
type: Question
has comment: http://stackoverflow.com/comment/80599724
has comment: http://stackoverflow.com/comment/80598713
has comment: http://stackoverflow.com/comment/80599762
has comment: http://stackoverflow.com/comment/80599725
tagged with: dataframe
score: -1

http://stackoverflow.com/comment/80493458
has text: the most performant solution being the sieve of Erathosthenes. Look that up.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46773854

http://stackoverflow.com/a/46781012
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46780954
has comment: http://stackoverflow.com/comment/80543183
score: 3
has body: The script may be running as user www-data, whose home directory is defined in /etc/passwd by default as /var/www.
has comment: http://stackoverflow.com/comment/80525891
upvote count: 3

http://stackoverflow.com/q/46752942
has comment: http://stackoverflow.com/comment/80451676
has comment: http://stackoverflow.com/comment/80451826
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80451609
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80451678
has answer: http://stackoverflow.com/a/46753088
has body: I've got a list which looks like this: ['Data', '2017-10-12', 'Nr', 'lekcji', '6', 'Nauczyciel', 'Name', 'Nothing', 'Rodzaj', 'sprawdzian', 'Przedmiot', 'Math', 'Opis', 'This', 'is', 'just', 'a', 'test.', 'Data', 'dodania', '2017-10-01', '18:12:31'] And I want to convert it to list which some keywords. Here is the result which I want to get: {'Data': '2017-10-12', 'Nr lekcji': '6', 'Nauczyciel': 'Name Nothing', 'Rodzaj': 'sprawdzian', 'Przedmiot': 'Math', 'Opis': 'This is just a test.', 'Data dodania': '2017-10-01 18:21:32'} Is it possible ? Thanks for help! EDIT base string: Data 2017-10-12 Nr lekcji 6 Nauczyciel Name Nothing Rodzaj sprawdzian Przedmiot Math Opis This is just a test. Data dodania 2017-10-01 18:12:31
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46753257
has comment: http://stackoverflow.com/comment/80451747
has comment: http://stackoverflow.com/comment/80451702
has answer: http://stackoverflow.com/a/46753105
answer count: 3
accepted answer: http://stackoverflow.com/a/46753088
has comment: http://stackoverflow.com/comment/80451761
has comment: http://stackoverflow.com/comment/80451580
has comment: http://stackoverflow.com/comment/80451722
downvote count: 0
has comment: http://stackoverflow.com/comment/80451707
score: 1
possible better answer: http://stackoverflow.com/a/46753105
has title: Python 3 - List to dictionary. Sort by words
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80451696
has comment: http://stackoverflow.com/comment/80451753
tagged with: python

http://stackoverflow.com/q/46759051
answer count: 4
possible better answer: http://stackoverflow.com/a/46759102
has answer: http://stackoverflow.com/a/46759102
has title: How to handle large inputs and improve run-time complexity?
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46759169
has body: I have the following function, that aims at returning the best average grade. It takes inputs like: scores = [["bob",100],["bob",100],["toto",100],["frank",100]] How can I improve it so it handles large inputs within a set period of time? That is to say how to have hte better run-time complexity? EDIT: it should handle negative scores and empty scores. def maxavg(scores): avs=[] namelist=[] for i in range(0,len(scores)): name = scores[i][0] if name not in namelist: namelist.append(name) note = scores[i][1] nbnotes = 1 for j in range(i+1,len(scores)): if scores[j][0]==name: nbnotes+=1 note+=scores[j][1] avs.append(note/nbnotes) return max(avs)
has answer: http://stackoverflow.com/a/46759098
score: 0
tagged with: time-complexity
has answer: http://stackoverflow.com/a/46759127
accepted answer: http://stackoverflow.com/a/46759169
tagged with: python
has comment: http://stackoverflow.com/comment/80463588

http://stackoverflow.com/a/46896690
score: 0
answers question: http://stackoverflow.com/q/46896650
has body: Create a list comprehension and only keep the values if the index is not None, it will keep your sub-lists intact: features = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] &gt;&gt;&gt; print features [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] &gt;&gt;&gt; print [f for f in features if f is not None] [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
type: Answer

http://stackoverflow.com/a/46840356
answers question: http://stackoverflow.com/q/46840094
score: 0
has body: I'd suggest a simplified implementation like this because it's much easier to understand and your original generateFalseTrueRangesAlternatively doesn't yield the correct values: def alternate_trues_and_falses(limit): for i in range(1, limit + 1): for j in range(i): yield True for j in range(i): yield False &gt;&gt;&gt; list(alternate_trues_and_falses(2)) [True, False, True, True, False, False] &gt;&gt;&gt; for value in alternate_trues_and_falses(2): ... print(value) ... True False True True False False
has comment: http://stackoverflow.com/comment/80629212
type: Answer

http://stackoverflow.com/q/46841569
tagged with: python
has answer: http://stackoverflow.com/a/46841590
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80631000
downvote count: 3
has body: I am new to Python, and you might have seen the question I asked earlier about a similar issue. I tried to run the code below, but it just prints the first to letters of the first line (Us). It is probably my own beginner's stupidity, but I would really appreciate some help with the issue. Thank you in advance if you can solve my issue! Code I tried to run below: file = open("createdFile.txt", "w") file.write("User Data Number:\n") file.write("10101") file.close() file = open("createdFile.txt", "r") getUserNumber = file.readline(2) print(getUserNumber) file.close()
has comment: http://stackoverflow.com/comment/80630971
type: Question
has comment: http://stackoverflow.com/comment/80630960
has comment: http://stackoverflow.com/comment/80630988
accepted answer: http://stackoverflow.com/a/46841590
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/80631016
answer count: 1
linked to: http://stackoverflow.com/q/3541203
favorite count: 0
score: -1
tagged with: python-3.x
upvote count: 2
has title: Python file.readline(2) reads first 2 charectars

http://stackoverflow.com/q/46864839
type: UnansweredQuestion
tagged with: punctuation
score: -3
has comment: http://stackoverflow.com/comment/80677649
has comment: http://stackoverflow.com/comment/80677249
has comment: http://stackoverflow.com/comment/80677240
has comment: http://stackoverflow.com/comment/80677263
has comment: http://stackoverflow.com/comment/80677829
has comment: http://stackoverflow.com/comment/80677195
has body: I want to count 'end sentences' e.g. full stops, exclamation marks, and question marks. I have written a little loop to do this, but I was wondering if there is a better way. Not allowed to use built-in functions. for line in textContent: numberOfFullStops += line.count(".") numberOfQuestionMarks += line.count("?") numberOfQuestionMarks += line.count("!") numberOfSentences = numberOfFullStops + numberOfQuestionMarks + numberOfExclamationMarks
has comment: http://stackoverflow.com/comment/80678510
has comment: http://stackoverflow.com/comment/80677309
type: Question
has comment: http://stackoverflow.com/comment/80677132
has title: Is there a better way to count punctuation in a sentence?
answer count: 1
has comment: http://stackoverflow.com/comment/80677121
tagged with: counting
favorite count: 0
has comment: http://stackoverflow.com/comment/80677222
has comment: http://stackoverflow.com/comment/80677396
downvote count: 3
has answer: http://stackoverflow.com/a/46865432
has comment: http://stackoverflow.com/comment/80677323
has comment: http://stackoverflow.com/comment/80677274
tagged with: python
upvote count: 0

http://stackoverflow.com/comment/80542676
comment on: http://stackoverflow.com/a/46797943
type: Comment
has text: Changed it just now
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80500529
score: 0
type: Comment
type: QuestionComment
has text: @JohnMinze yes. Check out my answer, I am getting >8x speedup. But yes, `pd.to_datetime` is handy because it will understand things like `"thursday, april 2 2012"` without having to specify a format. It uses the`dateutil` parser underneath the hood. However, the cost of flexibility is speed, which makes sense.
comment on: http://stackoverflow.com/q/46776588

http://stackoverflow.com/q/46810286
has body: This has been taking over 7 hours with no success. By now I have no idea why. I have two forms, this screenshot should give a pretty good indication of the flow I'm looking for. So basically, a user either selects one of the existing items from the dropdown menu of BottleForm (marked in the screenshot as "1"), or he elects to click the Add button, which opens a modal of another form BrandForm (marked in the screenshot as "2"), which should let him fill a new brand name. What I want is that when a new brand-name is submitted in the BrandForm and the page is reloaded, that brand is already pre-selected in the dropdown menu. I've read countless of threads but none of the suggested answers regarding setting initial on the field work. Why is it not working? views.py (add_brand is the submit name for the BrandForm): # Add brand form elif 'add_brand' in request.POST: brand_name = request.POST['name'] # this is the brand name we submitted context['form'] = BottleForm(initial={'brand': brand_name}) context['form2'] = BrandForm(request.POST) the_biz = Business.objects.filter(owner=user.id).first() if context['form2'].is_valid(): print("brand for valid!") brand = context['form2'].save(commit=False) brand.business = the_biz brand.save() return render(request, template_name="index.pug", context=context) bottle_form.pug: //- Create New Brand Modal div.modal.fade.create-new-brand(tabindex="-1" role="dialog") div.modal-dialog.modal-sm(role="document") div.modal-content div.modal-header H3 Enter the Brand's name here: div.modal-body form.form-horizontal(method="post" action=".") | {% csrf_token %} | {{ form2.as_p }} hr btn.btn.btn-default(type="button" data-dismiss="modal") Close input.btn.btn-primary(type="submit" value="submit")(name="add_brand") Add Brand models.py: class Brand(models.Model): name = models.CharField(max_length=150, blank=False) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="brands") permissions = ( ('view_brand', 'View the brand'),…
tagged with: django-forms
type: Question
has answer: http://stackoverflow.com/a/46811516
has title: Django: Can't pre-select from option menu Upon POST
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46811516
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/80595330
has text: I agree with @igrinis, CSV doesn't fit that data, I would use JSON.That way loading and unloading the data from and to the file would be trivial as JSON stores `list`s as JSON arrays (same notation with square brackets)
comment on: http://stackoverflow.com/q/46811986
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/54499180
answers question: http://stackoverflow.com/q/46773577
has comment: http://stackoverflow.com/comment/95813027
type: Answer
upvote count: 1
has body: Even if you only use curses in one thread, other processing-heavy threads can disrupt the escape sequences in the curses thread. The environment variable $ESCDELAY indicates how long (in ms) to wait after an escape code (0x1B) is sent; and if more than that time elapsed, a ^[ keystroke (ESC) is returned by get_wch().
downvote count: 1
score: 0

http://stackoverflow.com/q/46833451
has title: Python - How to pass a variable from one method to another in Python?
has answer: http://stackoverflow.com/a/46833608
type: Question
has body: I've looked around for a question like this. I've seen similar questions, but nothing that really helped me out. I'm trying to pass the choice variable from the method rollDice() to the method main(). This is what I've got so far: import random import os import sys def startGame(): answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n' os.system('cls') if (answer == '1'): rollDice() elif(answer == '2'): print('Thank you for playing!') else: print('That isn/t a valid selection.') StartGame() def rollDice(): start = input('Press Enter to roll dice.') os.system('cls') dice = sum(random.randint(1,6) for x in range (2)) print('you rolled ',dice,'\n') choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n) return choice def main(): startGame() while (choice == '1'): startGame() print('Thank you for playing') print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n') main() I know that I may have other things in here that are redundant or I may have to fix, but I'm just working on this one issue right now. I'm not sure how to pass the choice variable into the main() method. I've tried putting choice == rollDice() in the main() method but that didn't work. I do mostly SQL work, but wanted to start learning Python and I found a website that has 5 beginner tasks but virtually no instructions. This is task one.
type: AnsweredQuestion
tagged with: methods
accepted answer: http://stackoverflow.com/a/46833608
score: 0
tagged with: function
has comment: http://stackoverflow.com/comment/80614537
answer count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/80614685
has comment: http://stackoverflow.com/comment/80615140
tagged with: python

http://stackoverflow.com/comment/122941035
has text: What if the value of 'a' changes after every iteration of the for loop? Does the space complexity remain the same?
type: Comment
comment on: http://stackoverflow.com/a/46801951
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80728672
comment on: http://stackoverflow.com/q/46890714
type: Comment
type: QuestionComment
score: 2
has text: The moment an element is found which is not common, your code will stop executing. Why? Because, `return` statement is encountered. So, put it at the end, after the for loop.

http://stackoverflow.com/a/46814541
has comment: http://stackoverflow.com/comment/80576729
accepted answer of: http://stackoverflow.com/q/46812652
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46812652
has comment: http://stackoverflow.com/comment/80576559
has body: Django does not render inside css. If you want to change the background-image then better write inline inside template: Inside template: You can also create dynamic css, but it is not the case because you need to change only one property.
type: Answer

http://stackoverflow.com/q/46902467
score: 1
has comment: http://stackoverflow.com/comment/80751980
type: Question
has comment: http://stackoverflow.com/comment/80752106
has comment: http://stackoverflow.com/comment/80752012
has comment: http://stackoverflow.com/comment/80752027
upvote count: 1
favorite count: 0
has body: I'm trying to implement monte carlo tree search for an ultimate tictactoe game (its like tictactoe but the board is larger) and am having trouble in the selection phase of the alogirthm. My search tree is made up of individual nodes which the first part of the algorithm is trying to select one of to expand. However, I keep on getting an error that the maximum recursion has been reached: def select_node(node, board, state, identity): """ Traverses the tree until the end criterion are met. Args: node: A tree node from which the search is traversing. board: The game setup. state: The state of the game. identity: The player's identity, either 1 or 2. Returns: A node from which the next stage of the search can proceed. """ if len(node.child_nodes) == 0 and len(node.untried_actions) &gt; 0: # Node is root, choose it return node best_child = None if board.current_player(state) == identity: # its our turn best_child_utc = -inf for move in node.child_nodes: child_node = node.child_nodes[move] if child_node.visits == 0: best_child = child_node break child_UCB_score = (child_node.wins/child_node.visits) + 1.41 * sqrt(log(node.visits)/child_node.visits) if child_UCB_score &gt; best_child_utc: best_child = child_node best_child_utc = child_UCB_score else: # its the opponents turn best_child_utc = -inf for move in node.child_nodes: child_node = node.child_nodes[move] if child_node.visits == 0: best_child = child_node break child_UCB_score = 1 - ((child_node.wins/child_node.visits) + 1.41 * sqrt(log(node.visits)/child_node.visits)) if child_UCB_score &gt; best_child_utc: best_child = child_node best_child_utc = child_UCB_score if best_child is not None and len(best_child.child_nodes) &gt; 0 and not board.is_ended(best_child.state): return select_node(best_child, board, best_child.state, identity) else: return best_child Is there any way to maybe transform my algorithm from being recursive to using some sort of loop so it doesn't hit the recursion limit? This is being played on 9x9…
tagged with: python
has comment: http://stackoverflow.com/comment/80751881
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80752075
has title: Monte Carlo Selection phase maximum recursion exceeded
tagged with: tic-tac-toe
tagged with: montecarlo
tagged with: recursion
downvote count: 0

http://stackoverflow.com/q/46803527
accepted answer: http://stackoverflow.com/a/46803575
type: Question
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: python
has title: Add values from n dataframes if match ID of another dataframe
favorite count: 0
has comment: http://stackoverflow.com/comment/80553698
has answer: http://stackoverflow.com/a/46803575
has body: I currently have n number of dataframes (dfs[n]) with IDs and X values and one dataframe (df) with IDs. I would like to add X values to a new column in df if IDs of the X value match the ID of df and add 'X values n' as the column name. for n in range(len(files)): if dfs[n]['ID'] == df['ID']: df = df.join(dfs[n]['X values'], on='ID', rsuffix = int(r)) print(df) I tried this code but doesn't work. Thank you for your help!
has comment: http://stackoverflow.com/comment/80554516
upvote count: 1
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80553775

http://stackoverflow.com/q/46806763
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46815851
type: Question
tagged with: xml-parsing
has title: Need help to parse an XML file
has body: I'm trying to parse an XML file and I am blocked on something. Take a quick look on my XML file : <editrust> <terminé>1</terminé> 1 <terminé>11</terminé> 11 <terminé>150</terminé> 150 <terminé>150</terminé> 150 <terminé>2</terminé> 2 <terminé>181</terminé> 121 <terminé>600</terminé> 600 <terminé>600</terminé> 600 ... I want to render something like a dictionary list {'ITFR2006': ['IN', 'H10', '1','1', 'H60', '11', '11', 'D1', '150', '150'],... I did a script : import xml.etree.ElementTree as etree tree = etree.parse('fichier.xml') root = tree.getroot() flux = {} def findText(node): for child in node: if child.attrib.get("ref"): if "ITFR" in child.attrib.get("ref"): itfr = child.attrib.get("ref") flux[itfr] = [] print("\n-----------------\n") print(child.attrib.get("ref")) if child.attrib.get("sens"): flux[itfr].append(child.attrib.get("sens")) print(child.attrib.get("sens")) if child.text.strip(): print(child.text.strip()) findText(child) findText(root) print(flux) The script has this render : ----------------- ITFR2006 IN H10 1 1 H60 11 11 D1 150 150 D2 150 150 ----------------- ITFR2007_2021 IN H10 2 2 H60 181 121 D1 600 600 D2 600 600 .... So, the print(flux) makes: {'ITFR2006': ['IN'], 'ITFR2007_2021': ['IN'], 'ITFR2008': ['IN'], 'ITFR2011_2020': ['IN'], 'ITFR2012': ['OUT'], 'ITFR2013': ['OUT'], 'ITFR2014': ['OUT'], 'ITFR2017': ['OUT'], 'ITFR2018': ['OUT'], 'ITFR2019': ['OUT'], 'ITFR2023': ['OUT'], 'ITFR2024': ['OUT']} This is a good begining I think but I can't fill my list with the others values ('H10', '1', '1', 'H60', ...) Any idea to finish my work ? Thanks
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80561936
tagged with: elementtree
favorite count: 0
has answer: http://stackoverflow.com/a/46815851
has comment: http://stackoverflow.com/comment/80561617
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47154147
answers question: http://stackoverflow.com/q/46874171
type: Answer
score: 11
accepted answer of: http://stackoverflow.com/q/46874171
upvote count: 11
has comment: http://stackoverflow.com/comment/87367245
has body: Ok it is quite funny to answer my own question, but I understood that is the encouraged way to go if you actually found the answer. So what was causing this problem was that __init__.py was listed as a text file in Pycharm settings. If you go to Settings | File Types | Select Text you see a list of file names/extensions that Pycharm recognizes as text. I think this happened because I created a file named __init__ without file extension, and later changed it to __init__.py Removing it from there fixed the issue.
has comment: http://stackoverflow.com/comment/116999709
has comment: http://stackoverflow.com/comment/89301803
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92277800
has comment: http://stackoverflow.com/comment/87847360

http://stackoverflow.com/a/46902104
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46902026
type: Answer
answers question: http://stackoverflow.com/q/46902026
has comment: http://stackoverflow.com/comment/80751276
score: 0
has body: Try this: ReadImage = ReadImage[:, :, X] where X is the channel you want to select. For your second question, you might want to sort your array and then select the second maximum number.

http://stackoverflow.com/a/46794270
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/46793821
upvote count: 3
has body: Doesn't include the top number strip def P1(): print(" " + (" ---" * game)) def P2(): print(str(i+1) + ("| " * (game + 1))) game = 3 P1() for i in range(game): P2() P1()
type: Answer

http://stackoverflow.com/comment/80544545
score: 2
comment on: http://stackoverflow.com/q/46798691
type: Comment
type: QuestionComment
has text: @Bahrom the thing I don't like about that approach is that the `*` splat operator actually materializes a `tuple`, so, if the number of arguments is large, this becomes increasingly inefficient.

http://stackoverflow.com/q/46796211
has comment: http://stackoverflow.com/comment/80539189
type: Question
score: -2
has body: I'm assigning a bunch of values to dict keys, and some of the pairs semantically belong to others, but I can't indent to show possession because Python. This is akin to what I have: boxColors["large trunk"] = "black" boxColors["shoebox 1"] = "red" boxColors["shoebox 2"] = "tan" boxColors["jewelery box"] = "white" boxColors["tacklebox"] = "green" But, the shoeboxes are inside the trunk, and the jewelery box is inside shoebox 2. It would be much easier to see this relationship if I could indent things like this: boxColors["large trunk"] = "black" boxColors["shoebox 1"] = "red" boxColors["shoebox 2"] = "tan" boxColors["jewelery box"] = "white" boxColors["tacklebox"] = "green" Obviously I can't, because of how Python interprets whitespace-indentation. Is there some sort of no-op thing I could put at the start of a line to push the rest of the line over without changing its functionality? For example, if this were some sort of whitespace-significant version of C, I'd do this: boxColors["large trunk"] = "black" /**/boxColors["shoebox 1"] = "red" /**/boxColors["shoebox 2"] = "tan" /******/boxColors["jewelery box"] = "white" /**/boxColors["tacklebox"] = "green" But, alas, Python doesn't have C-style block comments. Is there a way to do what I want? (Yes, I realize I'm deliberately subverting the language's design. Being able to subvert it in this manner would improve my code's readability. I know, I know, Python's rules are designed to enforce readability, but they're imperfect, and I think I've found an edge case.) Edit: I've thought about separating sections with newlines, but that doesn't let me show multiple-level-deep ownership relationships, which I expect to have in droves.
downvote count: 2
has comment: http://stackoverflow.com/comment/80539159
tagged with: indentation
has comment: http://stackoverflow.com/comment/80539248
answer count: 1
favorite count: 0
has title: Are there ways to sidestep Python's indentation rules?
has answer: http://stackoverflow.com/a/46796252
has comment: http://stackoverflow.com/comment/80539141
type: UnansweredQuestion
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/80539148
has comment: http://stackoverflow.com/comment/80539837

http://stackoverflow.com/comment/80705393
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46878889
type: AnswerComment
has text: Now I get the window, but it losses its form and layouts and I get the error: `QLayout: Attempting to add QLayout "" to SinglePlotWindow "Form_single_plot", which already has a layout`

http://stackoverflow.com/comment/80665637
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46859003
has text: Because when you iterate over a `dict` you iterate over the keys. To get the maximum value, try `max(a.values())`

http://stackoverflow.com/a/46831342
score: 1
has comment: http://stackoverflow.com/comment/80611345
has comment: http://stackoverflow.com/comment/80611806
has comment: http://stackoverflow.com/comment/80610935
has comment: http://stackoverflow.com/comment/80610773
upvote count: 1
has comment: http://stackoverflow.com/comment/80611842
type: Answer
has body: You could use this to generate all possible combinations for a given length n and then filter the invalid ones. A faster method that uses comprehension (prefer for smaller n values): n = 10 combinations = [''.join(x) for x in itertools.product('ab', repeat=n)] valid = [x for x in combinations if 'bbb' in x] print len(valid) A RAM efficient method that uses generators (prefer for bigger n values): n = 10 combinations = (''.join(x) for x in itertools.product(['a', 'b'], repeat=n)) valid = (x for x in combinations if 'bbb' in x) print sum(1 for _ in valid)
downvote count: 0
has comment: http://stackoverflow.com/comment/80614659
has comment: http://stackoverflow.com/comment/80614714
answers question: http://stackoverflow.com/q/46830743

http://stackoverflow.com/q/46868001
tagged with: channel
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47628191
accepted answer: http://stackoverflow.com/a/47628191
downvote count: 0
tagged with: django
type: Question
has title: Is it possible to assign django channels group in connection?
has body: I hope you're all right: my question is whether I can make a connection to web socket from the client to a specific group, I'm currently connecting customers as follows: //connecting client with js var ws_scheme = window. location. protocol == "https:"? "wss":"ws"; //var ws_path = ws_scheme +': //' + window. location. host + "/sync/"; var ws_path = ws_scheme + ": //localhost: 8001"; console. log ("Connecting to " + ws_path); var socket = new ReconnectingWebSocket (ws_path); Okay, that's how it works, The problem is that I want each client to connect to a group created previously example: def ws_connect (message): for x in users: Group (x). add (message. reply_channel) and so sent the message to the respective group Group ("group1"). send ({' text': json. dumps (msg)}) Group ("group2"). send ({' text': json. dumps (msg)})
upvote count: 2
answer count: 1
tagged with: websocket
favorite count: 0

http://stackoverflow.com/q/46880944
accepted answer: http://stackoverflow.com/a/46881645
tagged with: numpy
has comment: http://stackoverflow.com/comment/80709314
score: 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46881645
type: AnsweredQuestion
has title: Delete row from scipy matrix
has comment: http://stackoverflow.com/comment/80710147
has body: I have a scipy sparse matrix data and an integer n which corropsonds to a row in data which I want to delete. To delete this row I tried this: data = sparse.csr_matrix(np.delete(np.array(data),n, axis=0)) However, this produced this error: Traceback (most recent call last): File "...", line 260, in &lt;module&gt; X_labeled = sparse.csr_matrix(np.delete(np.array(X_labeled),n, axis=0)) File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/compressed.py", line 79, in __init__ self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype))) File "/anaconda3/lib/python3.6/site-packages/scipy/sparse/coo.py", line 177, in __init__ self.row, self.col = M.nonzero() SystemError: &lt;built-in method nonzero of numpy.ndarray object at 0x113c883f0&gt; returned a result with an error set When I run: data = np.delete(data.toarray(),n, axis=0) I get this error: Traceback (most recent call last): File "...", line 261, in &lt;module&gt; X_labeled = np.delete(X_labeled.toarray(),n, axis=0) File "/anaconda3/lib/python3.6/site-packages/numpy/lib/function_base.py", line 4839, in delete "size %i" % (obj, axis, N)) IndexError: index 86 is out of bounds for axis 0 with size 4 When I run this: print(type(data)) print(data.shape) print(data.toarray().shape) I get this: &lt;class 'scipy.sparse.csr.csr_matrix'&gt; (4, 2740) (4, 2740)
upvote count: 3
has comment: http://stackoverflow.com/comment/80710118
tagged with: scipy
type: Question

http://stackoverflow.com/a/46774528
has comment: http://stackoverflow.com/comment/80684429
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46774412
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46774412
has comment: http://stackoverflow.com/comment/80689440
type: Answer
has body: tf.Variable accepts an initial value upon creation (a constant), this explains deterministic results when you use it. tf.get_variable is slightly different: it has an initializer argument, by default None, which is interpreted like this: If initializer is None (the default), the default initializer passed in the variable scope will be used. If that one is None too, a glorot_uniform_initializer will be used. Since you didn't pass an initializer, the variable got uniform random initial value.

http://stackoverflow.com/comment/80471114
score: 0
type: Comment
has text: "For some reason, the teacher doesn't want us to use while for the entire practice." - This answer is invalid.
type: AnswerComment
comment on: http://stackoverflow.com/a/46762950

http://stackoverflow.com/comment/80613594
has text: But concatenating *is* the answer. Django URL patterns don't include querystring parameters.
comment on: http://stackoverflow.com/q/46832963
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/80742204
comment on: http://stackoverflow.com/q/46897337
score: 0
type: QuestionComment
type: Comment
has text: Or even simpler: `otr.x -= 2` and `self.x -= 2`.

http://stackoverflow.com/comment/80552163
type: QuestionComment
has text: Looks like I misunderstood your question. Where is backtracker located?
comment on: http://stackoverflow.com/q/46802586
score: 0
type: Comment

http://stackoverflow.com/comment/80484225
comment on: http://stackoverflow.com/q/46769464
has text: Can you print the `type()` of that? I assume one is bytes, the other is str?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80726481
type: Comment
comment on: http://stackoverflow.com/q/46889602
score: 0
type: QuestionComment
has text: And regarding avoiding the loop, you should simply be able to use `new_X = X - new_origin` (assuming that `X` actually has shape `(68, 2)`, as you claim, though you code suggests otherwise).

http://stackoverflow.com/q/46883245
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/80716622
has title: Blur from OpenCV in Region of Interest
has comment: http://stackoverflow.com/comment/80715781
upvote count: 7
answer count: 1
has answer: http://stackoverflow.com/a/46886742
has body: I am trying create a circle and blur the contents in OpenCV. However, I am able to make the circle, but I am not able to blur that part. My code is given below. Please help me out import io import picamera import cv2 import numpy as np import glob from time import sleep from PIL import ImageFilter image = cv2.imread('/home/pi/Desktop/cricle-test/output_0020.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faceCascade = cv2.CascadeClassifier('/home/pi/Desktop/Image-Detection-test/haarcascade_frontalface_alt.xml') faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=5, minSize=(30, 30), flags = cv2.cv.CV_HAAR_SCALE_IMAGE ) print "Found {0} faces!".format(len(faces)) # Draw a circle around the faces and blur for (x, y, w, h) in faces: sub = cv2.circle(image, ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (0, 255, 0), 5) cv2.blur(image(x,y,w,h),(23,23), 40000) cv2.imwrite("/home/pi/Desktop/cricle-test/output_0020.jpg" ,image)
tagged with: opencv
has comment: http://stackoverflow.com/comment/80718112
has comment: http://stackoverflow.com/comment/80715635
tagged with: numpy
downvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46886742
has comment: http://stackoverflow.com/comment/80717522
favorite count: 0
has comment: http://stackoverflow.com/comment/80714381

http://stackoverflow.com/q/46795215
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
has title: "disable" on_change id odoo 9 after creating product
type: UnansweredQuestion
tagged with: python
score: 2
has body: I'd like to ask, if is there any way to "disable" onchange decorator, when product is already created. I have a field (X), which value depends, what will be in the 3 another fields (Y). I've used "api.onchange". When product is created, i want to make, that one of Y fields, will not change a value of X anymore. I tryed to check, if "self" is existing in database, like exists(), but even new record is marked as "existing". I tryed to get access to self.id, but it's impossible. I thought about create additional field with Boolean type, but it's the last resort.
tagged with: odoo
tagged with: odoo-9
has answer: http://stackoverflow.com/a/46798002
type: Question
tagged with: postgresql

http://stackoverflow.com/a/46900504
has body: @TheoretiCAL's answer shows you one approach to get desired result and here is another one: methods = { 'canberra': dist.canberra, 'euclidean': dist.euclidean, # etc } def get_distances(q, x, dist_method=None, *args, **kwargs): method = methods.get(dist_method, dist.euclidean) return [method(q, x_i) for x_i in x]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46900428

http://stackoverflow.com/comment/80700525
has text: thanks for your answer to the question! What a smart approach!
comment on: http://stackoverflow.com/a/46876714
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46857052
answer count: 1
linked to: http://stackoverflow.com/q/37682284
type: UnansweredQuestion
tagged with: python
has body: I have a question like Mask a 3d array with a 2d mask in numpy, but the answer from that isn't working for my issue; I am trying to get elements of an RGB image selected based on a 2d mask. I created a 2d mask with values of 1, on the elements that I want to preserve, with the rest being 0. I then want to apply this mask to an RGB image array and want to retain values only for elements that match the mask value of 1. I tried this code and it bombed. How do I select the pixels (and its values) based on the mask location. My bombed code based on the solution that is in the link is below. import numpy as np from PIL import Image, ImageDraw polygon = [(5,5), (10,5), (15,15), (2,15)] width = 20 height = 20 # create a mask img = Image.new('L', (width, height), 0) ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1) mask = np.array(img) mask = mask[:,:,np.newaxis] a_arr = np.arange(1200).reshape(20,20,3) # create a test image type array o_arr = np.ma.array(a_arr, mask=mask) print o_arr
has title: Selecting RGB image pixels from an image using a mask
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46857686
tagged with: image
score: 0

http://stackoverflow.com/q/46769840
score: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: this code opens a CSV, reads it and print the first row after the 'header' row. I'm using pprint to have the output of a dictionary. But, my code is not printing anything even with print(). Where am i going wrong? import csv from datetime import datetime from pprint import PrettyPrinter def print_first_point(filename): """ This function prints and returns the first data point (second row) from a csv file that includes a header row. """ # print city name for reference city = filename.split('-')[0].split('/')[-1] print('\nCity: {}'.format(city)) with open(filename, 'r') as f_in: trip_reader = csv.DictReader(f_in) def first_trip (trip_reader): reader = csv.DictReader (trip_reader) first = next (reader) return first pp = pprint.PrettyPrinter(indent=4) pp.pprint(first_trip)
has comment: http://stackoverflow.com/comment/80484949
has comment: http://stackoverflow.com/comment/80485494
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/80485253
has comment: http://stackoverflow.com/comment/80484880
has comment: http://stackoverflow.com/comment/80485023
has title: Error: PrettyPrinter is outside the scope of function
has comment: http://stackoverflow.com/comment/80485206

http://stackoverflow.com/comment/80608613
type: Comment
type: QuestionComment
has text: I am currently getting no input
comment on: http://stackoverflow.com/q/46818389
score: 0

http://stackoverflow.com/q/46767793
downvote count: 0
has body: using Anaconda2-5.0.0-Windows-x86_64, Python2.7, exchangelib 1.10.4 I am trying to save attachments from all emails from an exchange account. It seems I can connect to the account without problem but everytime I try to run through the process, it gives me an error message. Here is the code which I have tried : mailbox = account.inbox for msg in mailbox.all(): for attachment in msg.attachments: fpath = os.path.join(r'C:\temp', attachment.name) with open(fpath, 'wb') as f: f.write(attachment.content) The error I am getting is : The 'FieldURI' attribute is invalid - The value 'item:IsAssociated' is invalid according to its datatype 'http://schemas.microsoft.com/exchange/services/2006/types:UnindexedFieldURIType' - The Enumeration constraint failed. The messages on that inbox contain CSV file attachments and the mailbox currently has 23 messages stored.
tagged with: exchangelib
favorite count: 0
type: Question
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/46804637
answer count: 1
has title: how can I save an attachment using exchangelib
accepted answer: http://stackoverflow.com/a/46804637
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/46882406
has comment: http://stackoverflow.com/comment/80712081
has answer: http://stackoverflow.com/a/46882743
score: 0
has title: Trying to prompt user to enter arithmetic operation and prints value according to operation chosen
answer count: 1
has comment: http://stackoverflow.com/comment/80712033
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80712018
has comment: http://stackoverflow.com/comment/80712196
type: Question
has body: x= int(input("Please enter the value of x: ")) y= int(input("Please enter the value of y: ")) operator = input("Please enter an operator you would like to complete the equation:") if operator &gt; '*': print("The result of the equation is: ", x*y) elif operator &gt; '+': print("The result of the equation is ", x+y) elif operator &gt; '-': print("The result of the equation is", x-y) elif operator &gt; '/': print("The result of the equation is ", x/y) With my block of code, I am trying to get it to where it will take the operator the user inputs and completes the math equation according to what they type, and currently when I run it, it will only complete the equation using multiplication.
tagged with: python

google-app-engine-python
type: Tag
tags question: http://stackoverflow.com/q/46778792
tag name: google-app-engine-python

pants
tag name: pants
type: Tag
tags question: http://stackoverflow.com/q/46784908

http://stackoverflow.com/q/46820609
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/46821197
answer count: 1
downvote count: 0
tagged with: keras
has title: How the Keras steps_per_epoch in fit_generator works
has body: In Keras documentation - steps_per_epoch: Total number of steps (batches of samples) to yield from generator before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of unique samples of your dataset divided by the batch size. I have 3000 samples. If i set steps_per_epoch=3000 it's work slowly. If i set steps_per_epoch=300 it's work faster and i thought that Batch works! But then I compared how much video memory is allocated in the first and second cases. And did not notice a big difference. If I use a simple fit() function then the difference is large. So it's real speed up or i just process 300 examples, instead of 3000? What for this parameter is necessary? And how can I speed up the training? My generator code: def samples_generator(self, path_source, path_mask): while 1: file_paths_x = self.get_files(path_source) file_paths_y = self.get_files(path_mask) for path_x, path_y in zip(file_paths_x, file_paths_y): x = self.load_pixels(path_x, 3, cv2.INTER_CUBIC) y = self.load_pixels(path_y, 0, cv2.INTER_NEAREST) yield (x, y)
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/80692281
type: Comment
comment on: http://stackoverflow.com/a/46872520
has text: Using this modification I get: TypeError: name should be a string, not <class 'sympy.core.symbol.Symbol'>
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80513991
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46770292
has text: my octave function returns an output, as i can see ans in octave-cli like this: octave:1> mytest timeBSeuCallUI = 2.6464e-04 1.5133e+00 NaN relerrBSeuCallUI = 2.7459e-05 6.2769e-05 NaN ans = 2.6464e-04 octave:2> ans ans = 2.6464e-04

http://stackoverflow.com/a/46775682
type: Answer
has body: The BigQuerySource transform used in the Python DirectRunner doesn't automatically determine the locations for temp tables. See BEAM-1909 for the issue. When using the DataflowRunner this should work.
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46753904
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46753904
upvote count: 3

http://stackoverflow.com/q/46887990
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46888138
possible better answer: http://stackoverflow.com/a/57699366
answer count: 2
downvote count: 1
score: 4
favorite count: 0
upvote count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/46888138
has title: How to break from inner loop to the beginning of the outer loop
has body: What's the best way to break from inner loop so I reach beginning of the outer loop while condition: while second_condition: if some_condition_here: get_to_the_beginning_of_first_loop Right now I got something like while condition: while second_condition: if condition1: break if condition1: continue
has answer: http://stackoverflow.com/a/57699366
type: Question

http://stackoverflow.com/comment/80570950
has text: I undertand Python, I had looked up that operator since I haven't used it since learning python and the explanation was very poorly worded. Thanks for clearing that up. I updated the question to show the like button view.
comment on: http://stackoverflow.com/a/46797453
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80596422
score: 0
comment on: http://stackoverflow.com/q/46824226
has text: @ Francesco : Pls see the question. I have edied it with an example of grouped descripiton
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80633138
type: AnswerComment
comment on: http://stackoverflow.com/a/46835183
score: 0
has text: My final code included both your answer and deans. Thank you !!!!
type: Comment

http://stackoverflow.com/comment/80536052
has text: It means that you are trying to add two things that you can't meaningfully add together. Think back to primary school math class. What would you tell the teacher if he/she asked you to add the number 5 to chair? You would probably say the question makes no sense, and you'd be correct. Python is telling you that `self.url` is `None`, it's not there, doesn't exist, and that you're asking it to the equivalent of adding 5 to chair. You need to create it. See @wpercy's answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46794521

http://stackoverflow.com/q/46873354
has comment: http://stackoverflow.com/comment/80694450
tagged with: python
has comment: http://stackoverflow.com/comment/80696193
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80695153
has comment: http://stackoverflow.com/comment/80695017
tagged with: time-series
has comment: http://stackoverflow.com/comment/80694050
linked to: http://stackoverflow.com/q/39515411
has comment: http://stackoverflow.com/comment/80694568
has comment: http://stackoverflow.com/comment/80694493
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80695069
tagged with: pandas
upvote count: 1
has body: This is going be my first question here a stack overflow. I've searched through the forum and found one question which is the exact issue that i am unable to find a solution to. There has been no answer to it though. I've reproduced it here. Any help would be appreciated. What is pandas syntax for lookup based on existing columns + row values? Here is a summary of what's already been done Create a pandas df1 with two columns: 'Date' and 'Price' - done I add two new columns: 'rollmax' and 'rollmin', where the 'rollmax' is an 8 days rolling maximum and 'rollmin' is a rolling minimum. - done Now I need to create another column 'rollmax_date' that would get populated through a look up rule: For the row n, go to the column 'Price' and parse through the values for the last 8 days and find the maximum, then get the corresponding Date and put this value in the column 'rollingmax_date'. The same logic for the 'rollingmin_date', but instead of rolling maximum date, we look for the rolling minimum date. I did the first two and tried the third one, but I'm getting wrong results. The code below gives me only dates where on the same row df["Price"] is the same as df['rollmax'], but it doesn't bring all the corresponding dates from 'Date' to 'rollmax_date' df['rollmax_date'] = df.loc[(df["High"] == df.rollmax), 'Date'] The image as in the Q is below: EDIT: Here are additional inputs as requested. For some reason I am unable to paste a copy of the data frame here. It is a typical data frame of a stock. I have columns as 'Date', 'Open', 'High', 'Close'. The Rollmax and Rollmin have been calculated as above. Now, I need to fill the date of Rollmax and Rollmin in the columns 'Rollmax_date' and 'Rollmin_date' Here's the DataFrame added. This is formatted poorly. Unable to paste this as a table As seen here, the first rollmax is 11872, which occurs on 04th Jan 2011. I am trying to achieve getting this value into the column 'Rollmax_date' df = quandl.get(stock,start_date = start, end_dat…
has comment: http://stackoverflow.com/comment/80694415
favorite count: 0
has title: Pandas syntax for lookup based on existing columns + row values?

http://stackoverflow.com/comment/80666871
type: QuestionComment
has text: Why would anybody *else* be doing anything inside semo_function? And if they are couldn't they just circumvent your protection?
comment on: http://stackoverflow.com/q/46859511
score: 0
type: Comment

http://stackoverflow.com/q/46809141
tagged with: pandas
answer count: 1
has body: I have a pandas dataframe like this: aa bb cc dd ee a a b b foo a b a a foo b a a a bar b b b b bar I want to add a new column if value in columns 1 to 4 is a The results would be like this: aa bb cc dd ee ff a a b b foo a a b a a foo a b a a a bar a b b b b bar b The logic is: if value in any of columns 1 to 4 is a then column ff is a else it's b I can define a function and do each column manually like: def some_function(row); if row['aa']=='a' or row['bb']=='a' or row['cc']=='a' or row[dd]=='a': return 'a' return 'b' But I'm looking for a solution that can scale across n number of columns. Appreciate any help!
favorite count: 0
has comment: http://stackoverflow.com/comment/80565370
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46809177
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/46809177
downvote count: 0
score: 4
has title: Pandas add a new column based on conditional logic of many other columns

http://stackoverflow.com/comment/80649045
type: AnswerComment
comment on: http://stackoverflow.com/a/46835720
type: Comment
has text: My ["good reason"](https://blogs.unity3d.com/2015/01/07/a-primer-on-repeatable-random-numbers/) is that I don't want to have to generate all the data in exactly the same sequence every time. Looking at my example code that I just added - how would you add a "middle name" attribute without all the subsequent people having totally different names for a given random seed?
score: 1

http://stackoverflow.com/comment/80667803
type: Comment
has text: So, from what I'm understanding, when I run ./match.py, I can see the lists from fs and z because the lists are not being initialized in their own files and because match.py is being executed. However, having if __name__ == '__main__' becomes an issue when I try to initialize a list to pass in to another function since match.py is no longer executed? It looks like I just need to first initialize the list in y.py from match.py and just call the function towards the end? Please let me know if I'm totally off my line of thinking....
comment on: http://stackoverflow.com/a/46859986
type: AnswerComment
score: 0

http://stackoverflow.com/a/53526772
type: Answer
score: 3
has body: To expand on Arun's answer, you can set the favicon by customizing the browsable API. That means you create a copy of api.html in your app, and then add a link to your favicon. In this example, I have the following files: my_project my_app static favicon.png templates rest_framework api.html The api.html file looks like this: {% extends "rest_framework/base.html" %} {% block style %} {{ block.super }} &lt;link rel="shortcut icon" type="image/png" href="/static/portal/favicon.png" /&gt; {% endblock %}
answers question: http://stackoverflow.com/q/46842938
downvote count: 0
upvote count: 3

http://stackoverflow.com/a/46835651
score: 0
answers question: http://stackoverflow.com/q/46825440
type: Answer
has body: To my knowledge, there's no way to attach Selenium to an already-running browser. More to the point, why do you want to do that? The only thing I can think of is if you're trying to set up something with the browser manually, and then having Selenium do things to it from that manually-set-up state. If you want your tests to run as consistently as possible, you shouldn't be relying on a human setting up the browser in a particular way; the script should do this itself.
has comment: http://stackoverflow.com/comment/94414730

http://stackoverflow.com/a/46881374
has body: You'll need to add a thread from Tkinter import * import threading class GUIDemo(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createWidgets() # self.datarcv() def createWidgets(self): self.inputText = Label(self) self.inputText["text"] = "Input:" self.inputText.grid(row=0, column=0) self.inputField = Entry(self) self.inputField["width"] = 50 self.inputField.grid(row=0, column=1, columnspan=6) self.regist = Button(self, command=self.datasave_thread) self.regist["text"] = "button" self.regist.grid(row=2, column=0) def datasave_thread(self): self.thread = threading.Thread(None, self.datasave, None, (), {}) self.thread.start() def datasave(self): a=0 while a&lt;100000000: a+=1 print a if __name__ == '__main__': root = Tk() app = GUIDemo(master=root) app.mainloop()
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/80716093
has comment: http://stackoverflow.com/comment/80710009
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46881316
type: Answer
answers question: http://stackoverflow.com/q/46881316
has comment: http://stackoverflow.com/comment/80710500
has comment: http://stackoverflow.com/comment/80710025

http://stackoverflow.com/comment/80490810
score: 1
has text: Softmax in convolutional layers (channels summing 1) is a good idea for image segmentation tasks, where each channel is a class.
type: AnswerComment
comment on: http://stackoverflow.com/a/46771947
type: Comment

opencv3.0
tags question: http://stackoverflow.com/q/46861924
type: Tag
tags question: http://stackoverflow.com/q/46845656
tags question: http://stackoverflow.com/q/46902828
tag name: opencv3.0

http://stackoverflow.com/a/46851968
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80651614
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46851216
has comment: http://stackoverflow.com/comment/80651649
answers question: http://stackoverflow.com/q/46851216
has comment: http://stackoverflow.com/comment/80651489
has body: This code will use python to get the sentiment for any text you enter: import os import json result = json.loads(os.popen('curl -d "text=great" http://text-processing.com/api/sentiment/').read()) print result['label'] However, since "curl is not defined", you need to make sure that you have curl installed. If you are on any operating system, you can install it at https://curl.haxx.se/download.html : simply choose your operating and system and install curl. Once you have curl installed, the above code will work. You can simply change the "text = great" part of the code to whatever text you want. In my example, this code will print out "pos"; if the text was negative, it would print out "neg". Hope this helps!

http://stackoverflow.com/q/46773798
has answer: http://stackoverflow.com/a/46779297
accepted answer: http://stackoverflow.com/a/46779297
tagged with: python
has title: Extract follower numbers from Vkontakte using Python & BeautifulSoup
type: AnsweredQuestion
type: Question
has body: I am trying to extract the follower count from a page on Vkontakte, a Russian social network. As I'm a complete beginner with Python, I have tried using a code I discovered on StackOverflow initially made to extract follower count on Twitter. Here's the original code : from bs4 import BeautifulSoup import requests username='realDonaldTrump' url = 'https://www.twitter.com/'+username r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") f = soup.find('li', class_="ProfileNav-item--followers") print(f) I'm using this webpage as an example : https://vk.com/msk_my. Here is my code : from bs4 import BeautifulSoup import requests url = 'https://vk.com/msk_my' r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") f = soup.find('span', class_="header_count fl_l") print(f) This, and many other variations I've tried (for example, trying to find "div" instead of "span", only prints "None". It seems BeautifulSoup can't find the follower count, and I'm sttruggling to understand why. The only way I've managed to print the follower count is with this : text = soup.div.get_text() print(text) But this prints much more stuff than I want, and I don't know how to get only the follower count.
has comment: http://stackoverflow.com/comment/80493600
tagged with: twitter
score: 0
answer count: 1
tagged with: beautifulsoup

http://stackoverflow.com/q/46886226
accepted answer: http://stackoverflow.com/a/46886506
has comment: http://stackoverflow.com/comment/80720031
answer count: 2
possible better answer: http://stackoverflow.com/a/62245433
has answer: http://stackoverflow.com/a/62245433
downvote count: 0
favorite count: 0
has title: Taylor diagram in python by using skill_metrics
tagged with: python
has answer: http://stackoverflow.com/a/46886506
type: AnsweredQuestion
score: 1
has body: I tried to use skill_metris to create taylor diagram. But I am getting error saying that module 'matplotlib.colors' has no attribute 'to_rgb' example code: import skill_metrics as sm sm.taylor_diagram(0.22,0.52,0.32)
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80719922
upvote count: 1
type: Question

http://stackoverflow.com/q/46836766
has title: Plot ode in python
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46837101
downvote count: 1
tagged with: plot
tagged with: ode
type: Question
score: -1
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
has body: When I compile Python code below import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def f(s,t): a = 20 b = 1 c = 1 d = 3 E = 3 f = 2 g = 3 h = 1 eq0 = S[0] eq1 = s[1] eq2 = S[2] eq3 = s[3] dHs = a-(a+b*eq3)*eq0+c*eq2 dHi = b*eq3*eq0-(a+d+g)*eq1 dHr = d*eq1-(a+c)*eq2 dAs = eq3*(E-E*eq3)-h*eq3 return [dHs, dHi, dHr, dAs] t= np.linspace(0,20) eq0= [20,5] s= odeint(f,s0,t) plt.plot(t,eq[:,0],'r--',Linewidth=2.0) plt.plot(t,eq[:,1],'r--',Linewidth=2.0) plt.plot(t,eq[:,2],'r--',Linewidth=2.0) plt.plot(t,eq[:,3],'r--',Linewidth=2.0) plt show() I get this error, but I dont' know fix this error File "tentativa.py", line 7 b = 1 ^ IndentationError: unindent does not match any outer indentation level

http://stackoverflow.com/comment/114067794
has text: is there a solution that can perform this behavior on a windows machine? It specifically says on a OS that doesn't have the SIGALRM, it won't work.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/58541728

http://stackoverflow.com/a/46882980
has body: EDIT: If need add mising days only to last level days use reindex with unstack + stack: df = df['frequency'].unstack() .reindex(columns=list(range(30)), fill_value=0) .stack() .to_frame('frequency') If need add all combination of all levels: Use by new MultiIndex created by from_product: #get all unique values of all levels a = df.index.get_level_values('enrollment_id').unique() b = df.index.get_level_values('event').unique() c = df.index.get_level_values('days').unique() Or you can use your values in lists like: a = ['access', 'remove'] b = range(1, df.index.get_level_values('event').max() + 1) c = range(30) mux = pd.MultiIndex.from_product([a,b,c], names=df.index.names) #for missing values add 0 df = df.reindex(mux, fill_value=0)
accepted answer of: http://stackoverflow.com/q/46882516
has comment: http://stackoverflow.com/comment/80734707
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/46882516

http://stackoverflow.com/comment/80542344
type: Comment
score: 1
has text: Any compelling reason to not just run the `pytest` command directory instead of using setup.py?
comment on: http://stackoverflow.com/q/46796011
type: QuestionComment

http://stackoverflow.com/a/46827006
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46822892
has body: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html Save an array to a text file. You can, unfortunately, only store a single numeric numpy array in a single file. Whereas your .mat file contains a structure: &gt;&gt; fieldnames(imdb) ans = { [1,1] = dob [2,1] = photo_taken [3,1] = full_path [4,1] = gender [5,1] = name [6,1] = face_location [7,1] = face_score [8,1] = second_face_score [9,1] = celeb_names [10,1] = celeb_id } &gt;&gt; imdb.name(1) ans = { [1,1] = Fred Astaire } It might make sense to convert the data to a numpy dictionary (as described in "Complex matlab-like data structure in python (numpy/scipy)"), and store that as a .csv using How do I convert this list of dictionaries to a csv file? [Python]
answers question: http://stackoverflow.com/q/46822892
score: 1
has comment: http://stackoverflow.com/comment/80605868
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46813987
has body: Redis only support one-level data structures, but you can break the rule using Json. So you could make each inner list a json string, and store this using redis list.
accepted answer of: http://stackoverflow.com/q/46812748
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/46812748
upvote count: 1

http://stackoverflow.com/q/46898256
has answer: http://stackoverflow.com/a/46898277
upvote count: 2
has comment: http://stackoverflow.com/comment/80920162
type: Question
has body: I am trying to take a pandas dataframe and returns a pandas dataframe object after adding the new column 'Size_Category' with value of either small medium or large based on some conditions. mod_df = df.copy(deep=True) mod_df.loc[(mod_df['Length'] &lt;= 300 , 'Size_Category')] = 'small' # condition, new_column mod_df.loc[(mod_df['Length'] &lt;= 300 | mod_df['Length'] &gt; 450) , 'Size_Category')] = 'medium' # condition, new_column mod_df.loc[(mod_df['Length'] &gt;= 450, 'Size_Category')] = 'large' # condition, new_column When I do this, it gives me an error saying The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How can I handle this?
accepted answer: http://stackoverflow.com/a/46898277
has title: Conditioning in pandas
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83724376
type: Comment
has text: you'd keep the `hue` column separate pass it by itself
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46774570

http://stackoverflow.com/comment/80551099
type: Comment
has text: what does `map(str, numbers)` do? I didn't see any `str` variable in your code
comment on: http://stackoverflow.com/a/46802153
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80611437
score: 3
has text: There is old-style formatting, which uses the `%` operator, but it is much less feature rich than using the `.format` method. There is also new (Python 3.6) f-strings.
comment on: http://stackoverflow.com/q/46831964
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46894493
tagged with: pytables
has title: How do I append only the new indices to a table with an HDFS store
linked to: http://stackoverflow.com/q/19325950
has comment: http://stackoverflow.com/comment/80737971
answer count: 1
downvote count: 0
tagged with: hdfs
has body: I am going to be iterating through many data frames to append to a table in an hdfs store. The indices will overlap with each other. I want to append only the rows with indices that aren't already in the store. MCVE Consider my data frames d1 and d2: d1 = pd.DataFrame.from_dict( {('a', 'x'): {'col': 1}, ('a', 'y'): {'col': 1}}, orient='index') d2 = pd.DataFrame.from_dict( {('b', 'x'): {'col': 2}, ('a', 'y'): {'col': 2}}, orient='index') print(d1, '\n\n', d2) col a x 1 y 1 col a y 2 b x 2 I want to accomplish the same logic as the following: d1.append(d2.loc[d2.index.difference(d1.index)]) col a x 1 y 1 b x 2 But I want this for appending to the hdfs store. What I've Tried d1.to_hdf('test.h5', 'mytable', format='table') d2.to_hdf('test.h5', 'mytable', append=True) pd.read_hdf('test.h5', 'mytable') col a x 1 y 1 y 2 b x 2 You can see that the index ('a', 'y') is duplicated with the two different values. I'm assuming there is a way to check the index values in the table prior to appending new rows to the table.
favorite count: 0
tagged with: pandas
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/46894792
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/46894792
type: Question

http://stackoverflow.com/q/46758807
has comment: http://stackoverflow.com/comment/80463598
tagged with: error-handling
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/80463113
has comment: http://stackoverflow.com/comment/80463041
has title: TypeError: 'NoneType' object has no attribute '__getitem__' - although the information is on the website
has body: the code below stops where the error occurs. When accessing the page, the keyword "redzone" is there however, the script doesn't return the results, thus the error in the title. import re import requests from urllib2 import urlopen as uReq from bs4 import BeautifulSoup as soup print "Content-type: text/html\n\n"; print (' <TITLE>Buffalo Streams ') print (' ') print ('<p />') try: my_url = 'https://www.reddit.com/r/NFLStreams/' # opening up connection, grabbing the page uClient = uReq(my_url) page_html = uClient.read() uClient.close() # html parsing page_soup = soup(page_html, 'html.parser') linktwo = 'http://www.reddit.com' linkone = page_soup.find('a', href=True, text=re.compile(r"\b[Rr]edzone\b"))['href'] If I change the (r"\b[Rr]edzone\b") to a sports team name, it works. For some odd reason, this text doesn't return anything value. Why?
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80463091
tagged with: python
has comment: http://stackoverflow.com/comment/80463153
has comment: http://stackoverflow.com/comment/80463617

http://stackoverflow.com/a/46879955
type: Answer
downvote count: 0
score: 1
has body: Assuming that you have an empty DataFrame df with columns, you could access the columns of df as a list with: &gt;&gt;&gt; df.columns Index(['columnA', 'columnB'], dtype='object') .columns will allow you to overwrite the columns of df, but you don't need to pass in another Index. You can pass it a regular list, like so: &gt;&gt;&gt; df.columns = ['columna', 'columnb'] &gt;&gt;&gt; df Empty DataFrame Columns: [columna, columnb] Index: []
upvote count: 1
answers question: http://stackoverflow.com/q/46879672

http://stackoverflow.com/comment/108637101
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55834112
score: 3
has text: The accepted answer still works with the latest version of `Firefox` and `geckodriver`

http://stackoverflow.com/q/46855686
accepted answer: http://stackoverflow.com/a/46855877
has comment: http://stackoverflow.com/comment/80658834
favorite count: 0
answer count: 5
tagged with: python
tagged with: recursion
has answer: http://stackoverflow.com/a/59564330
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46855877
has comment: http://stackoverflow.com/comment/80660345
has answer: http://stackoverflow.com/a/46855785
upvote count: 3
has answer: http://stackoverflow.com/a/46855812
type: Question
has title: Test Recursive Python Function
tagged with: testing
tagged with: mocking
has body: I have a recursive function that I'm looking to test, however I'm having difficulty limiting the recursive call during testing. For example, below is a simple example of a recursive function that calls a bool_function(n) to check if it should break the recursive loop. def factorial(n): if bool_function(n): return 1 else: return n * factorial(n-1) What would be the best way to test or mock bool_function(n) so that it is true for the first iteration and false for any call after?
downvote count: 0
possible better answer: http://stackoverflow.com/a/46856667
has answer: http://stackoverflow.com/a/46856667

http://stackoverflow.com/q/46805623
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/46822872
tagged with: python
has title: Restart postgres connection in django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80560562
tagged with: django
upvote count: 1
tagged with: git
type: Question
has answer: http://stackoverflow.com/a/46822872
has comment: http://stackoverflow.com/comment/80560915
has body: I have very strange situation here. Problem: I describe original problem inside this post, but to sum up: After using the project for a while, makemigrations stop working for me. (Yes I have set everything ok, setting are ok,.. please see my comments on previous post) I decided that I can't figure this out, so I would start fresh. (thats why git is for :D ) So, I delete my django project, I create new virtual environment, and I also create new database and new user in postgres. I update new database parameter inside my config file and try to run initial makemigrations but with no luch. It is still say that no new migrations are available. I am desperate because I can't work on the project, so any solution would do :D (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py makemigrations connectors environment=local I will use local settings. No changes detected in app 'connectors' All my migrations (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py showmigrations environment=local I will use local settings. admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length connectors (no migrations) contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial When lunch migration (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py migrate --fake-initial environment=local I will use local settings. Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. The funny thing is that if I close postgres database, I still get the same text in terminal. I would guess that I should get some connection error. database config yaml database: port: 5432 ho…
linked to: http://stackoverflow.com/q/46789185

http://stackoverflow.com/comment/80746696
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46897380
has text: `fsolve = lambda: [1,2]; a, b = fsolve(); x = fsolve(); print a, b, x`. Compare the values of `a`, `b` and `x`. Is this not exactly the same as what's happening in your code?

http://stackoverflow.com/comment/80658305
type: AnswerComment
type: Comment
has text: @emmaqqq No worries, please accept this answer (click the checkmark) if it solved your problem. Then I can close the question I linked to as a duplicate of this. For your comment, please open a new question and feel free to link it here.
score: 0
comment on: http://stackoverflow.com/a/46816557

http://stackoverflow.com/comment/80750966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46902082
has text: [this](https://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv/39713544#39713544) claims that pyenv is deprecated for 3.6+
score: 0

http://stackoverflow.com/comment/80885389
has text: ...ah...and mentioning ODR is probably a good idea as well....
type: QuestionComment
comment on: http://stackoverflow.com/q/46832659
type: Comment
score: 0

http://stackoverflow.com/comment/80658810
type: QuestionComment
has text: You need some javascript to pick it up and save to the db. I'd go with option 1, instant save to db. You could write your own script and send an AJAX request. Or maybe look at grapelli or django-admin-tools, not sure if they do what you want.
comment on: http://stackoverflow.com/q/46855553
score: 0
type: Comment

http://stackoverflow.com/comment/80749417
type: Comment
has text: Per the comment on the question, you may have been able to remove the `end=''`, which would have ended each print statement with a null rather than an endline. Replacing it with `end="\r"` or `end = '\r'` may also do the trick.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46900669

http://stackoverflow.com/comment/80496670
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46774454
has text: Yes, Python 2.7.12 on Ubuntu 16.04.3.
type: Comment

http://stackoverflow.com/q/46810056
has comment: http://stackoverflow.com/comment/80567339
has body: I have hard typed lots of assignments: definition = ['basename', 'dirname', 'supports_unicode_filenames'] condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] . . . Intend to transform them to dict avoiding repeating typing: {'definition': ['basename', 'dirname', 'supports_unicode_filenames'], 'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] ...} I tried to encapsulate them in class. class OsPath: definition = ['basename', 'dirname', 'supports_unicode_filenames'] condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] Working on console In [125]: dt = dict(vars(OsPath)) In [127]: {i:dt[i] for i in dt if not i.startswith('__')} Out[127]: {'condition': ['isabs', 'isdir', 'isfile', 'islink', 'ismount'], 'definition': ['basename', 'dirname', 'supports_unicode_filenames']} How to do it in shortcut?
has comment: http://stackoverflow.com/comment/80567356
has comment: http://stackoverflow.com/comment/80568114
has comment: http://stackoverflow.com/comment/80567701
score: -1
has title: Transform assignments to dict
answer count: 3
has answer: http://stackoverflow.com/a/46810186
has comment: http://stackoverflow.com/comment/80567925
downvote count: 1
has comment: http://stackoverflow.com/comment/80567239
favorite count: 0
possible better answer: http://stackoverflow.com/a/46810186
has answer: http://stackoverflow.com/a/46810155
accepted answer: http://stackoverflow.com/a/46810155
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47809641
type: Question

http://stackoverflow.com/comment/80670609
score: 0
comment on: http://stackoverflow.com/q/46860457
has text: Funny fact: sum(b[::-1]) is exactly zero. Precision gets lost mainly during calculation -0.628... + 0.533... as a few bits just cancel out, the mantissa bits then are shifted, and the exponent is decreased. The new bits that appear on the right in the mantissa contribute nothing to precision, of course.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46883898
favorite count: 0
linked to: http://stackoverflow.com/q/16905295
has body: I have a test that does the following: create an index on ES using pyes insert mapping insert data query the data to check if it fits the expected result However when I run this test, sometimes it would find no result, and sometimes it would find something but some data is missing. The interesting thing is this only happens when I run the test automatically. If I type in the code ling-by-line, everything works as expected. I've tested it 3 times manually and it works without failure. Sometimes I've even received this message: NoServerAvailable: list index out of range It seems like the index was not created at all I've pinged my ES address and everything looks correct. There was no other error msg found anywhere. I thought it would be because I was trying to get the data too fast after the insert, as documented here: Elastic Search No server available, list index out of range (check first comment in the accepted answer) However, even if I make it delay for 4 seconds or so, this problem still happens. What concerns me is the fact that sometimes only SOME data is missing, which is really strange. I thought it would be either finding it all or missing it all. Anyone got similar experience that can shine some light on this issue? Thanks.
has comment: http://stackoverflow.com/comment/80715499
tagged with: elasticsearch
tagged with: python
has title: Elasticsearch is missing data when querying after insert
has answer: http://stackoverflow.com/a/46884087
has comment: http://stackoverflow.com/comment/80715302
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: pyes
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/80602049
type: AnswerComment
comment on: http://stackoverflow.com/a/46826767
type: Comment
score: 0
has text: This is really slow. If you're working with pandas, these aren't the types of commands you should be giving.

http://stackoverflow.com/q/46768813
has comment: http://stackoverflow.com/comment/80483521
has body: I try to use the multiprocessing tool in python (3.4.2) to speed up my performance. My normal programm is running ok, but I have to process a large and nested dictionary in it. Attached a simplified version, which shows my problem. If I use the TestProc directly it is working, with multiprocessing not. Thanks for your help! import multiprocessing def TestProc(liste, results): for i in liste: results[i] = {'power':{'square': float(i)**2, 'cubic': float(i)**3},'root':{'square': float(i)**(1/2), 'cubic': float(i)**(1/3)}} if __name__ == "__main__": multiprocessing.freeze_support() results = multiprocessing.Manager().dict() results = {} liste = ['1','2','3','4','5'] for i in liste: results[i] = multiprocessing.Manager().dict() print(results) #TestProc(liste, results) p1 = multiprocessing.Process(target=TestProc, args=(liste,results,)) p1.start() p1.join() print(results)
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46779687
score: 0
upvote count: 1
downvote count: 1
has title: python multiprocessing nested dictionay
tagged with: multiprocessing
type: Question

http://stackoverflow.com/comment/81085763
type: Comment
has text: i am sorry but if i replace my code with your code, it makes the program run step 0 for like 500 times, i tried this "nested for" like this too but the result was just like the program run step 0 for many times. did i misplace the code for batch section?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46905232

http://stackoverflow.com/comment/80608325
has text: With 'targetip' I mean for example 192.1.1.1. I update it in the code. Thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46767853
score: 0

http://stackoverflow.com/comment/80686277
comment on: http://stackoverflow.com/q/46869500
has text: ok that fix worked out... so if you could post that as an answer I can mark it as accepted.
score: 0
type: Comment
type: QuestionComment

qpushbutton
type: Tag
tag name: qpushbutton
tags question: http://stackoverflow.com/q/46811610

http://stackoverflow.com/comment/80469630
score: 0
type: Comment
has text: @BruceMartin your cb2xml library worked with the file concerned (to get it to XML) - thank you very much. I will look to the other files I have. I am reading hexdumps from the isam files and bringing them into a RDBMS.
type: QuestionComment
comment on: http://stackoverflow.com/q/46750954

http://stackoverflow.com/a/46851576
type: Answer
has body: This answer is dedicated to answering: How can I give Two Arguments to the key of sort? The old style compare way to sort is gone in Python 3, as in Python 2 you would do: def sorted_by(a,b): # logic here pass boxes.sort(cmp=sorted_by) But if you must use it Python 3, it’s still there, but in a module, functools, it’s purpose is to convert the cmp to key: import functools cmp = functools.cmp_to_key(sorted_by) boxes.sort(key=cmp) The preferred way to sort is to make a key function that returns a weight for the sorting to base on. See Francisco’s answer.
answers question: http://stackoverflow.com/q/46851479
score: 20
upvote count: 20
downvote count: 0

http://stackoverflow.com/q/46869918
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46874820
score: 1
has title: Websocket listen continuously after receiving response in tornado
tagged with: tornado
type: Question
has answer: http://stackoverflow.com/a/46874820
answer count: 1
downvote count: 0
tagged with: websocket
upvote count: 1
has body: I'm working on a websocket client listening to a tornado server. Once the client receives a message from server, the client is exiting silently. Following is the code I've implemented. #!/usr/bin/python import tornado.websocket from tornado import gen import requests @gen.coroutine def test_ws(): client = yield tornado.websocket.websocket_connect("ws://localhost:8888/subscribe/ports") msg = yield client.read_message() print(msg) if __name__ == "__main__": loop = tornado.ioloop.IOLoop() loop.run_sync(test_ws) The client is running until it receives the first message from server. But I want to run indefinitely. Am I missing something?
tagged with: python

http://stackoverflow.com/comment/80537189
score: 0
type: Comment
has text: I get the whole code now. Thank you for your support. I really appreciate it.
comment on: http://stackoverflow.com/a/46789668
type: AnswerComment

http://stackoverflow.com/comment/80612363
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46832451
has text: What version of Ubuntu are you on?

http://stackoverflow.com/comment/80683178
type: AnswerComment
score: 0
type: Comment
has text: The comparison can also be done with `array1[:2] == array2[:2]`.
comment on: http://stackoverflow.com/a/46867849

http://stackoverflow.com/comment/80647298
type: Comment
has text: The production runs the same code as locally, I have checked my code line by line, even other fields like user, email, and link from TaggedArticle models are displaying in list view for TaggedArticles in Django admin but not displaying in Detail view, is it possible that the issue may be from DB side as i;m using PostgreSQL on production?
score: 0
comment on: http://stackoverflow.com/q/46848912
type: QuestionComment

http://stackoverflow.com/a/46865366
accepted answer of: http://stackoverflow.com/q/46865266
has body: You can use re.sub: mesh = "Adrenergic beta-Antagonists/*therapeutic use, Adult, Aged, Aged/*effects, Antihypertensive Agents/*therapeutic use, Blood Glucose/*drug effects, Celiprolol/*therapeutic use, Female, Glucose Tolerance Test, Humans, Hypertension/*drug therapy, Male, Middle Aged, Prospective Studies" import re s = re.sub("\/\*[\w\s]+", '', mesh) final_string = [] for i in re.split(",", s): if i not in final_string: final_string.append(i) new_final_string = ', '.join(final_string) print(new_final_string) Output: 'Adrenergic beta-Antagonists, Adult, Aged, Antihypertensive Agents, Blood Glucose, Celiprolol, Female, Glucose Tolerance Test, Humans, Hypertension, Male, Middle Aged, Prospective Studies'
answers question: http://stackoverflow.com/q/46865266
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80678207
has comment: http://stackoverflow.com/comment/80678306
score: 4
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/46791913
tagged with: jenkins
type: UnansweredQuestion
has title: Kafka timing out because of Docker latency
tagged with: python
has comment: http://stackoverflow.com/comment/80555750
downvote count: 0
has answer: http://stackoverflow.com/a/46806101
score: 1
type: Question
tagged with: apache-kafka
has answer: http://stackoverflow.com/a/46813003
tagged with: docker
answer count: 2
has comment: http://stackoverflow.com/comment/80535941
upvote count: 1
favorite count: 0
has body: I am totally new to Kafka and Docker, and have been handed a problem to fix. Our Continuous Integration tests for Kafka (Apache) queues run just fine on local machines, but when on the Jenkins CI server, occasionally fail with this sort of error: %3|1508247800.270|FAIL|art#producer-1| [thrd:localhost:9092/bootstrap]: localhost:9092/bootstrap: Connect to ipv4#127.0.0.1:9092 failed: Connection refused %3|1508247800.270|ERROR|art#producer-1| [thrd:localhost:9092/bootstrap]: localhost:9092/bootstrap: Connect to ipv4#127.0.0.1:9092 failed: Connection refused %3|1508247800.270|ERROR|art#producer-1| [thrd:localhost:9092/bootstrap]: 1/1 brokers are down The working theory is that the Docker image takes time to get started, by which time the Kafka producer has given up. The offending code is producer_properties = { 'bootstrap.servers': self._job_queue.bootstrap_server, 'client.id': self._job_queue.client_id } try: self._producer = kafka.Producer(**producer_properties) except: print("Bang!") with the error lines above appearing in the creation of the producer. However, no exception is raised, and the call returns an otherwise valid looking producer, so I can't programmatically test the presence of the broker endpoint. Is there an API to check the status of a broker?

currency
tag name: currency
tags question: http://stackoverflow.com/q/46797070
type: Tag

http://stackoverflow.com/a/46795688
upvote count: 1
answers question: http://stackoverflow.com/q/46793919
has comment: http://stackoverflow.com/comment/80548596
downvote count: 0
has body: Have you tried to explicitly declare q as global in your listener and RealTrEventHandler class? E.g.: class listener(mp.Process): global q def __init__(self): mp.Process.__init__(self) self.q=q Another way of passing variables between (at least) threads is using the buildins-module, but I'm not sure if multiprocessing is so much different.
type: Answer
score: 1

http://stackoverflow.com/q/46851780
has comment: http://stackoverflow.com/comment/80651500
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/80651152
favorite count: 0
has title: Python define and call function represented by string
has answer: http://stackoverflow.com/a/46852244
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80650979
tagged with: python
has comment: http://stackoverflow.com/comment/80651281
has comment: http://stackoverflow.com/comment/80651815
has body: Assume that we have a string function_string = 'def main():\n\treturn(1)' How can this be compiled as a function during runtime and then be executed? This is my current attempt, unfortunately it raises a NameError expressing that main is not defined: self.run(): exec(self.formatted_function_string) # similar to 'function_string' in the example print(main())
has comment: http://stackoverflow.com/comment/80654360
downvote count: 3
linked to: http://stackoverflow.com/q/2220699
type: Question
tagged with: function
tagged with: runtime
has comment: http://stackoverflow.com/comment/80651177
tagged with: compilation
score: -3
has comment: http://stackoverflow.com/comment/80651016
linked to: http://stackoverflow.com/q/1186789
upvote count: 0

http://stackoverflow.com/comment/80576079
has text: Have you tried dif = np.array([dY(y,x) for y in res])`?
comment on: http://stackoverflow.com/q/46812671
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46787851
type: Question
has comment: http://stackoverflow.com/comment/80523228
has answer: http://stackoverflow.com/a/46787938
accepted answer: http://stackoverflow.com/a/46787938
has body: In Django, is there a way (function) to test if a model field is primary key (pk)? For instance, my model is: class Gender(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name Is there a function to test for name being primary key?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: model
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/80521902
score: 1
has title: Is there any function in Django that tests if a field instance of a model is primary key?

http://stackoverflow.com/q/46887939
upvote count: 4
has answer: http://stackoverflow.com/a/47472416
has title: Sourcing Anaconda activate script vs. adding the Anaconda bin directory to PATH
tagged with: bash
type: AnsweredQuestion
downvote count: 0
tagged with: shell
favorite count: 0
accepted answer: http://stackoverflow.com/a/47472416
tagged with: linux
type: Question
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/80723157
tagged with: anaconda
has body: I would like to move to Anaconda Python as my default Python environment. In order to use Anaconda over the system Python I have been looking at the following two options: Adding the Anaconda bin path to my bash PATH variable (in my .bashrc) so that the Anaconda binaries take precedence over those elsewhere on the system. Sourcing the Anaconda activate script in my bash shell (again, automated by adding it to my .bashrc). As someone who is relatively new to Anaconda Python, I'm not sure which of the two approaches is generally considered as better. Therefor I was wondering if there is any general guidance in this regard? As far as I can work out the main difference between the two approaches is that the activate script sets up a number of additional shell environment variables such as: CONDA_PREFIX, PS1, CONDA_PS1_BACKUP and CONDA_DEFAULT_ENV.
answer count: 1

http://stackoverflow.com/comment/80710278
has text: Does the file `C:\Python36\python_bible\nlp_class\all_book_titles.txt` exist?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46881525

http://stackoverflow.com/comment/80448985
score: 0
type: Comment
has text: No, you needn't to modify the source code. You can just create a new file which include `from tweepy import API` and your `CustomAPI`. Then you can replace `from tweepy import API` with `from your_file import CustomAPI as API` to use your `CustomAPI`. Also, in this case you just override these two functions, others are not changed at all. I will update my answer to make it more explicit.
type: AnswerComment
comment on: http://stackoverflow.com/a/46750888

http://stackoverflow.com/comment/80492982
type: Comment
score: 0
has text: The first thing I see is that you are not telling `pack()` where to pack each widget. This will result in the widgets just being placed underneath the last widget that was packed with no arguments. So you will need to specify where to pack with `side=LEFT` or other directions. There are several good tutorials out there on how to use `pack()` and `grid()`. I prefer using `grid()` for an application like this one.
type: QuestionComment
comment on: http://stackoverflow.com/q/46773499

http://stackoverflow.com/comment/80504869
comment on: http://stackoverflow.com/q/46779359
type: QuestionComment
has text: Scripts usually take input in the form of parameters or read from stdin. Scripts should output to stdout. If you update your script to work this way you can use https://nodejs.org/api/child_process.html.
type: Comment
score: 1

http://stackoverflow.com/comment/80601938
comment on: http://stackoverflow.com/a/46825883
has text: I did it, but when I want to execute other methods like "sc.textFile(path)", as I don't have a 'sc' object (SparkContext object), if I try to run "spark.textFile(path)" I get the error: 'SparkSession' object has no attribute 'textFile'.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/80445089
has text: `np.where(A == element)`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46749486
type: QuestionComment

http://stackoverflow.com/comment/83661416
has text: uninstall spacy and try pip3 install spacy==2.0
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46887236

http://stackoverflow.com/comment/80736016
score: 0
has text: @SardorbekImomaliev have you got the same format as i mentioned above mean to say i have another solution for that but formatting is not correct in that solution like the whole text appears in one line etc.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46893770

http://stackoverflow.com/q/46870304
tagged with: data-structures
favorite count: 0
has body: The following code is used to apply a function across all the members of an object "nspace". The nspace contains a list of more nspaces, with a dimension variable reduced by 1. An nspace with dimension=1 is a list of "None"s. Is it possible to vectorize this function? def __call__(self, func): if self.dimension == 1: for i in range(self.size): self.list[i,] = func(self.list[i,]) else: for i in self.list: i(func) nspace's structure: nspace(3,3)=[nspace(2,3), nspace(2,3), nspace(2,3)] nspace(2,3)=[nspace(1,3), nspace(1,3), nspace(1,3)] nspace(1,3)=[None, None, None] nspace(2,4)=[nspace(1,4), nspace(1,4), nspace(1,4), nspace(1,4)]
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/80688371
type: UnansweredQuestion
upvote count: 1
tagged with: vectorization
has comment: http://stackoverflow.com/comment/80688704
tagged with: recursion
score: 1
has title: Vectorization of a complex object python
type: Question
downvote count: 0

http://stackoverflow.com/a/46840431
type: Answer
has body: You could create an array instead I would assume. However, the indenting is due to how Python's syntax works. If you put the numbers inside an array, the indenting does not matter, but I would advice sticking to PEP8 style conventions.
answers question: http://stackoverflow.com/q/46840382
score: 0

http://stackoverflow.com/comment/80731007
has text: In your example Text file exists no DOCID string, please clarify what you mean with DOCID.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46891862

http://stackoverflow.com/comment/80470234
comment on: http://stackoverflow.com/a/46762480
score: 0
type: AnswerComment
has text: I understand, however, I'm trying to find a div with a certain text like ` 2017-10-21 ` then tell the script to grab all `<a href>` tags in the sub divs of `2017-10-21`.
type: Comment

http://stackoverflow.com/a/46768904
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/80483922
has comment: http://stackoverflow.com/comment/80484743
answers question: http://stackoverflow.com/q/46766714
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46766714
has body: TSNE is a heuristic. Like most heuristics, it might behave quite differently according to small changes. The core characteristic here is: only local-convergence is guaranteed! (not very robust). The latter is indicated (follows from basic optimization-theory) in the docs: t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results. While you explained, that the non-seeding approach is not the culprit in your opinion (hard to measure! benchmarking is hard), you should check out your versions of sklearn, as the t-sne code is one of the more active parts of sklearn with many changes over time. Each of these changes is likely to introduce observations like yours (when only trying one example; a bigger benchmark/testset should be a better approach when comparing t-sne implementations of course) Remark: however one of the computers keeps getting better results: this is broad as there are at least two different interpretations: rate the result visually / perceptually look at kl_divergence_ achieved after optimization

http://stackoverflow.com/a/46881138
has body: You can try this. Each match is a set. You have list of sets and then filter them by your criteria, count the sets. s1 = frozenset(['a','b','c','x','y','z']) s2 = frozenset(['a','y','z','k','m','o']) s3 = frozenset(['c','x','a','k','l','m']) def find_common_matches(first_player, second_player, *sets): return sum(1 for x in frozenset(*sets) if first_player in x and second_player in x) lst = [s1, s2, s3] count = find_common_matches('a', 'c',lst) print(count)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46876060

http://stackoverflow.com/q/46798652
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46798828
type: Question
tagged with: numpy
tagged with: arrays
tagged with: tuples
answer count: 2
has comment: http://stackoverflow.com/comment/80544456
has title: Appending a tuple to a np array returns a list of scalars instead of tuples
tagged with: pandas
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/46798741
has answer: http://stackoverflow.com/a/46798741
accepted answer: http://stackoverflow.com/a/46798828
tagged with: python
has body: I'm trying to create a numpy array of tuples, but the resulting np array contains scalars instead of tuples. I have: log_df = pd.read_csv(file_name) nod_intervals = np.array([]) for index, row in log_df.iterrows(): if row['gesture'] == 'Nod' and row['label'] == 'y': nod_intervals = np.append(nod_intervals, (row['start'], row['end'])) print nod_intervals The result is: [ 700072. 711071. 1123467. 1133810. 1799492. 1810464. 3861590. 3871927. 4124862. 4135798. 5097266. 5107561. 5392353. 5402949. 5528955. 5539925. 6056021. 6066913. 6730803. 6741807.] As you can see, these are scalars, not tuples. What am I doing wrong?
type: AnsweredQuestion

command-line-interface
tags question: http://stackoverflow.com/q/46759490
tag name: command-line-interface
type: Tag
tags question: http://stackoverflow.com/q/46765803

http://stackoverflow.com/q/46759563
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80465167
has title: Accessing nested elements with beautifulsoup
upvote count: 1
tagged with: html-parsing
type: Question
has comment: http://stackoverflow.com/comment/80464993
has comment: http://stackoverflow.com/comment/80464802
has comment: http://stackoverflow.com/comment/80465406
answer count: 2
has answer: http://stackoverflow.com/a/46765274
downvote count: 0
has answer: http://stackoverflow.com/a/46759891
favorite count: 0
has body: I have the following html: Mailing Address 500 ORACLE PARKWAY MAIL STOP 5 OP 7 REDWOOD CITY CA 94065 I am trying to access "500 ORACLE PARKWAY" and "MAIL STOP 5 OP &", but I cannot find a way to do it. My attempt was this: for item in soup.findAll("span", {"class" : "mailerAddress"}): if item.parent.name == 'div': return_list.append(item.contents) Edit: I forgot to mention that there are elements after that in the html that use similar tags so it captures all of those when I just want the first two. Edit: link: https://www.sec.gov/cgi-bin/browse-edgar?CIK=orcl
tagged with: beautifulsoup

http://stackoverflow.com/q/46834347
tagged with: matplotlib
has title: Matplotlib/Basemap figure size different when generated in script versus imported function
has comment: http://stackoverflow.com/comment/80658682
type: Question
has comment: http://stackoverflow.com/comment/80622725
has comment: http://stackoverflow.com/comment/80621275
has comment: http://stackoverflow.com/comment/80659645
score: 0
has comment: http://stackoverflow.com/comment/80659524
has body: I have a script that makes a basic map and then exports the figure to a png file: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt def basic_map(): ##geographic boudning/projection info lon_0 = -119.610686 lat_0 = 37.246066 llcrnrlon = -129.409591 llcrnrlat = 30.034156 urcrnrlon = -109.131211 urcrnrlat = 43.009518 fig = plt.figure(figsize=(7205 / 600, 4308 / 600), dpi=600) ax = fig.add_axes([0.001, 0.001, .999, .999]) m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, \ resolution='l', lon_0=lon_0, lat_0=lat_0, projection='aea' \ ,ellps='GRS80', lat_1=llcrnrlat, lat_2=urcrnrlat,ax=ax) m.drawcountries() m.drawstates() m.drawcoastlines() ax.axis('off') f = 'somewhere.png' plt.savefig(f, dpi=600, bbox_inches='tight', pad_inches=0) basic_map() When I run the script above it returns a png file with dimensions of 5358 × 4310 pixels (600 dpi). However, if import the nearly identical file (see below) as a module and then run the basic_map() function it returns a png file of size 1685 × 1356 pixels (600 dpi), i.e. ~3x smaller than original dimensions: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt def basic_map(): ##geographic boudning/projection info lon_0 = -119.610686 lat_0 = 37.246066 llcrnrlon = -129.409591 llcrnrlat = 30.034156 urcrnrlon = -109.131211 urcrnrlat = 43.009518 fig = plt.figure(figsize=(7205 / 600, 4308 / 600), dpi=600) ax = fig.add_axes([0.001, 0.001, .999, .999]) m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, \ resolution='l', lon_0=lon_0, lat_0=lat_0, projection='aea' \ ,ellps='GRS80', lat_1=llcrnrlat, lat_2=urcrnrlat,ax=ax) m.drawcountries() m.drawstates() m.drawcoastlines() ax.axis('off') f = 'somewhere.png' plt.savefig(f, dpi=600, bbox_inches='tight', pad_inches=0) I then import this as a module and run the function: import File as F F.basic_map() Neither the script or the imported module/function report error…
tagged with: python
has comment: http://stackoverflow.com/comment/80622917
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/80659623
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80632162
tagged with: save
has comment: http://stackoverflow.com/comment/80636479
has comment: http://stackoverflow.com/comment/80659819
has comment: http://stackoverflow.com/comment/80659247
has comment: http://stackoverflow.com/comment/80659190

http://stackoverflow.com/a/46776212
has comment: http://stackoverflow.com/comment/80498060
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46776110
answers question: http://stackoverflow.com/q/46776110
has body: You can use the shlex.split function to preserves spaces inside quotes.

opencv
type: Tag
tags question: http://stackoverflow.com/q/46857433
tags question: http://stackoverflow.com/q/46859115
tags question: http://stackoverflow.com/q/46776280
tags question: http://stackoverflow.com/q/46837658
tags question: http://stackoverflow.com/q/46849668
tags question: http://stackoverflow.com/q/46775869
tags question: http://stackoverflow.com/q/46761067
tags question: http://stackoverflow.com/q/46861199
tags question: http://stackoverflow.com/q/46861924
tags question: http://stackoverflow.com/q/46803465
tags question: http://stackoverflow.com/q/46779690
tags question: http://stackoverflow.com/q/46838984
tags question: http://stackoverflow.com/q/46895772
tags question: http://stackoverflow.com/q/46866121
tags question: http://stackoverflow.com/q/46873911
tags question: http://stackoverflow.com/q/46804380
tags question: http://stackoverflow.com/q/46779891
tags question: http://stackoverflow.com/q/46804954
tags question: http://stackoverflow.com/q/46775284
tags question: http://stackoverflow.com/q/46851275
tags question: http://stackoverflow.com/q/46899994
tags question: http://stackoverflow.com/q/46854330
tags question: http://stackoverflow.com/q/46769913
tag name: opencv
tags question: http://stackoverflow.com/q/46866586
tags question: http://stackoverflow.com/q/46891359
tags question: http://stackoverflow.com/q/46762963
tags question: http://stackoverflow.com/q/46845648
tags question: http://stackoverflow.com/q/46844444
tags question: http://stackoverflow.com/q/46824478
tags question: http://stackoverflow.com/q/46881087
tags question: http://stackoverflow.com/q/46788883
tags question: http://stackoverflow.com/q/46863047
tags question: http://stackoverflow.com/q/46822226
tags question: http://stackoverflow.com/q/46755932
tags question: http://stackoverflow.com/q/46883245
tags question: http://stackoverflow.com/q/46829975
tags question: http://stackoverflow.com/q/46763121
tags question: http://stackoverflow.com/q/46876388
tags question: http://stackoverflow.com/q/46873757
tags question: http://stackoverflow.com/q/46838913
tags question: http://stackoverflow.com/q/46808404
tags question: http://stackoverflow.com/q/46764711
tags question: http://stackoverflow.com/q/46795669
tags question: http://stackoverflow.com/q/46881346
tags question: http://stackoverflow.com/q/46751105
tags question: http://stackoverflow.com/q/46848869
tags question: http://stackoverflow.com/q/46893885
tags question: http://stackoverflow.com/q/46879245
tags question: http://stackoverflow.com/q/46825504
tags question: http://stackoverflow.com/q/46815492
tags question: http://stackoverflow.com/q/46864915
tags question: http://stackoverflow.com/q/46796276
tags question: http://stackoverflow.com/q/46789896
tags question: http://stackoverflow.com/q/46821936
tags question: http://stackoverflow.com/q/46764494
tags question: http://stackoverflow.com/q/46890602
tags question: http://stackoverflow.com/q/46787124
tags question: http://stackoverflow.com/q/46800380
tags question: http://stackoverflow.com/q/46768506
tags question: http://stackoverflow.com/q/46872431

http://stackoverflow.com/q/46902966
favorite count: 0
has comment: http://stackoverflow.com/comment/80785653
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django
has body: I am having some trouble with connection errors in my Django app when a user navigates to a different page before AJAX call is finished. So, when the client-side sends several AJAX calls for save/load/retrieve data etc., and when a user navigates to a different page - say when an AJAX call was just made from the client side to save the content, the content is saved and the functionally everything is fine, but I keep getting this error: Exception happened during processing of request from ('127.0.0.1', 50646) Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\socket.py", line 594, in write return self._sock.send(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\site-packages\…
score: 1
type: Question
has comment: http://stackoverflow.com/comment/80753164
linked to: http://stackoverflow.com/q/18040898
has comment: http://stackoverflow.com/comment/80753219
downvote count: 0
has comment: http://stackoverflow.com/comment/80753086
has comment: http://stackoverflow.com/comment/80753110
has title: Connection errors due to webpage navigation
has comment: http://stackoverflow.com/comment/80757929
tagged with: ajax
has comment: http://stackoverflow.com/comment/80785673
has comment: http://stackoverflow.com/comment/80752917
tagged with: python
tagged with: connection

http://stackoverflow.com/a/46872476
downvote count: 0
has body: Simply pass x into the solver function as a parameter. This way you are not relying on global variables. The code for doing this may look something like: from sympy.solvers import nsolve from sympy import Symbol def solver(I, x): return nsolve(x-3*(1-2.73**-x), I, verify=False) i_min=-51 i_max=100 z=0 x = Symbol('x') for i in range(i_min,i_max): y=z z=solver(i, x) if y!=z: continue print(z)
has comment: http://stackoverflow.com/comment/80692449
upvote count: 2
has comment: http://stackoverflow.com/comment/80692243
has comment: http://stackoverflow.com/comment/80692602
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/80692570
answers question: http://stackoverflow.com/q/46872398

http://stackoverflow.com/comment/80668497
type: Comment
score: 1
has text: You've answered the question, shown code and outputs, and simultaneously shown just because one can does not mean one should. Challenge accomplished!
comment on: http://stackoverflow.com/a/46827604
type: AnswerComment

http://stackoverflow.com/q/46868725
tagged with: python-3.6
has body: I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below: getUsrName = input("Enter username: ") file = open("documents/pytho/login/cdat.txt", "r") lines = file.readlines() recievedUsrName = lines[1] file.close() print(getUsrName) print(recievedUsrName) if recievedUsrName == getUsrName: print("hello") elif getUsrName != recievedUsrName: print("bye") else:
answer count: 1
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/80684698
type: UnansweredQuestion
has title: Issue with conditional statement on external python file
tagged with: python
has comment: http://stackoverflow.com/comment/80684995
downvote count: 1
tagged with: file.readalllines
has answer: http://stackoverflow.com/a/46868769
type: Question
has comment: http://stackoverflow.com/comment/80684679
upvote count: 0

http://stackoverflow.com/comment/80460841
comment on: http://stackoverflow.com/q/46751635
has text: @KlausD. , I'm open to either method of getting this to work.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80628160
type: QuestionComment
has text: An empty products list { orders: [{ products: [] }] }
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46839977

http://stackoverflow.com/comment/80580714
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46796204
type: Comment
has text: Updated my earlier answer with an implementation using `DictWriter` as part of a `DoFn` and `PTransform` :)

http://stackoverflow.com/q/46842005
upvote count: 3
has body: First, I did a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]] b = pd.DataFrame(a) print(b.head(2)) The output is 1 2 3 4 5 6 6 5 4 3 2.00 NaN 1 2 3 4 5.00 6.00 3 4 5 6 NaN NaN So I did a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]] b = pd.DataFrame(a).fillna(-1).astype(int) print(b.head(2)) The output becomes 1 2 3 4 5 6 6 5 4 3 2 -1 1 2 3 4 5 6 3 4 5 6 -1 -1 But I don't want those -1, so I did a = [[6,5,4,3,2],[1,2,3,4,5,6],[3,4,5,6]] b = pd.DataFrame(a).fillna(-1).astype(int) b = b.replace(-1, np.NaN) print(b.head(2)) The output is again same as the first time 1 2 3 4 5 6 6 5 4 3 2.00 NaN 1 2 3 4 5.00 6.00 3 4 5 6 NaN NaN
has answer: http://stackoverflow.com/a/46842213
type: Question
has comment: http://stackoverflow.com/comment/80631765
linked to: http://stackoverflow.com/q/21287624
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46842213
favorite count: 0
has comment: http://stackoverflow.com/comment/80631929
tagged with: python
type: AnsweredQuestion
score: 3
has title: Replacing integers with NaN results in the entire column becoming float dtype

http://stackoverflow.com/a/46843735
has comment: http://stackoverflow.com/comment/80635499
downvote count: 0
has comment: http://stackoverflow.com/comment/80636164
has comment: http://stackoverflow.com/comment/80635151
has comment: http://stackoverflow.com/comment/80635412
type: Answer
upvote count: 1
has body: I think in the GetProductionTotals(), it should return json.loads(data) instead of json.dumps(data) since json.dumps returns a string while json.loads returns back json from the string passed to it.
has comment: http://stackoverflow.com/comment/80635272
score: 1
has comment: http://stackoverflow.com/comment/80636369
has comment: http://stackoverflow.com/comment/80641075
answers question: http://stackoverflow.com/q/46843619
has comment: http://stackoverflow.com/comment/80635872
has comment: http://stackoverflow.com/comment/80642775
has comment: http://stackoverflow.com/comment/80635934
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80634936
accepted answer of: http://stackoverflow.com/q/46843619
has comment: http://stackoverflow.com/comment/80642127
has comment: http://stackoverflow.com/comment/80642030
has comment: http://stackoverflow.com/comment/80642232
has comment: http://stackoverflow.com/comment/80641779

http://stackoverflow.com/q/46895192
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/80737531
type: Question
has answer: http://stackoverflow.com/a/46895270
type: AnsweredQuestion
score: 1
has title: convert a string with parenthesis to an integer- %d format: a number is required, not str'
upvote count: 1
answer count: 1
has body: I'm new to Python. I'm trying to insert a formula into an excel column. The inputs to the formula do not necessarily come from one row. I have- formula= '=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2' formulaRegex= re.compile(r'([A-Z]+)(\d{1,})') cellCoordinatesR= formulaRegex.findall(formula) #find a Cap. Letter and a number rowIndex=[] #list of the row indexes i.e '4' in 'B4' and '2' in 'D2' for group in cellCoordinatesR: rowIndex.append(group[1]) rowIndexFormat= '('+','.join(rowIndex)+')' # add parenthesis to rowIndex list '(4,4,4,2)' newFormula= formulaRegex.sub(r'\1%d',formula) %rowIndexFormat Error: '%d format: a number is required, not str' What I want: newFormula= formulaRegex.sub(r'\1%d',formula) %(4,4,4,2) What I currently have: newFormula= formulaRegex.sub(r'\1%d',formula) %'(4,4,4,2)' I found a way with this: newFormula= formulaRegex.sub(r'\1%d',formula) % (int(rowIndex[0]),int(rowIndex[1]), int(rowIndex[2]), int(rowIndex[3])) '=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2' But it requires that I have int(rowIndex[i]) as many times as necessary. How can I have %d in such a way that I don't have to type int(rowIndex[i]) so many times?
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/46895270
downvote count: 0

http://stackoverflow.com/comment/80687849
type: AnswerComment
type: Comment
has text: OP mentions that they have an existing dict, and that should somehow come into the picture (I can't say for sure because of the poor wording).
score: 0
comment on: http://stackoverflow.com/a/46870277

http://stackoverflow.com/comment/80519280
score: 0
type: AnswerComment
has text: It sounds like what you're wanting to do would require another instance of python. I don't think it's feasible to run two scripts in parallel like that. There maybe a way to add some kind of "event listener", but that may not be trivial.
comment on: http://stackoverflow.com/a/46776694
type: Comment

http://stackoverflow.com/comment/80638780
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46835245
has text: As mentioned, by using `free -m`. I did not measure the memory used by the process. I measured the occupied memory by any process.
score: 0

http://stackoverflow.com/comment/80675612
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46864077
has text: I am not agree with marking this post as duplicated because it is related to ```numpy.array``` and not to the ```list```. And, yes, you could check identity with ```numpy.all(your_array == your_array[0])```
type: Comment

http://stackoverflow.com/q/46814477
type: AnsweredQuestion
has body: using python, pandas I have a dataframe with three columns and about a million rows. The third column contains strings. I want to select a subset of these strings that match the strings in a list and put them in a fourth column. Here is an example of a string from the dataframe: "BW - Jl 8 '79 - pE2 CCB-B -vl9-Ja '66-p83 LJ - v91 - Ja 15 -66 - p426 NYRB - v5 - D 9 '65 - p39 NYTBR - v70 - N 21 '65 - p60 Nat R - vl7 - D14 '65-pll65 y" Here is a sample of my list: ['AAA', 'A Anth', 'AAPSS-A', 'A Anth', 'A Arch', 'A Art', 'AB', 'ABA Jour', 'ABC', 'ABR', 'AC', 'ACSB', 'Adult L', 'Advocate', 'AE', 'AER', 'AF', 'Africa T', 'Afterimage', 'Aging', 'AH', 'AHR', 'A Hy R', 'AIQ', 'AJA', 'AJES', 'AJMD', 'AJMR', 'AJP', 'A J Psy', 'AJS', 'AL', 'A Lead', 'A Lib', 'Am', 'Am Ant', 'Am Arts', 'Am Craft', 'Amer R', 'Am Ethol', 'Am Film', 'Am Mus Teach', 'Am Q', 'Ams', 'Am Sci', 'Am Spect', 'Am Threat', 'Analog', 'ANQ', 'ANQ:QJ', 'Ant &amp; Col Hob', 'Antiq', 'Antiq J', 'Ant R', 'Apo', 'APR', 'APSR', 'AR', 'ARBA', 'Arch', 'Archt R', 'ARG', 'Armchair Det', 'Art Am', 'Art Bull', 'Art Dir', 'Art J', 'Art N', 'AS', 'ASBYP', 'Aspen A', 'Aspen J', 'ASR', 'Astron', 'Ath J', 'Atl', 'Atl Pro Bk R', 'Atl PBR', 'Aud', 'AW', 'BALF', 'Ballet N', "Barron's", 'BAS', 'BB', 'B&amp;B', 'BC', 'BCM', 'B Ent', 'Belles Let', 'BF', 'BFYC', 'B Hor', 'BHR', 'BIC', 'Biography', 'BksW', 'Bks for Keeps', 'Bks for YP', 'BL', 'Bloom Rev'] From the string in the dataframe, I want to select 'BW', 'CCB-B', 'LJ', 'NYRB', 'NYTRB', and 'Nat R', (all of which are in the list) and put them in a new column in the same row. My code looks like this: s = df65['Review'].str.extractall(reviews_list).squeeze() s = s.unstack(level=-1) df65['Reviews'] = s But extractall doesn't take lists as arguments in this way. Help?
tagged with: list
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/46814655
answer count: 1
has title: match strings in list and DF column and put into new DF column
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/46814655
tagged with: python

http://stackoverflow.com/q/46769776
has comment: http://stackoverflow.com/comment/80485487
tagged with: python
has comment: http://stackoverflow.com/comment/80484906
has body: i have an excel file with 2 columns: A B 1 COLUMN 1 COLUMN 2 2 21,177.5 22,775.19 3 10,512.41 19.641.59 4 5.19 11.53 if value A2 >= B2: return ('OK') else: return ('Verify') Example output after run: line 2 - 'OK' line 3 - 'OK' line 4 - 'Verify' I am new in python and i don't how could i do this simple thing... i just know csv module, but don't works with an excel file. Thanks.
answer count: 0
type: UnansweredQuestion
tagged with: excel
type: Question
score: 0
has comment: http://stackoverflow.com/comment/80485736
has title: Compare values excel: 2 columns with python

http://stackoverflow.com/a/46804915
has comment: http://stackoverflow.com/comment/82391255
score: 5
has body: According to Summer Fang's comment, I want to show the way how moving the window outside of the loop works for me: test_img = np.zeros(shape=(height,width,3)).astype('uint8') cv2.imshow('image',test_img) cv2.moveWindow('image',200,200) cv2.waitKey(1) while true: (...) img = cv2.imread('test.jpg', cv2.IMREAD_COLOR) cv2.imshow('image',img) (...)
accepted answer of: http://stackoverflow.com/q/46804380
answers question: http://stackoverflow.com/q/46804380
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/80621542
has text: Which version of Python? d.items() only works in version 3+
type: QuestionComment
comment on: http://stackoverflow.com/q/46836864
type: Comment
score: 1

http://stackoverflow.com/comment/80736631
comment on: http://stackoverflow.com/q/46894751
type: Comment
type: QuestionComment
has text: Is this `R` or Python?
score: 0

sockets
tags question: http://stackoverflow.com/q/46846766
tags question: http://stackoverflow.com/q/46856137
tags question: http://stackoverflow.com/q/46787160
tags question: http://stackoverflow.com/q/46880362
tags question: http://stackoverflow.com/q/46775320
tags question: http://stackoverflow.com/q/46852824
tags question: http://stackoverflow.com/q/46790250
tags question: http://stackoverflow.com/q/46805399
tags question: http://stackoverflow.com/q/46855865
tags question: http://stackoverflow.com/q/46860663
tags question: http://stackoverflow.com/q/46834567
tags question: http://stackoverflow.com/q/46751804
tags question: http://stackoverflow.com/q/46782505
tags question: http://stackoverflow.com/q/46859006
tags question: http://stackoverflow.com/q/46809972
type: Tag
tags question: http://stackoverflow.com/q/46835945
tags question: http://stackoverflow.com/q/46894768
tags question: http://stackoverflow.com/q/46808877
tags question: http://stackoverflow.com/q/46841062
tags question: http://stackoverflow.com/q/46898336
tags question: http://stackoverflow.com/q/46754943
tags question: http://stackoverflow.com/q/46836616
tags question: http://stackoverflow.com/q/46815868
tags question: http://stackoverflow.com/q/46869323
tags question: http://stackoverflow.com/q/46780638
tag name: sockets
tags question: http://stackoverflow.com/q/46905201
tags question: http://stackoverflow.com/q/46751438
tags question: http://stackoverflow.com/q/46900044
tags question: http://stackoverflow.com/q/46814272
tags question: http://stackoverflow.com/q/46770278

http://stackoverflow.com/q/46774028
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46774136
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80493743
score: 2
has title: uppered dna transcription with for loop
type: Question
has body: This is the code I have to achieve my objective as stated in the title. The problem I seem to have right now is the second line of code. The moment I added it the program stopped working without giving me an error. Thanks in advance for the help. seqDNA = input() seqDNA = seqDNA.upper() comp = '' for c in seqDNA: if c == 'a': comp = comp + 'u' elif c == 't': comp = comp + 'a' elif c == 'g': comp = comp + 'c' elif c == 'c': comp = comp + 'g' print(comp)
tagged with: for-loop
tagged with: dna-sequence

http://stackoverflow.com/comment/80707416
type: Comment
has text: Have minimal experience using `python`. You `POST` data to server using `data: { imgBase64: dataURL }`, though `"imgBase64"` does not appear at `python` code?
comment on: http://stackoverflow.com/a/46879881
type: AnswerComment
score: 0

http://stackoverflow.com/q/46873766
has comment: http://stackoverflow.com/comment/80694586
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/46873806
score: -1
has body: I was watching explore python. It had an example: &gt;&gt;&gt; d1 = {'name': 'ethan', 'books': ['book1', 'book2', 'book3']} &gt;&gt;&gt; d2 = d1.copy() &gt;&gt;&gt; d2['name'] = 'peter' &gt;&gt;&gt; d2 {'books': ['book1', 'book2', 'book3'], 'name': 'peter'} &gt;&gt;&gt; d1 {'books': ['book1', 'book2', 'book3'], 'name': 'Ethan'} Is a dict not a value-key object? Why it said the value of name is an immutable object, so the properties of d1 will not change.
answer count: 2
accepted answer: http://stackoverflow.com/a/46873806
has answer: http://stackoverflow.com/a/46873804
has title: Why is the attribute of dict immutable object, and the list in it is mutable object
favorite count: 0
linked to: http://stackoverflow.com/q/30188560
possible better answer: http://stackoverflow.com/a/46873804
has comment: http://stackoverflow.com/comment/80694582
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80694542

http://stackoverflow.com/q/46853839
has title: Python code not creating tables on the database but able to query the results postgres
tagged with: python
score: 2
has body: My usecase is to write create a temp table in the postgres database and fetch records from it and insert into a different table. The code i used is: import psycopg2 import sys import pprint from __future__ import print_function from os.path import join,dirname,abspath import xlrd import os.path newlist = [] itemidlist = [] def main(): conn_string = "host='prod-dump.cvv9i14mrv4k.us-east-1.rds.amazonaws.com' dbname='ebdb' user='ebroot' password='*********'" # print the connection string we will use to connect # print "Connecting to database" % (conn_string) # get a connection, if a connect cannot be made an exception will be raised here conn = psycopg2.connect(conn_string) # conn.cursor will return a cursor object, you can use this cursor to perform queries cursor = conn.cursor() dealer_id = input("Please enter dealer_id: ") group_id = input("Please enter group_id: ") scriptpath = os.path.dirname('__file__') filename = os.path.join(scriptpath, 'Winco - Gusti.xlsx') xl_workbook = xlrd.open_workbook(filename, "rb") xl_sheet = xl_workbook.sheet_by_index(0) print('Sheet Name: %s' % xl_sheet.name) row=xl_sheet.row(0) from xlrd.sheet import ctype_text print('(Column #) type:value') for idx, cell_obj in enumerate(row): cell_type_str = ctype_text.get(cell_obj.ctype, 'unknown type') #print('(%s) %s %s' % (idx, cell_type_str, cell_obj.value)) num_cols = xl_sheet.ncols for row_idx in range(0, xl_sheet.nrows): # Iterate through rows num_cols = xl_sheet.ncols id_obj = xl_sheet.cell(row_idx, 1) # Get cell object by row, col itemid = id_obj.value #if itemid not in itemidlist: itemidlist.append(itemid) # execute our Query ''' cursor.execute(""" if not exists(SELECT 1 FROM model_enable AS c WHERE c.name = %s); BEGIN; INSERT INTO model_enable (name) VALUES (%s) END; """ %(itemid,itemid)) ''' cursor.execute("drop table temp_mbp1") try: cursor.execute("SELECT p.model_no, pc.id as PCid, g.id AS GROUPid into public.temp_mbp1 FROM products p, \ model_enable me, products_clients pc, groups g…
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/80655508
type: Question
has comment: http://stackoverflow.com/comment/80655198
tagged with: database
has answer: http://stackoverflow.com/a/46853934
tagged with: postgresql
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: create-table

http://stackoverflow.com/q/46850934
has body: I have some dataframe in Pandas: 1 2 a .2 a .3 b .5 I would like to add, for each of those records, a column with hour (from 0 to 23), so it will look like 1 2 3 a .2 0 a .2 1 a .2 2 ... a .2 23 a .3 0 a .3 1 ... a .3 23 b .5 0 ... b .5 23
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/80650470
answer count: 2
has answer: http://stackoverflow.com/a/46851119
accepted answer: http://stackoverflow.com/a/46851119
has title: How do I "enrich" every record in a Pandas dataframe with an hour column?
tagged with: pandas
downvote count: 1
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/46851042
has answer: http://stackoverflow.com/a/46851042
has comment: http://stackoverflow.com/comment/80649318
has comment: http://stackoverflow.com/comment/80649380
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/80728416
type: Comment
type: QuestionComment
score: 1
has text: In the first post you linked, the question is about creating a sentence vector. i.e. combine the word vectors to a single vector representing the sentence (or paragraph). That is where the question about how to combine the vectors seems to be most relevant. Is that what you want to do?
comment on: http://stackoverflow.com/q/46889727

url
tags question: http://stackoverflow.com/q/46770755
tags question: http://stackoverflow.com/q/46778655
tags question: http://stackoverflow.com/q/46831200
tag name: url
tags question: http://stackoverflow.com/q/46761219
tags question: http://stackoverflow.com/q/46875933
tags question: http://stackoverflow.com/q/46889366
type: Tag

http://stackoverflow.com/comment/80662980
score: 0
type: QuestionComment
type: Comment
has text: 5th line: should be negative(k+1)
comment on: http://stackoverflow.com/q/46857541

http://stackoverflow.com/comment/80718866
has text: Shouldn't an implemetation of __radd__ also be added here? Also, in the case of 1 + 2 + 3, is the implementation (1.__add__(2)).__add__(3) or 1.__add__(2.__add__(3))?
score: 2
comment on: http://stackoverflow.com/a/46885719
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46780690
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11556958
has title: Flask textarea to Python Def()
has answer: http://stackoverflow.com/a/46783761
has comment: http://stackoverflow.com/comment/80509791
duplicate of: http://stackoverflow.com/q/11556958
downvote count: 1
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/80507645
score: 4
tagged with: flask
accepted answer: http://stackoverflow.com/a/46783761
answer count: 1
favorite count: 0
has body: Essentially what I am trying to do : I have a simple HTML page with a Textarea to input a bunch of text, my use case is a single code on each line like below: 1234 5678 1456 etc. Ideally I want to take that into Python and be able to work with the data and return the results. So lets start simple and say take each line as a separate entry and run it against a function to add the word "Hi" in front of it So the results are: Hi 1234 Hi 5678 etc. So far have this working example I found but I tend to break it anytime I try something. Html: Enter some text Hello World! Python: From flask import Flask, request app = Flask(__name__) @app.route('/') def main_form(): return ' Hello World! ' @app.route('/submit', methods=['POST']) def submit_textarea(): return "You entered: {}".format(request.form["text"]) if __name__ == '__main__': app.run() Example : i try to extract the textarea to a string and then return that back to the page with : x = format(request.form["text"]) return x Any help or guidance would be appreciated!
tagged with: python

http://stackoverflow.com/q/46797973
type: Question
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/46798334
answer count: 1
has title: Django: Problems changing the current language
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I want to change the current language of my page. I'm using this HTML code to make the buttons: {% csrf_token %} {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} {{ language }} {{ language.name_local }} {% endfor %} I have no problems when I'm switching from Spanish 'es' to US English 'en-us' but when I try to switch from US English to Spanish send me this error: Not Found: /i18n/setlang/-us/
tagged with: django-templates

http://stackoverflow.com/comment/80497776
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46773837
has text: Ok, so is the input file (gps log) is in csv format? And you're trying to get that into a sqlite db?

http://stackoverflow.com/comment/80776204
has text: All console's preferences are stored in a file inside your domain : ${DOMAIN_HOME}/servers/AdminServer/data/console/ConsolePreferences.xml You can write a wlst script that will update this file to meet your needs.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46848859

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/46902082
tag name: linux-mint

http://stackoverflow.com/q/46819239
score: 0
upvote count: 1
downvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/46819458
has answer: http://stackoverflow.com/a/46819504
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46819458
tagged with: python
linked to: http://stackoverflow.com/q/4998629
has answer: http://stackoverflow.com/a/46819414
answer count: 4
accepted answer: http://stackoverflow.com/a/46819414
has title: How to split a string on multiple conditions
has answer: http://stackoverflow.com/a/46819581
tagged with: list
has comment: http://stackoverflow.com/comment/80586016
type: AnsweredQuestion
tagged with: split
has body: I have a bunch of strings of the format "Initials - Month - Year" which i want to split. However, the exact format is not consistent due to user input. Some examples: 'AA-JAN17' 'AA- JAN 17' 'AA-JAN-17' 'AA - JAN - 17' 'AA - 01 - 2017' What I want is ['AA', 'JAN', '17']. Converting 01 to JAN or 2017 to 17 is trivial. I can split on a hyphen and remove spaces by doing st = 'AA-JAN-17' list = [s.strip() for s in st.split('-')] which will work, except for the first and second example where there is no hyphen between month and year. I could probably split on both letters/numbers and on the hyphen but I'm not sure how to do this. This could probably be done with regex but I'm not familiar with that at all. I accept that there are any number of ways the string could be entered but if there's something that can work for all the examples above then that will be good enough for most cases.
type: Question

web-services
type: Tag
tag name: web-services
tags question: http://stackoverflow.com/q/46784976

http://stackoverflow.com/comment/80685891
comment on: http://stackoverflow.com/q/46869343
type: Comment
type: QuestionComment
has text: `Failed to build` errors tend to appear because of the `gcc` and `g++` compilers in my experience. Upgrading these and installing `cython` might help.
score: 0

http://stackoverflow.com/comment/80698030
score: 0
type: AnswerComment
type: Comment
has text: And yes, there's certainly no problem with passing in the data in chunked fashion (since it's being operated on chunks anyways) and having small intermediate strings that are thrown away. The main issue was having something that does exactly this--keeps partial multi-byte sequences as state for decoding the next chunk. I could have rolled something like this myself but I felt like there had to be something built-in...
comment on: http://stackoverflow.com/a/46865661

http://stackoverflow.com/q/46757079
answer count: 1
has answer: http://stackoverflow.com/a/46757111
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80459444
tagged with: python
has comment: http://stackoverflow.com/comment/80459450
has comment: http://stackoverflow.com/comment/80459438
type: Question
has body: when I run my program which finds the inverse permutation of numbers, it returns me with the follow error: python inverse_permutation.py 1 2 3 4 5 File "inverse_permutation.py", line 18 else: ^ SyntaxError: invalid syntax Prior to asking this question I tried looking at similar posts, but could not find a solution to my specific problem. Here is my code: import stdarray import stdio import sys q = input().split() for i in range(len(q)): q[i] = int(q[i]) l = len(q) s = int((l*(l+1))/2-(l)) s2 = 0 b = [0 for i in range(l)] for i in range(l): s2 = s2+q[i] if(s == s2): for i in range(l): b[q[i]] = i print(b) else: print('Not a permutation')
has title: python program syntax error on `else:`
score: 0

http://stackoverflow.com/a/47940527
upvote count: 1
score: 0
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46757761
has body: Your headers are wrong: "bfx-nonce": nonce,"bfx-apikey": self.api, "bfx-signature": signature

http://stackoverflow.com/comment/80484386
has text: What's your tolerance for false negatives (i.e. throwing out good data)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46762597
score: 0

http://stackoverflow.com/a/46777178
type: Answer
has body: You can try this: import itertools AD= ['3,7', '6,7', '17,16', '16,23', '9,10'] final = list(map(int, itertools.chain.from_iterable([b.split(",") for b in AD]))) Output: [3, 7, 6, 7, 17, 16, 16, 23, 9, 10] If you want to conserve the original pairs: import re AF=['0.27, 0.56', '0.24, 0.06', '0.44, 0.35'] final_data = [tuple(map(float, re.split(",\s*", i))) for i in AF] Output: [(0.27, 0.56), (0.24, 0.06), (0.44, 0.35)]
answers question: http://stackoverflow.com/q/46777123
has comment: http://stackoverflow.com/comment/80503726
has comment: http://stackoverflow.com/comment/80499987
has comment: http://stackoverflow.com/comment/80500043
has comment: http://stackoverflow.com/comment/80503465
has comment: http://stackoverflow.com/comment/80499964
score: 0

http://stackoverflow.com/comment/80693502
has text: The idea was to pass any function as a parameter and get index to work with.
comment on: http://stackoverflow.com/a/46869938
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/46961512
has body: The issue seems to be because the LinearClassifier.train method expects the inputs as a batch and the code is calling: ex = tf.parse_single_example(next_elem, features=spec) This will work if you change the input_fn to iterator = dataset.batch(2).make_one_shot_iterator() next_batch = iterator.get_next() ex = tf.parse_example(next_batch, features=spec)
has comment: http://stackoverflow.com/comment/104120658
downvote count: 0
has comment: http://stackoverflow.com/comment/80917405
upvote count: 2
answers question: http://stackoverflow.com/q/46816469
type: Answer
score: 2

http://stackoverflow.com/comment/80568074
type: Comment
comment on: http://stackoverflow.com/a/46771805
has text: What you say now is much clearer. The original statement "python is using doubles, you're using floats" isn't clear enough. If you had have said "Python is using C doubles for its floats, and double double for its double's I would have understood what you meant, but the original statement is ambiguous. Python is using floats for floats, but is its own version of float not C's version of float. Do you see what I'm getting at?
score: 0
type: AnswerComment

http://stackoverflow.com/q/46877437
type: Question
score: 0
answer count: 1
has body: How can I display both the smallest and largest on a single plot. My current code is this: import matplotlib.pyplot as plt smallest = lsoas.sort_values('imd_score').head(10) largest = lsoas.sort_values('imd_score').head(10) f, ax = plt.subplots(1, figsize=(6, 6)) lsoas.plot(facecolor='black', linewidth=0.025, ax=ax) smallest.plot(alpha=1, facecolor='red', linewidth=0, ax=ax) largest.plot(alpha=1, facecolor='blue', linewidth=0, ax=ax) ax.set_axis_off() f.suptitle('Areas with smallest population') plt.axis('equal') plt.show() but this only shows the largest.
has title: how to display largest and smallest in python
tagged with: python
has answer: http://stackoverflow.com/a/46877466
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46877466
tagged with: matplotlib

http://stackoverflow.com/q/46849949
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/46850353
has body: Is there a way to make a NxN array (so 2d array) of elements, where each element is an array of 3 numbers randomly chosen between 0 and 1? Output should look something like this: (0.2,0.45,0.98), (0.7,0.58,0.11) ... (1.0,0.05,0.63, ... . . . etc. I've been trying to do this but there must be a more elegant way. Code included below: import numpy as np import matplotlib.pyplot as plt lat = [] for _ in range(2): w = [] for _ in range(2): a = np.random.uniform(0.0,1.0) b = np.random.uniform(0.0,1.0) c = np.random.uniform(0.0,1.0) D = np.array([a,b,c]) w.append(D) lat.append(w) if _ &gt;= 1: np.hstack(lat)
favorite count: 0
has answer: http://stackoverflow.com/a/46849996
has answer: http://stackoverflow.com/a/46850353
tagged with: python
type: AnsweredQuestion
has title: Make a NxN array of 1x3 arrays of random numbers (python)
upvote count: 2
accepted answer: http://stackoverflow.com/a/46849996
type: Question
tagged with: 2d
answer count: 2
tagged with: random
score: 2
tagged with: matrix

http://stackoverflow.com/comment/80501879
score: 1
has text: I use a regular loop. Especially for expanding it is [more efficient](https://stackoverflow.com/a/45654731/2285236) anyway.
comment on: http://stackoverflow.com/q/46777910
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56505078
has body: In OpenCV 3.3 load() is replaced by read() save() is replaced by write()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46873728
score: 1
upvote count: 1

http://stackoverflow.com/q/46749147
linked to: http://stackoverflow.com/q/32655874
type: UnansweredQuestion
tagged with: google-api
has comment: http://stackoverflow.com/comment/80445419
has title: How can I get the body of an email with Python and Google's gmail API?
score: 1
type: Question
has comment: http://stackoverflow.com/comment/80444376
tagged with: gmail-api
has body: I just started up with APIs and figured I'd play around with Gmail's. I'm looking to scrape all emails sent to me in the past month for some text analysis. I might just be being thick here or have missed some documentation somewhere (probably), but I can't figure out how to get the body of emails that had attachments. I'm not interested in the attachment, just the body of the email. results = gmail.users().messages().list(labelIds=['INBOX'], q='to:me after: '+str(date),userId='me').execute() mssg_list = results['messages'] for mssg in mssg_list: m_id = mssg['id'] message = gmail.users().messages().get(userId='me', id=m_id).execute() body = message['payload']['parts'][1]['body'] final_body = base64.urlsafe_b64decode(body['data'].decode("utf-8")) For messages with attachments, it returns only attachmentId and size, rather than size and data. I tried reading the attachmentId to see if perhaps data was kept there instead, but no dice; it appears to just refer to the attachment. Where is the actual text body living?
upvote count: 1
tagged with: email
tagged with: python
favorite count: 0
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/80444423

http://stackoverflow.com/comment/80493959
comment on: http://stackoverflow.com/q/46769933
has text: Can you run htop(or taskmanager under windows) to see if Mathematica & Python are using all the cores(minus hyper threading)? Are you using a dense or a sparse matrix in Mathematica?
score: 0
type: Comment
type: QuestionComment

header
type: Tag
tags question: http://stackoverflow.com/q/46828207
tag name: header

http://stackoverflow.com/q/46804149
answer count: 1
has comment: http://stackoverflow.com/comment/80555238
has comment: http://stackoverflow.com/comment/80555842
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: While conversion, invalid literal for float
downvote count: 1
type: Question
has body: I'm trying to train my own data on the Yolo network, but before that I have to convert the bounding boxes co-ordinates to the form it wants. The file contents are like this: 0 53 19 163 116 and I'm trying to convert it to the form the network works with the following. The code is: import os from os import walk, getcwd from PIL import Image classes = ["stopsign"] def convert(size, box): dw = 1./size[0] dh = 1./size[1] x = (box[0] + box[1])/2.0 y = (box[2] + box[3])/2.0 w = box[1] - box[0] h = box[3] - box[2] x = x*dw w = w*dw y = y*dh h = h*dh return (x,y,w,h) """------------------------------------------------------------------- """ """ Configure Paths""" mypath = "/home/decentmakeover2/BBox-Label-Tool/Labels/002/" outpath = "/home/decentmakeover2/output/" cls = "stopsign" if cls not in classes: exit(0) cls_id = classes.index(cls) wd = getcwd() list_file = open('%s/%s_list.txt'%(wd, cls), 'w') """ Get input text file list """ txt_name_list = [] for (dirpath, dirnames, filenames) in walk(mypath): txt_name_list.extend(filenames) break print(txt_name_list) """ Process """ for txt_name in txt_name_list: #txt_file = open("Labels/stop_sign/001.txt", "r") """ Open input text files """ txt_path = mypath + txt_name print("Input:" + txt_path) txt_file = open(txt_path, "r") lines = txt_file.read().split('\r\n') #for ubuntu, use "\r\n" instead of "\n" """ Open output text files """ txt_outpath = outpath + txt_name print("Output:" + txt_outpath) txt_outfile = open(txt_outpath, "w") """ Convert the data to YOLO format """ ct = 0 for line in lines: #print('lenth of line is: ') #print(len(line)) #print('\n') if(len(line) &gt;= 2): ct = ct + 1 print(line + "\n") elems = line.split(' ') print(elems) xmin = elems[0] xmax = elems[2] ymin = elems[1] ymax = elems[3] # img_path = str('%s/images/%s/%s.JPEG'%(wd, cls, os.path.splitext(txt_name)[0])) #t = magic.from_file(img_path) #wh= re.search('(\d+) x (\d+)', t).groups() im=Image.open(img_path) w= int(im.size[0]) h= int(im.size[1]) #w = i…
score: -1
has answer: http://stackoverflow.com/a/46804363
upvote count: 0

http://stackoverflow.com/q/46844135
has comment: http://stackoverflow.com/comment/80635884
score: 0
has comment: http://stackoverflow.com/comment/80639503
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: i am not able to install scipy library using pip and get the error Collecting scipy Using cached scipy-0.19.1.tar.gz Installing collected packages: scipy Running setup.py install for scipy ... error Complete output from command "c:\users\ayush ghai\appdata\local\programs\python\python36\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\AYUSHG~1\\AppData\\Local\\Temp\\pip-build-61f5db76\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\AYUSHG~1\AppData\Local\Temp\pip-p2803zdd-record\install-record.txt --single-version-externally-managed --compile: Note: if you need reliable uninstall behavior, then install with pip instead of using `setup.py install`: - `pip install .` (from a git repo or downloaded source release) - `pip install scipy` (last SciPy release on PyPI) lapack_opt_info: lapack_mkl_info: libraries mkl_rt not found in ['c:\\users\\ayush ghai\\appdata\\local\\programs\\python\\python36\\lib', 'C:\\', 'c:\\users\\ayush ghai\\appdata\\local\\programs\\python\\python36\\libs'] NOT AVAILABLE openblas_lapack_info: c:\users\ayush ghai\appdata\local\programs\python\python36\lib\site-packages\numpy\distutils\system_info.py:655: UserWarning: Specified path c:\opt\64\lib is invalid. return self.get_paths(self.section, key) libraries libopenblas_v0.2.20_mingwpy not found in [] NOT AVAILABLE atlas_3_10_threads_info: Setting PTATLAS=ATLAS libraries tatlas,tatlas not found in c:\users\ayush ghai\appdata\local\programs\python\python36\lib libraries lapack_atlas not found in c:\users\ayush ghai\appdata\local\programs\python\python36\lib libraries tatlas,tatlas not found in C:\ libraries lapack_atlas not found in C:\ libraries tatlas,tatlas not found in c:\users\ayush ghai\appdata\local\programs\python\python36\libs libraries lapack_atlas not found in c:\users\ayush ghai\appdata\local\programs\python\python36\libs &lt;class 'numpy.distu…
tagged with: python
has title: error installing scipy using pip on windows 10
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80653468
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/28190534
has answer: http://stackoverflow.com/a/46982798
accepted answer: http://stackoverflow.com/a/46982798

http://stackoverflow.com/q/46799198
has body: I am quite new with python and I try to replace the elements of a list with x given the specific list has the same elements. For example: list =[1,2,3,4,5,6,7,8,9] a = [1,4,7,9] The list should become like: list =[x,2,3,x,5,6,x,8,x]
has comment: http://stackoverflow.com/comment/80545393
tagged with: python-2.7
score: 0
has title: Replacement of element in a list of python
has answer: http://stackoverflow.com/a/46799294
downvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46799276
possible better answer: http://stackoverflow.com/a/46799294
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46799276
upvote count: 1

http://stackoverflow.com/a/46869936
score: 0
has body: This is just a cleaned up version of your code: from mcpi.minecraft import Minecraft import time mc = Minecraft.create() pos = mc.player.getTilePos() x = pos.x + 1 y = pos.y z = pos.z def stack(delay, block, direction): for count in range(10) if direction == 1 else range(9, -1, -1): print(count) mc.setBlock(x, y + count, z, block) time.sleep(delay) stack(0, 20, 1) stack(0.5, 22, 1) stack(0.5, 20, -1)
type: Answer
answers question: http://stackoverflow.com/q/46869332

http://stackoverflow.com/comment/80701836
comment on: http://stackoverflow.com/q/46877482
score: 0
type: Comment
type: QuestionComment
has text: is Pair a list or a string?

http://stackoverflow.com/comment/80445883
comment on: http://stackoverflow.com/q/46749826
type: Comment
type: QuestionComment
has text: @RoryDaulton no, I understand, it is the typical parlance of imperative programming. They still teach this :) I was trying to say that the question wasn't properly specified, but at first glance, I didn't realize that these strings were simply the alphabet interwoven. Now what the assignment was getting at is obvious enough.
score: 0

http://stackoverflow.com/comment/80695678
score: 0
type: QuestionComment
has text: @importanceOfBeingErnest ok I edited it now
type: Comment
comment on: http://stackoverflow.com/q/46873801

http://stackoverflow.com/a/46793745
accepted answer of: http://stackoverflow.com/q/46792631
answers question: http://stackoverflow.com/q/46792631
type: Answer
downvote count: 0
score: 1
has body: Try the below script and tell me it didn't fix the issue. I used conditional statement to avoid any error supposed to happen if any item is none, as in the second result where price is none. Now it works great. import requests ; from bs4 import BeautifulSoup url = "https://hbx.com/categories/sneakers" soup = BeautifulSoup(requests.get(url).text,"lxml") for item in soup.find_all(class_="product-box"): name = item.find(class_="name").text if item.find(class_="name") else "" brand = item.find(class_="brand").text if item.find(class_="brand") else "" price = item.find(class_="regular-price").text if item.find(class_="regular-price") else "" print(name,brand,price) Or with find_all if you like. However, the result are always the same. for item in soup.find_all(class_="product-box"): name = item.find_all(class_="name")[0].text if item.find_all(class_="name") else "" brand = item.find_all(class_="brand")[0].text if item.find_all(class_="brand") else "" price = item.find_all(class_="regular-price")[0].text if item.find_all(class_="regular-price") else "" print(name,brand,price) Partial result: Club C 85 Reebok USD 75.00 NMD R2 Runner Primeknit Adidas Originals NMD R2 Runner Adidas Originals USD 155.00
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/80630212
score: 0
type: QuestionComment
type: Comment
has text: I am going to use this data to create a prediction model.
comment on: http://stackoverflow.com/q/46841117

http://stackoverflow.com/a/46870985
has body: You just need to encode the hello string before you write it to a file (csv). Otherwise Python is expecting you to input only ascii characters, in case of non-ascii characters, you may use utf-8 encoding as: # -*- coding: utf-8 -*- import csv with open("test.csv", 'w') as csvfile: csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) hello = u'привет, мир!' # Better way of declaring a unicode string literal csvfile.writerow([hello.encode("utf-8")])
answers question: http://stackoverflow.com/q/46870929
has comment: http://stackoverflow.com/comment/80689324
score: 0
has comment: http://stackoverflow.com/comment/80693635
has comment: http://stackoverflow.com/comment/80701247
has comment: http://stackoverflow.com/comment/80693629
has comment: http://stackoverflow.com/comment/80689464
has comment: http://stackoverflow.com/comment/80689331
has comment: http://stackoverflow.com/comment/80689457
has comment: http://stackoverflow.com/comment/80689405
type: Answer
has comment: http://stackoverflow.com/comment/80689458

http://stackoverflow.com/a/46801432
has body: Imagine fetch function was read only (for example in other library), then you'd have to imap over an intermediate function. pool.imap(lambda (u,f): fetch(u, f), zip(dlList, dlFList)) but since you can control the mapping function, change it to accept a tuple of url and filename. def fetch(t): url, filename = t urllib.request.urlretrieve(url, filename) return t pool.imap(fetch, zip(dlList, dlFList)) Don't feel like tupling? Make filename calculable from url, for example, via dictionary lookup or string processing. url_filename_map = dict(zip(dlList, dlFList)) # or build dict some other way def fetch(url): filename = url_filename_map[url] # or filename = '/path/prefix/' + hashlib.md5(url).hexdigest() urllib.request.urlretrieve(url, filename) return url, filename pool.imap(fetch, url_filename_map) # same as imap(fetch, urlmap.keys())
score: 0
answers question: http://stackoverflow.com/q/46780981
type: Answer

http://stackoverflow.com/a/46820133
type: Answer
has comment: http://stackoverflow.com/comment/80597777
answers question: http://stackoverflow.com/q/46819586
has comment: http://stackoverflow.com/comment/80615573
score: 1
upvote count: 1
has body: This is one solution: idt = [item for item in range(len(mylist)) if mylist[item][1] == u'DT'] jdt = [item for item in range(len(mylist)) if mylist[item][1] == u'IN'] ij = zip(idt,jdt) temp_list = [mylist[i[0]+1:i[1]] for i in ij] new_list = [str(elem[0][0]+ ' ' + elem[1][0]) for elem in temp_list] It first finds the indices of u'DT' and u'IN' in mylist, then it zips them together into a list of tuples, ij. Each tuple is the beginning and end of the interval from which the program is supposed to extract values. The values are first extracted as they appear in mylist into temp_list. Last step forms the target new_list that joins and processes extracted values stored in temp_list. This solution does not give you values within brackets ( ) - it seems that to achieve this, elements of new_list would either have to be turned into tuples, i.e. ('Satisfactory tracing',) or the bracket would have to be part of the string '(Satisfactory tracing)'. Edit - solution for any number of strings between DT and IN - everything until new_list is the same, new_list is formed by extracting first element from each element in the sublist of temp_list and joining them into one string, new_list = [((' ').join(map(lambda x: x[0], sub_el))) for sub_el in temp_list] Testing with mylist = [('a', u'DT'), ('Satisfactory', u'JJ'), ('Satisfactory', u'JJ'), ('tracing', u'VBG'),('with', u'IN'),('a', u'DT'),('fairly', u'RB'), ('persistent', u'JJ'),('with', u'IN'), ('a', u'DT'),('persistent', u'JJ'), ('with', u'IN')] yields ['Satisfactory Satisfactory tracing', 'fairly persistent', 'persistent']
has comment: http://stackoverflow.com/comment/80617754
has comment: http://stackoverflow.com/comment/80614440
downvote count: 0

http://stackoverflow.com/q/46786327
has answer: http://stackoverflow.com/a/46786570
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46788010
has answer: http://stackoverflow.com/a/46786424
has comment: http://stackoverflow.com/comment/80519094
type: Question
has answer: http://stackoverflow.com/a/73706615
accepted answer: http://stackoverflow.com/a/46786424
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80519024
has answer: http://stackoverflow.com/a/46787339
has answer: http://stackoverflow.com/a/71718993
has comment: http://stackoverflow.com/comment/80519062
has body: I try to sort my list using two algorithms of sort: bubble and quick. For this purpose i use algorithms module and bubble_sort , quick_sort respectively. As I know complexity of first algorithm is n^2 and second is n*log(n). But i get unexpected output from this code: from algorithms.sorting import bubble_sort, quick_sort import time my_list = [1, 12, 33, 14, 52, 16, 71, 18, 94] start1 = time.time() for i in range(1000000): bubble_sort.sort(my_list) end1 = time.time() start2 = time.time() for i in range(1000000): quick_sort.sort(my_list) end2 = time.time() print('Bubble sort:', end1 - start1) print('Quick sort:',end2 - start2) Output: &gt;&gt;&gt; Bubble sort: 7.04760217666626 &gt;&gt;&gt; Quick sort: 8.181402921676636 Why in this case bubble sort is faster than quick sort?
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/80519110
favorite count: 0
score: 8
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46786580
upvote count: 8
tagged with: python
has title: Why bubble sort is faster than quick sort
possible better answer: http://stackoverflow.com/a/46786570

http://stackoverflow.com/comment/80592850
comment on: http://stackoverflow.com/q/46822148
has text: I don't think they will allow me to install python, virtual enviroments or each of the packages that the script depends on; which is only numpy and pandas.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80571395
type: Comment
type: QuestionComment
has text: Please show us how the output would be for the CSV row containing the example you posted.
score: 2
comment on: http://stackoverflow.com/q/46811986

http://stackoverflow.com/q/46864921
has comment: http://stackoverflow.com/comment/80677509
tagged with: python
has comment: http://stackoverflow.com/comment/80677370
has comment: http://stackoverflow.com/comment/80684006
has comment: http://stackoverflow.com/comment/80684678
answer count: 0
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/80694000
has comment: http://stackoverflow.com/comment/80684227
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80684147
has comment: http://stackoverflow.com/comment/80684776
tagged with: cyk
has comment: http://stackoverflow.com/comment/80678093
has comment: http://stackoverflow.com/comment/80680967
has comment: http://stackoverflow.com/comment/80717301
score: 0
has comment: http://stackoverflow.com/comment/80709637
has title: Bottleneck in my recursive python code
has comment: http://stackoverflow.com/comment/80677650
has body: I wrote the below code using recursion to do CYK algorithm so that the Grammar G can generate any words having same number of a's followed by any number of b's but for some reason it is very slow, not sure why? When I use s2 it works, but if I used s1 which is a longer string it takes forever. Could anyone please advise as I can't figure out where is the bottleneck? def fn(G, w, i, j, T): if T[i, j]: print '1' return T[i, j] elif i == j: for r in G: print '2' if r.endswith(w[i]) and r[0] not in T[i, j]: print '3' T[i, j].append(r[0]) else: print '4' for k in range(i, j): print '5' for a in fn(G, w, i, k, T): print '6' for b in fn(G, w, k+1, j, T): print '7' for r in G: print '8' if r.endswith(a+b) and r[0] not in T[i, j]: print '9' T[i, j].append(r[0]) return T[i, j] def fnmain(G, S, w): dict = {} for x in range(0, len(w)): for y in range(x, len(w)): dict[x,y] = [] print dict v = fn(G, w, 0, len(w) - 1, dict) print (w, v) if S in v: print ("T") return True else: print ("F") return False G = ["S-&gt;AB", "S-&gt;XB", "T-&gt;AB", "T-&gt;XB", "X-&gt;AT", "A-&gt;a", "B-&gt;b"] s1 = "aaaaabbbbb" s1 = "aaaaaaaaabbbbbbbbb" fnmain(G, "S", s1) I've used cProfile as suggested by @wwii and below is the result: When s1 = "aaaaabbbbb" when s1= "aaaaaaaaabbbbbbbbb"
type: UnansweredQuestion

http://stackoverflow.com/comment/80594253
comment on: http://stackoverflow.com/q/46822744
has text: The first thing you should do when you get an error message you don't understand is to google it. That will generally find you answers that you can at least start with.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80719544
comment on: http://stackoverflow.com/q/46879416
type: QuestionComment
type: Comment
has text: Is there any other code between the code block you've shown us and fetching the first element of the array? Maybe some sneaky reassignment of said element? Like hpaulj said, with only the code you've given us there should be no problem. We need a [minimal, complete AND verifiable example](https://stackoverflow.com/help/mcve) of your problem.
score: 0

http://stackoverflow.com/a/46768031
has body: After clarification of OP, seems what is needed is something like: for ii, element in enumerate(my_list): if element == my_list[0]: continue else: break new_list = my_list[ii-1:] Also, using itertools dropwhile, we can concatenate element 0 and the result of dropping any element at the beginning that is equal to the first element: new_list = [my_list[0]] + list(dropwhile(lambda x: x == my_list[0], my_list))
has comment: http://stackoverflow.com/comment/80482143
upvote count: 0
answers question: http://stackoverflow.com/q/46767818
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/80483545
downvote count: 1

http://stackoverflow.com/comment/80740046
type: QuestionComment
comment on: http://stackoverflow.com/q/46896469
has text: from __future__ import unicode_literals import sys import os import traceback import paramiko import socket import random import subprocess import ipaddress import time import string hostip = ['firewallIP.txt'] username = "cisco" password = "password" port = 22 array =[ ] for line in hostip: hostip = string.split(line.rstrip('\n'),)
score: 0
type: Comment

http://stackoverflow.com/a/46872889
type: Answer
has body: It seems the best way to go about this is to not delete the column by reference/variable but by name. I'm still unclear on why that is. Happy to mark an explanation for this as the correct answer, my solution feels a bit hack. def _get_macd_c(df, f, s, g): fast = df['close_'+str(f)+'_ema'] slow = df['close_'+str(s)+'_ema'] df['macd'] = fast - slow df['macds'] = df['macd_'+str(g)+'_ema'] df['macdh'] = (df['macd'] - df['macds']) del df['macd_'+str(g)+'_ema'] del df['close_'+str(f)+'_ema'] del df['close_'+str(s)+'_ema']
has comment: http://stackoverflow.com/comment/80692987
answers question: http://stackoverflow.com/q/46872566
score: 0

http://stackoverflow.com/comment/80685745
has text: Is it possible that I need to have another variable that I set Max_Force Equal to to get it to not just be the same number for each iteration?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46869238
type: Comment

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/46789892
tags question: http://stackoverflow.com/q/46901021
tags question: http://stackoverflow.com/q/46819212
tags question: http://stackoverflow.com/q/46829650
tags question: http://stackoverflow.com/q/46788266
tags question: http://stackoverflow.com/q/46855059
tag name: r
tags question: http://stackoverflow.com/q/46847695
tags question: http://stackoverflow.com/q/46839332
tags question: http://stackoverflow.com/q/46816111
tags question: http://stackoverflow.com/q/46784727
tags question: http://stackoverflow.com/q/46879273
tags question: http://stackoverflow.com/q/46828086
tags question: http://stackoverflow.com/q/46901356
type: Tag
tags question: http://stackoverflow.com/q/46826880
tags question: http://stackoverflow.com/q/46853354
tags question: http://stackoverflow.com/q/46878439
tags question: http://stackoverflow.com/q/46769896
tags question: http://stackoverflow.com/q/46803072
tags question: http://stackoverflow.com/q/46803764
tags question: http://stackoverflow.com/q/46854408
tags question: http://stackoverflow.com/q/46842528

http://stackoverflow.com/comment/80771577
type: Comment
type: QuestionComment
has text: @GregGlockner I agree with you. I forgot to mention that they are binary variables.
comment on: http://stackoverflow.com/q/46898257
score: 0

http://stackoverflow.com/q/46756302
downvote count: 0
has body: I am using the following code to copy a dataframe into an Excel document: dfPol.to_excel(writer, 'Influence on Policy', columns=colsPol) The problem is that I am getting the following error as the URLs are too long: Ignoring URL .... 255 characters since it exceeds Excel's limit for URLS So, I found a solution which is to use: dfPol.to_excel(writer, 'Influence on Policy', columns=colsPol, options={'strings_to_urls': False}) But I am getting an error of: TypeError: to_excel() got an unexpected keyword argument 'options' As obviously options does not work with to_excel, which is what I am using for a lot of other code in my script (i.e. I want to stick with 'to_excel') Are there any solutions to my problem? This is not a duplicate of: How to save in *.xlsx long URL in cell using Pandas as that is not about to_excel (it is about excelwriter)
has answer: http://stackoverflow.com/a/77593788
has answer: http://stackoverflow.com/a/46756426
favorite count: 0
has comment: http://stackoverflow.com/comment/80457984
upvote count: 8
tagged with: pandas
has comment: http://stackoverflow.com/comment/80458139
tagged with: python
has comment: http://stackoverflow.com/comment/80458032
has answer: http://stackoverflow.com/a/60572237
score: 8
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46756426
possible better answer: http://stackoverflow.com/a/60572237
has comment: http://stackoverflow.com/comment/80457973
has comment: http://stackoverflow.com/comment/80457924
has comment: http://stackoverflow.com/comment/80457922
type: Question
linked to: http://stackoverflow.com/q/35440528
has comment: http://stackoverflow.com/comment/80457915
has comment: http://stackoverflow.com/comment/80458081
has title: (PYTHON) to_excel - Ignoring URL... 255 characters since it exceeds Excel's limit for URLS
answer count: 3
has comment: http://stackoverflow.com/comment/80457889
has comment: http://stackoverflow.com/comment/91550657
has comment: http://stackoverflow.com/comment/80458010

http://stackoverflow.com/q/46765859
favorite count: 0
tagged with: pangram
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/80477112
has comment: http://stackoverflow.com/comment/80477033
upvote count: 1
answer count: 1
downvote count: 7
score: -6
has answer: http://stackoverflow.com/a/46765946
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80480230
has comment: http://stackoverflow.com/comment/80479835
has comment: http://stackoverflow.com/comment/80476985
tagged with: function
has body: I wrote this code for a function to check for pangram and it doesn't work. I need an explanation as to where I am getting it wrong. def is_mypangram(phrase): alphabets = 'abcdefghijklmnopqrstuvwxyz' for letters in alphabets: for char in phrase: if letters not in phrase: return False else: return True
has title: What's wrong with my code for pangram function?

http://stackoverflow.com/comment/80619094
has text: Thanks, I think I see! I'll try to apply it tonight, and then give you the checkmark :)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46830288
score: 1

http://stackoverflow.com/comment/80511603
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46782146
has text: I believe I'd be able to use iter know, well, actually, at first I believed it was included in iter.tools and my teacher allowed that. We haven't seen it in class, that's sure, but know I think I could use it. However, I seen some other things we wouldn't been able to use, like `lambda`. I think I'm making you guys struggle a little too much, really, thanks a lot for this. But I think it'd be easier if as @PM2Ring says, I did a list with stuff we have seen. Give me a second, it'd be useful for me too

http://stackoverflow.com/comment/80652557
comment on: http://stackoverflow.com/a/46849429
has text: Hm. A `default=None` should work here. Are you sure it's not because your `source` is `fk_promotion.id` instead of `promotion.id`?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80642277
comment on: http://stackoverflow.com/q/46821018
type: Comment
type: QuestionComment
has text: (Obviously, the above does not really matter **if** the encryption key is used only once.)
score: 0

http://stackoverflow.com/comment/80642109
score: 0
type: Comment
type: QuestionComment
has text: Trying this out on https://try.jupyter.org/ and defining the class in the same text box, the notebook raises a ValueError as expected. Same running locally with `the_file` in the same directory I launched the notebook from. This points to something with the `import` - have you installed `the_file` in the python path somewhere? Or is there already a module with that name?
comment on: http://stackoverflow.com/q/46846860

http://stackoverflow.com/a/46893575
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80735179
score: 1
has comment: http://stackoverflow.com/comment/80734659
has comment: http://stackoverflow.com/comment/80735598
has body: Try it like this srcs = response.xpath('//*[@id="comic"]/img/@src').extract() i['image_urls'] = [response.urljoin(src) for src in srcs] Probably you've already have done this but, just in case, be sure to set correctly the IMAGES_STORE setting.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46892962
answers question: http://stackoverflow.com/q/46892962

http://stackoverflow.com/comment/80483218
type: AnswerComment
comment on: http://stackoverflow.com/a/46768853
type: Comment
has text: Wow, thanks, that solves it! Just one word from getting there myself I see. Slightly embarrassed
score: 0

http://stackoverflow.com/comment/80480158
has text: Comment about input format says "first line contains N", the second line contains N numbers. In the example there is only one input line but the first element of the input array appears to be the array length, which is not needed in my algorithm. The question is extremely vague in this sense. If you understood it differently, feel free to post another answer. My algorithm is based on my interpretation of the question - and focusing on the part OP seems to struggle with - the output number selection.
score: 0
comment on: http://stackoverflow.com/a/46766077
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80747761
has text: @BookmarkScraper Both of them use the loads function from the json library and assign the return value to the j variable. But it is strange as the 2nd line overwrites the first.
type: Comment
comment on: http://stackoverflow.com/a/46900348
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80724945
score: 0
has text: Which pywinauto version do you use? And can you provide the traceback of a typical failure?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46884612

http://stackoverflow.com/a/46803346
answers question: http://stackoverflow.com/q/46798057
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/96113904
has body: Not tested code,you can have a try: class PostSerializer(serializers.ModelSerializer): content = serializers.SerializerMethodField() def get_content(self, instance): from django.utils.safestring import mark_safe return mark_safe(instance.content) class Meta: model = Post fields = '__all__'
score: 1
upvote count: 1

http://stackoverflow.com/a/46753752
score: 3
accepted answer of: http://stackoverflow.com/q/46753628
answers question: http://stackoverflow.com/q/46753628
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: You have to use bytespdate2num function to read csv file (because you read the file in binary mode): import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import bytespdate2num time, impressions = np.loadtxt("datalog_new.csv", unpack=True, delimiter=',', converters={0: bytespdate2num('%H:%M:%S.%f')}) plt.plot_date(x=time, y=impressions) plt.show()
downvote count: 0

http://stackoverflow.com/a/46869591
upvote count: 4
has body: Iterate over each group that df.groupby returns. for _, g in df.groupby('a'): print(g, '\n') a b c d 0 1 1 1 1 1 1 2 2 2 2 1 3 3 3 3 1 4 4 4 a b c d 4 2 1 1 1 5 2 2 2 2 6 2 3 3 3 If you want a dict of dataframes, I'd recommend: df_dict = {idx : g for idx, g in df.groupby('a')} Here, idx is the unique a value. A couple of nifty techniques courtesy Root: df_dict = dict(list(df.groupby('a'))) # for a dictionary And, idxs, dfs = zip(*df.groupby('a')) # separate lists idxs (1, 2) dfs ( a b c d 0 1 1 1 1 1 1 2 2 2 2 1 3 3 3 3 1 4 4 4, a b c d 4 2 1 1 1 5 2 2 2 2 6 2 3 3 3)
downvote count: 0
has comment: http://stackoverflow.com/comment/80686432
accepted answer of: http://stackoverflow.com/q/46869521
answers question: http://stackoverflow.com/q/46869521
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/80686682
type: Answer
has comment: http://stackoverflow.com/comment/80686469

http://stackoverflow.com/q/46760771
has comment: http://stackoverflow.com/comment/80466904
accepted answer: http://stackoverflow.com/a/46760863
type: Question
answer count: 2
has body: User may give a bunch of urls as command line args. All URLs given in the past are serialized with pickle. The script checks all given URLs, if they are unique then they are serialized and appended to a file. At least that's what should be happening. Nothing is being appended. However when I open the file in write mode,the new, unique URL is written. So what gives? Code is: def get_new_urls(): if(len(urls.URLs) != 0): # check if empty with open(urlFile, 'rb') as f: try: cereal = pickle.load(f) print(cereal) toDump = [] for arg in urls.URLs: if (arg in cereal): print("Duplicate URL {0} given, ignoring it.".format(arg)) else: toDump.append(arg) except Exception as e: print("Holy bleep something went wrong: {0}".format(e)) return(toDump) urlsToDump = get_new_urls() print(urlsToDump) # TODO: append new URLs if(urlsToDump): with open(urlFile, 'ab') as f: pickle.dump(urlsToDump, f) # TODO check HTML of each page against the serialized copy with open(urlFile, 'rb') as f: try: cereal = pickle.load(f) print(cereal) except EOFError: # your URL file is empty, bruh pass
tagged with: pickle
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/46760869
has title: pickle.dump dumps nothing when appending to file
has answer: http://stackoverflow.com/a/46760869
tagged with: file
has answer: http://stackoverflow.com/a/46760863
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80466888
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/46797267
tagged with: pandas
has comment: http://stackoverflow.com/comment/80541293
upvote count: 1
has title: Extract a column from csv file which has few rows with extra commas as value(address field), which causes the column count to break
has comment: http://stackoverflow.com/comment/85871545
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80541290
has comment: http://stackoverflow.com/comment/80541981
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46797683
accepted answer: http://stackoverflow.com/a/46797683
type: Question
has comment: http://stackoverflow.com/comment/80541523
possible better answer: http://stackoverflow.com/a/46797489
score: -1
has body: I need to access values of a column that occur after the address column, but due to presence of comma in the address field, I causes the file to count extra columns. Example csv: id,name,place,address,age,type,dob,date 1,Murtaza,someplace,Street,MA,22,B,somedate,somedate, 2,Murtaza,someplace,somestreet,45,C,somedate,somedate, 3,Murtaza,someplace,somestreet,MA,44,V,somedate,somedate Excel output: id name place address age type dob date newcolumn9 1 Murtaza someplace somestreet MA 22 B somedate somedate 2 Murtaza someplace somestreet 45 C somedate somedate 3 Murtaza someplace somestreet MA 44 V somedate somedate This is what I tried: # I was able to see that all columns before the column with extra commas displayed fine using this code. import pandas as pd import csv with open('Myfile', 'rb') as f, open('Newfile', 'wb') as g: writer = csv.writer(g, delimiter=',') for line in f: row = line.split(',', 2) writer.writerow(row) I am trying to do this in python pandas. If I can parse the csv in reverse ill be able to get the proper values regardless of the error. From the above example, I want extract age column.
has answer: http://stackoverflow.com/a/46797489
has comment: http://stackoverflow.com/comment/80541857
answer count: 2
downvote count: 2

http://stackoverflow.com/a/46786120
type: Answer
has comment: http://stackoverflow.com/comment/80809033
score: 2
has comment: http://stackoverflow.com/comment/80591073
upvote count: 2
answers question: http://stackoverflow.com/q/46769954
has comment: http://stackoverflow.com/comment/80556640
accepted answer of: http://stackoverflow.com/q/46769954
type: AcceptedAnswer
downvote count: 0
has body: Do you have any other idea to make some queries to sql database , or install these two libraries on that machine. As a workaround, we can use PowerShell to run sql query, here is the example: $SqlServer = "jasontest321.database.windows.net" $SqlServerPort = "1433" $Database = "jasonsqltest" $Table = "dbc" $SqlCredentialAsset = "sql" $SqlCredential = Get-AutomationPSCredential -Name $SqlCredentialAsset if ($SqlCredential -eq $null) { throw "Could not retrieve '$SqlCredentialAsset' credential asset. Check that you created this first in the Automation service." } $SqlUsername = $SqlCredential.UserName $SqlPass = $SqlCredential.GetNetworkCredential().Password $Conn = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$SqlServer,$SqlServerPort;Database=$Database;User ID=$SqlUsername;Password=$SqlPass;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;") $Conn.Open() $Cmd=new-object system.Data.SqlClient.SqlCommand("insert into dbc(name,age)values('jason2','ba')", $Conn) $Cmd.CommandTimeout=120 $Ds=New-Object system.Data.DataSet $Da=New-Object system.Data.SqlClient.SqlDataAdapter($Cmd) [void]$Da.fill($Ds) $Ds.Tables.Column1 $Conn.Close() About the $SqlCredentialAsset = "sql", we should create credentials in Azure automation account, like this: Here is the runbook result: More information about, please refer to this link.

http://stackoverflow.com/comment/80701672
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46876976
has text: why not `type(x) is A`?

http://stackoverflow.com/q/46869883
upvote count: 0
tagged with: pyqt
answer count: 1
accepted answer: http://stackoverflow.com/a/46869967
has body: I am creating a window that allows me to add a array of text boxes when I press a button, but when, I press the button, and call the function, I get an error, which says 'IndicSelectWindow' object has no attribute "whatever ". I Try something else easier like changing what a label said, but I can not access the label either. How could I do to fix it? please... :( import sys from PyQt4.QtGui import * class IndicSelectWindow(QDialog): def __init__(self, parent=None): super(IndicSelectWindow, self).__init__(parent=parent) # cero un layout vertical para las matrices layoutmatrices = QVBoxLayout() ########################## # create the area for the matrix scrollarea = QScrollArea() scrollarea.setWidgetResizable(True) widgetdelscrollarea = QWidget() layoutgrilla = QGridLayout(widgetdelscrollarea) scrollarea.setWidget(widgetdelscrollarea) ########################### # now now place elements in the array layout #the elements consist of a layout where the buttons are placed and another layout where the area is placed layoutelementosmatriz1 = QHBoxLayout() labelm1 = QLabel("Matriz 1") labelmf1 = QLabel("Filas") labelmc1 = QLabel("Columnas") botonm1 = QPushButton("Aceptar") text_m1f = QLineEdit() text_m1c = QLineEdit() layoutelementosmatriz1.addWidget(labelm1) layoutelementosmatriz1.addWidget(labelmf1) layoutelementosmatriz1.addWidget(text_m1f) layoutelementosmatriz1.addWidget(labelmc1) layoutelementosmatriz1.addWidget(text_m1c) layoutelementosmatriz1.addWidget(botonm1) layoutelementosmatriz1.setSpacing(20) botonm1.clicked.connect(lambda: self.create_matrix()) ##eventos layoutmatrices.addLayout(layoutelementosmatriz1) layoutmatrices.addWidget(scrollarea) ####################################3 i create the layout for the frame layoutgeneral = QHBoxLayout() self.setLayout(layoutgeneral) self.resize(800, 500) ################################# # I add the elements to the frame layoutgeneral.addLayout(layoutmatrices) ################################### def create_matrix(self): #thi…
favorite count: 0
score: -1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80687251
has comment: http://stackoverflow.com/comment/80687002
tagged with: pyqt5
downvote count: 1
has answer: http://stackoverflow.com/a/46869967
type: Question
tagged with: qlabel
has comment: http://stackoverflow.com/comment/80687118
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/80687068
has comment: http://stackoverflow.com/comment/80687174
has title: how to access the elements of a frame, if these are placed on layouts (HBoxLayout())

http://stackoverflow.com/q/46862074
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80671698
downvote count: 0
has answer: http://stackoverflow.com/a/77425249
has comment: http://stackoverflow.com/comment/80671643
type: Question
tagged with: python-os
has answer: http://stackoverflow.com/a/46862255
accepted answer: http://stackoverflow.com/a/46862255
has body: I want to change the group name of one directory recursively, I am using os.chown() to do that. But I can not find any recursive flag like (chgrp -R) in os.chown().
possible better answer: http://stackoverflow.com/a/46862139
has title: Is there any equivalent of chgrp -R in python?
upvote count: 2
has comment: http://stackoverflow.com/comment/80671592
tagged with: python-2.7
answer count: 3
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80671948
has answer: http://stackoverflow.com/a/46862139
tagged with: python

http://stackoverflow.com/a/46858160
has comment: http://stackoverflow.com/comment/80746579
score: 3
has comment: http://stackoverflow.com/comment/80663893
has body: Maybe you can catch the exception in a try block, and do what you want ( set some object to None use a Dummy class)? edit: Take a look at this, I don't know if it is the right way to do it, but it seems to work fine: import sys import pickle class Dummy: pass class MyUnpickler(pickle._Unpickler): def find_class(self, module, name): # from the pickle module code but with a try # Subclasses may override this. # we are doing it right now... try: if self.proto &lt; 3 and self.fix_imports: if (module, name) in _compat_pickle.NAME_MAPPING: module, name = _compat_pickle.NAME_MAPPING[(module, name)] elif module in _compat_pickle.IMPORT_MAPPING: module = _compat_pickle.IMPORT_MAPPING[module] __import__(module, level=0) if self.proto &gt;= 4: return _getattribute(sys.modules[module], name)[0] else: return getattr(sys.modules[module], name) except AttributeError: return Dummy # edit: as per Ben suggestion an even simpler subclass can be used # instead of the above class MyUnpickler2(pickle._Unpickler): def find_class(self, module, name): try: return super().find_class(module, name) except AttributeError: return Dummy class C: pass c1 = C() with open('data1.dat', 'wb') as f: pickle.dump(c1,f) del C # simulate the missing class with open('data1.dat', 'rb') as f: unpickler = MyUnpickler(f) # or MyUnpickler2(f) c1 = unpickler.load() print(c1) # got a Dummy object because of missing class
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80787620
downvote count: 1
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46857615
answers question: http://stackoverflow.com/q/46857615

http://stackoverflow.com/a/46809669
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/46809632
answers question: http://stackoverflow.com/q/46809632
has body: There is problem different types, need same. Check it: print (A['Ubi'].dtype) print (B['Ubi'].dtype) So need: A['Ubi'] = A['Ubi'].astype(str) B['Ubi'] = B['Ubi'].astype(str) Or: A['Ubi'] = A['Ubi'].astype(int) B['Ubi'] = B['Ubi'].astype(int)
has comment: http://stackoverflow.com/comment/80567141

gmt
tags question: http://stackoverflow.com/q/46823064
tag name: gmt
type: Tag

http://stackoverflow.com/a/46850628
type: Answer
score: 1
has body: Here is another way to do it using loop: text = """CPO 1 CL 1 SL 1 EL 1 CPO 1 SL 1 CPO 1""" text_split = text.split() # split the text [CPO, 1, CL, 1 and so on] dict_k = text_split[0::2] # values at odd index dict_v = text_split[1::2] # values at even index dict_t = {} for k, v in zip(dict_k, dict_v): dict_t[k] = dict_t.get(k, 0) + int(v) print(dict_t) # output:{'SL': 2, 'CPO': 3, 'EL': 1, 'CL': 1}
answers question: http://stackoverflow.com/q/46849507
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/80629883
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46840960
has text: load_workbook and ExcelWriter/to_excel are two different way to deal with Excel files, I don't think you can do them together. It's unclear what is broken here, partially due to the the try: except: block (which catches all exceptions... this shouldn't be necessary).
score: 0

http://stackoverflow.com/a/46879502
upvote count: 1
score: 1
has body: In addition to the string-to-int issues already identified, you might find this simpler if you set your x and y bounds to [-1,1]. Also, consider using Numpy: import numpy as np n = int(input("Enter the number of darts you have. ")) count = 1 circleval = 0 squareval = 0 while count &lt;= n: y = np.random.uniform(low=-1, high=1) x = np.random.uniform(low=-1, high=1) if np.sqrt(x**2 + y**2) &lt;= 1: circleval+=1 squareval+=1 else: squareval+=1 count+=1 print("Pi is", 4*(1.*circleval/squareval)) Output: Enter the number of darts you have. 1000000 Pi is 3.142168 Notes: - You don't need to keep track of squareval, you can just use n. - You can use Numpy's vectorized operations to skip the while-loop: area = 4 n = int(input("Enter the number of darts you have. ")) X = np.random.uniform(low=-1, high=1, size=n) Y = np.random.uniform(low=-1, high=1, size=n) dist = np.sqrt(X**2+Y**2); in_circle = np.sum(dist &lt; 1.0) print("Pi is", area * in_circle/n)
downvote count: 0
answers question: http://stackoverflow.com/q/46879374
type: Answer

http://stackoverflow.com/q/46749486
score: 0
has body: This seems like a pipe dream if it exists, but I figured I would ask just in case... Long story short, I'm trying to pull in an element of an array and do multiple manipulations on it. I'm trying to use a class to organize the manipulations. However, when feeding an element from an array, I need the value of the row and column as well. To reduce the number of inputs that I have to feed into the class function, I was hoping there was a way I could extract the characteristics of the array element I was passing in (even though I know that's not what the function "sees"...). Obviously doable without, but was thinking if I didn't have to pass in redundant (sort of?) information, it might look cleaner so hoped the experts might have a way...Thanks! Example element value would be the value from A[0][1] class Element(): def __init__(self, element, row, col): self.element = element self.row = row self.col = col What I was hoping exists somewhere... class Element(): def __init__(self, element): self.element = element numpy.row(element) = row #or some other package? numpy.col(element) = col
answer count: 0
has comment: http://stackoverflow.com/comment/80445167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80445089
tagged with: python
has title: Numpy Array: Extract Array Row (i) and Column (j) from Index x[i][j]
has comment: http://stackoverflow.com/comment/80445104
type: Question
tagged with: numpy
tagged with: arrays
tagged with: class

http://stackoverflow.com/comment/80651489
comment on: http://stackoverflow.com/a/46851968
type: AnswerComment
score: 0
type: Comment
has text: Thank you so much. It helped. Just a small question. Why did you read it as json I think it is in HTML format. Also is there any way to do the same without curl ? Thanks again

http://stackoverflow.com/comment/80449459
has text: @user3120554 i would suggest you avoid wildcard imports. And it would be better to import required objects to main module directly ( readability matters )
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46751598

http://stackoverflow.com/a/52251920
has body: Another method is via pd.to_numeric, just a slight variant of @coldspeed's answer i.e df = df.set_index('TimeStamp') df.groupby(pd.to_numeric(df.columns).astype(int),1).mean() 382 383 TimeStamp 10:28:00 0.012405 0.012405 10:30:00 0.012405 0.012422 10:32:00 0.055138 0.056121 10:34:00 0.055655 0.056802 10:36:00 0.055681 0.057086
upvote count: 3
has comment: http://stackoverflow.com/comment/91514413
type: Answer
answers question: http://stackoverflow.com/q/46760083
score: 3
downvote count: 0

http://stackoverflow.com/comment/80515979
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46773773
has text: U, I like that. I like that a lot! :D
type: AnswerComment

http://stackoverflow.com/a/46888329
score: 2
downvote count: 0
has body: Add the following line in the "repl_python_run" command in SublimeREPL\config\Python\Main.sublime-menu, right before the "external_id": "python" argument: "view_id": "*REPL* [python]", and then to change the line: if view.id() == view_id into: if view.name() == view_id in SublimeREPL\sublimerepl.py.
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80891749
type: Answer
answers question: http://stackoverflow.com/q/46887575
accepted answer of: http://stackoverflow.com/q/46887575

http://stackoverflow.com/comment/80676465
has text: Surely there is a wrapper? Was this written in pyrex? cython?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46864408
type: Comment

http://stackoverflow.com/q/46822055
tagged with: python
has comment: http://stackoverflow.com/comment/80592080
answer count: 4
has answer: http://stackoverflow.com/a/46822307
has answer: http://stackoverflow.com/a/46822168
has body: I'm not quite sure why this doesn't work, can anyone please help me fix this? def valid(user_guess, valid_characters, guess_size): '''(list, str, int) -&gt; bool Given a list of single character strS and a str, return True if every character is in the given string. &gt;&gt;&gt; (['A', 'C', 'B', 'E'], 'ACBE', 4) True &gt;&gt;&gt; (['A', 'C', 'B', 'E'], 'ADFG', 4) False ''' for char in user_guess: if char in valid_characters and len(user_guess) == guess_size: return True if char not in valid_characters and len(user_guess) != guess_size: return Fal
type: Question
has comment: http://stackoverflow.com/comment/80592378
has comment: http://stackoverflow.com/comment/80592066
has answer: http://stackoverflow.com/a/46822134
score: 0
has answer: http://stackoverflow.com/a/46822085
has title: Returning characters in single string lists
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/46811218
has title: Creating a list of deduplicated lists based on matches in loop? - Python, Openpyxl
tagged with: python
has comment: http://stackoverflow.com/comment/80672563
upvote count: 2
tagged with: openpyxl
answer count: 1
tagged with: excel
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/80570831
has answer: http://stackoverflow.com/a/46812074
has body: I'm trying to accomplish this with Pycharm 2017.1.3., Openpyxl 2.4.7, and Excel 2016. Here is a smaller version of my data set, for starters: SHEET1: | partID | keywordcategory |keyword| | 4849348| searchkeyword1 |Hobbock | 4849348| searchkeyword1 |Lentso* | 4849348| searchkeyword2 |Lentso| | 4849348| searchkeyword3 |LENTSO-EIEMR | | 4849348| searchkeyword3 |Hobbock | 4849346| searchkeyword1 |protein | 4849346| searchkeyword3 |ion The result I want to achieve is, for each unique part number, to: A. Get a list of the unique search terms at each keyword category, AND B. A combined list of each part number's keywords across all keywordcategories. Heres an example of what I'd love to end up with: | partID |searchkeyword1 |searchkeyword2|searchkeyword3|combined | 4849348| Hobbock;Lentso*|Lentso |LENTSO-EIMER |Hobbock;Lentso*; |Lentso; |LENTSO-EIMER | 4849346| protein | |ion |protein;ion This is what I've been working on so far, but it doesn't seem to be creating new lists at each row. import openpyxl print('Opening file...') wb = openpyxl.load_workbook('keywords.xlsx') sheet1 = wb.get_sheet_by_name('Sheet1') sheet2 = wb.get_sheet_by_name('Sheet2') maxRow1 = sheet1.max_row + 1 maxRow2 = sheet2.max_row + 1 print('Processing...') for rowNum in range(1, maxRow2): for col in sheet1.iter_cols(min_row=1, min_col=2, max_col=2, max_row=1000): for cell in col: keywordlist = [] if cell.value == sheet2.cell(row=rowNum, column=1).value: if sheet1.cell(row=rowNum, column=3).value == 16985323: #if sheet1.cell(row=rowNum, column=4).value not in keywordlist and 'None' not in sheet1.cell(row=rowNum, column=4).value: keywordlist.append(sheet1.cell(row=rowNum, column=4).value + ';') sheet2.cell(row=rowNum, column=2).value = str(keywordlist) Any ideas or help would be greatly appreciated! Thanks in advance! EDIT: Charlie's help has gotten me a lot further than I was! The issue I'm having now is that when I try to use the defaultdict(list) on my actual project, it doesn't seem to be removing …
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80571388
type: Question
has comment: http://stackoverflow.com/comment/80571122

http://stackoverflow.com/q/46795690
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46795741
type: AnsweredQuestion
type: Question
upvote count: 9
has title: django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name
has body: Django version 1.11.5, views.py class SignupPage(CreateView): form_class = forms.UserSignupForm success_url = reverse_lazy('login') template_name = 'signup.html' website/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView,LogoutView from . import views app_name = 'website' urlpatterns = [ url(r'^login/', auth_views.LoginView.as_view(template_name='signin_2_w.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^signup/', views.SignupPage.as_view(), name='sign_up'), forms.py class UserSignupForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = "Display Name" self.fields['email'].label = "Email Address" self.fields['password1'].label = "Password" self.fields['password2'].label = "Confirm Password" proj/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomePage.as_view(),name='home'), url(r'^website/',include('website.urls',namespace='website')), url(r'^website/',include('django.contrib.auth.urls')), url(r'^website/',views.StreamyePage.as_view(),name='streamye'), url(r'^thanks/$',views.ThanksPage.as_view(),name='thanks'), url(r'^congrats/$',views.CongratsPage.as_view(),name='congrats'), url(r'^aboutus/$',views.AboutusPage.as_view(),name='about_us'), HTML {% if user.is_authenticated %} Logout {% else %} Login Signup {% endif %} In the above code, the signup page is throwing me a error -- "django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name." Please someone help me out where im wrong! Thanks in advance!
accepted answer: http://stackoverflow.com/a/46795741
possible better answer: http://stackoverflow.com/a/70753996
has answer: http://stackoverflow.com/a/70753996
has answer: http://stackoverflow.com/a/73647742
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80538040
score: 9

http://stackoverflow.com/a/46837104
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/46837040
upvote count: 7
type: Answer
has body: Take a look at this one: mylist = [1,5,15,30,60] def diff(myList): return [myList[i+1] - myList[i] for i in range(len(myList)-1)] l = diff(mylist) print(l) The output is: [4, 10, 15, 30]

http://stackoverflow.com/q/46864556
tagged with: security
upvote count: 3
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: bandit-python
score: 3
downvote count: 0
has body: I would like to get python code for an analysis using Bandit static analyzer. The main emphasis is security, for python 2.7. Can anyone help ?
has title: Python code for security analysis using Bandit
type: Question
tagged with: analyzer
has answer: http://stackoverflow.com/a/51103501

http://stackoverflow.com/q/46852470
linked to: http://stackoverflow.com/q/1975250
possible better answer: http://stackoverflow.com/a/46852942
accepted answer: http://stackoverflow.com/a/46852543
tagged with: python
has comment: http://stackoverflow.com/comment/80652406
type: AnsweredQuestion
tagged with: list
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80652362
has body: I have a lists of lists of strings which I would like to convert to a list of strings adding a space between each list item. eg. original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']] desired_output = ['the cat in the hat', 'fat cat sat on the mat'] I understand that I can do it using this: desired_output for each in original_list: desired_output.append(' '.join(each)) but as I am working with large amounts of data am ideally looking for a more efficient way to do this.
tagged with: string
has answer: http://stackoverflow.com/a/46852942
has answer: http://stackoverflow.com/a/46852543
has title: Convert lists of lists of string into a list of string efficently
score: 0

http://stackoverflow.com/q/46897949
downvote count: 2
has comment: http://stackoverflow.com/comment/80743774
answer count: 1
has comment: http://stackoverflow.com/comment/80744113
has comment: http://stackoverflow.com/comment/80744146
has comment: http://stackoverflow.com/comment/80743910
has comment: http://stackoverflow.com/comment/80743739
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46898487
has comment: http://stackoverflow.com/comment/80743871
has comment: http://stackoverflow.com/comment/80743137
has title: Extract value from complex list of decoy/fake dictionaries
linked to: http://stackoverflow.com/q/46514274
upvote count: 0
has body: I am trying to extract the arrival time values from the following, which appears to be a list of dictionaries: [{'arrival': {'time': 1508791028L}, 'departure': {'time': 1508791028L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508790596L}, 'departure': {'time': 1508790596L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508791744L}, 'departure': {'time': 1508791744L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508792223L}, 'departure': {'time': 1508792223L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508793450L}, 'departure': {'time': 1508793450L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508792591L}, 'departure': {'time': 1508792591L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508794110L}, 'departure': {'time': 1508794110L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508794740L}, 'departure': {'time': 1508794740L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508788421L}, 'departure': {'time': 1508788421L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508788919L}, 'departure': {'time': 1508788919L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508789417L}, 'departure': {'time': 1508789417L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508790287L}, 'departure': {'time': 1508790287L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508790347L}, 'departure': {'time': 1508790347L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508791330L}, 'departure': {'time': 1508791330L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508791799L}, 'departure': {'time': 1508791799L}, 'schedule_relationship': 0, 'stop_id': u'D03N'}, {'arrival': {'time': 1508792447L}, 'departure': {'time': 1508792447L}, 'schedule_relatio…
favorite count: 0
has comment: http://stackoverflow.com/comment/80743843
has comment: http://stackoverflow.com/comment/80744046
type: Question
has comment: http://stackoverflow.com/comment/80743563
tagged with: python
score: -2
tagged with: dictionary
tagged with: list
has comment: http://stackoverflow.com/comment/80743818

http://stackoverflow.com/q/46854121
score: 1
has body: Code below creates a single QTreeWidget. I want each "Root" item to display the "expand" arrow next to its name but I don't want to create the Root's children items yet (I would rather create the children items after the user clicks the "Expand" arrow. The the attached image illustrates the idea. How to achieve it? app = QApplication([]) class Tree(QTreeWidget): def __init__(self, *args, **kwargs): super(Tree, self).__init__() self.setHeaderLabels(['Column name']) for i in range(3): root_item = QTreeWidgetItem() root_item.setText(0, 'Root %s' % i) self.addTopLevelItem(root_item) self.show() tree = Tree() app.exec_()
favorite count: 0
duplicate of: http://stackoverflow.com/q/2638974
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80655881
tagged with: qtreewidgetitem
tagged with: qtreewidget
linked to: http://stackoverflow.com/q/2638974
tagged with: pyqt
downvote count: 0
has title: How to make QTreeWidgetItem expandable

http://stackoverflow.com/comment/80547761
type: QuestionComment
comment on: http://stackoverflow.com/q/46800380
has text: COLOR_BGR2GRAY is not a valid mode for imread. Start by reading the image with the [correct mode] https://docs.opencv.org/3.3.0/d4/da8/group__imgcodecs.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822
score: 1
type: Comment

http://stackoverflow.com/comment/127849448
score: 1
has text: Yes, it does. Thank you for the link. Similar to the answer given below.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46756911

http://stackoverflow.com/a/46888679
upvote count: 2
has body: str.format is designed to repeat arguments or change their order when passing a position (starting at 0): a = 10 b = 20 print("{1} {0}".format(a,b)) you get: 20 10
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46888583
answers question: http://stackoverflow.com/q/46888583
type: Answer

http://stackoverflow.com/a/46821946
downvote count: 0
has comment: http://stackoverflow.com/comment/80591290
answers question: http://stackoverflow.com/q/46821838
type: Answer
upvote count: 2
has body: You can simply use the csv reader library to handle this. import csv headers = ['name', 'num', 'cost'] with open('venue.txt', 'r') as f: reader = csv.reader(f) needed_list = [{headers[i]: row[i].strip() for i in range(3)} for row in reader]
has comment: http://stackoverflow.com/comment/80591269
score: 2

http://stackoverflow.com/comment/80592274
has text: The relevant view was always there but added the relevant url
comment on: http://stackoverflow.com/a/46820096
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46824087
has comment: http://stackoverflow.com/comment/80595703
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80596748
has body: I'm using Python 2.7 to read the Book-Crossings dataset using Surprise Library. I had an Encoding problem. Here is my code: #load book_ratings dataset which contains (user-id, ISBN and book rating [0..10]) df = pd.read_csv("Desktop\ML project\BX-CSV-Dump\BX-Book-Ratings.csv", sep=';',encoding = "CP1252") # Create the reader in the proper format reader = Reader(line_format='user item rating', sep=';', rating_scale=(0,10)) ratings = Dataset.load_from_df(df, reader) # Test that surprise is working by running SVD on the dataset ratings.split(5) algo = SVD() evaluate(algo, ratings, measures=['RMSE', 'MAE']) The exception I get: UnicodeEncodeError Traceback (most recent call last) &lt;ipython-input-23-03cf8b43a4db&gt; in &lt;module&gt;() 9 ratings.split(5) 10 algo = SVD() ---&gt; 11 evaluate(algo, ratings, measures=['RMSE', 'MAE']) C:\Users\Jihed Mestiri\Anaconda2\lib\site-packages\scikit_surprise-latest-py2.7-win-amd64.egg\surprise\evaluate.pyc in evaluate(algo, data, measures, with_dump, dump_dir, verbose) 66 # train and test algorithm. Keep all rating predictions in a list 67 algo.train(trainset) ---&gt; 68 predictions = algo.test(testset, verbose=(verbose == 2)) 69 70 # compute needed performance statistics C:\Users\Jihed Mestiri\Anaconda2\lib\site-packages\scikit_surprise-latest-py2.7-win-amd64.egg\surprise\prediction_algorithms\algo_base.pyc in test(self, testset, verbose) 150 r_ui_trans - self.trainset.offset, 151 verbose=verbose) --&gt; 152 for (uid, iid, r_ui_trans) in testset] 153 return predictions 154 C:\Users\Jihed Mestiri\Anaconda2\lib\site-packages\scikit_surprise-latest-py2.7-win-amd64.egg\surprise\prediction_algorithms\algo_base.pyc in predict(self, uid, iid, r_ui, clip, verbose) 93 iiid = self.trainset.to_inner_iid(iid) 94 except ValueError: ---&gt; 95 iiid = 'UKN__' + str(iid) 96 97 details = {} UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 4: ordinal not in range(128) I tried with other encoding codes but it didn't work t…
score: 1
tagged with: scikits
has comment: http://stackoverflow.com/comment/80596687
type: Question
has comment: http://stackoverflow.com/comment/80597807
tagged with: encoding
has comment: http://stackoverflow.com/comment/80596273
tagged with: unicode
has comment: http://stackoverflow.com/comment/80596728
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80595904
has title: 'ascii' codec can't encode character u'\x90' in position 0: ordinal not in range(128)
upvote count: 1
has comment: http://stackoverflow.com/comment/80596599
has comment: http://stackoverflow.com/comment/80595976
favorite count: 0

http://stackoverflow.com/a/46868023
type: Answer
has body: For little B sample, the set approach is output dependent, execution time grow linearly with index output. Numpy can provide better solution in this case. N=10**6 A=np.unique(np.random.randint(0,N,N)) np.random.shuffle(A) B=A[:3].copy() np.random.shuffle(A) def find(A,B): pos=np.in1d(A,B).nonzero()[0] return pos[A[pos].argsort()][B.argsort().argsort()].min() def findset(A,B): bset = set(B) return next(i for i, v in enumerate(A) if v in bset) #In [29]: find(A,B)==findset(A,B) #Out[29]: True #In [30]: %timeit findset(A,B) # 63.5 ms ± 1.31 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # # In [31]: %timeit find(A,B) # 2.24 ms ± 52.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
answers question: http://stackoverflow.com/q/46862148
score: 0

http://stackoverflow.com/comment/80719765
has text: mmm no, you can't load data in that method
comment on: http://stackoverflow.com/a/46857536
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46790654
has body: I am new to machine learning. I have a continuous dataset. I am trying to model the target label using several features. I utilize the train_test_split function to separate the train and the test data. I am training and testing the model using the code below: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = Sequential() model.add(Dense(128, input_dim=X.shape[1], kernel_initializer = 'normal', activation='relu')) model.add(Dense(1, kernel_initializer = 'normal')) hist = model.fit(X_train.values, y_train.values, validation_data=(X_test.values,y_test.values), epochs=200, batch_size=64, verbose=1) I can get good results when I use X_test and y_test for validation data: https://drive.google.com/open?id=0B-9aw4q1sDcgNWt5TDhBNVZjWmc However, when I use this model to predict another data (X_real, y_real) (which are not so different from the X_test and y_test except that they are not randomly chosen by train_test_split) I get bad results: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = Sequential() model.add(Dense(128, input_dim=X.shape[1], kernel_initializer = 'normal', activation='relu')) model.add(Dense(1, kernel_initializer = 'normal')) hist = model.fit(X_train.values, y_train.values, validation_data=(X_real.values,y_real.values), epochs=200, batch_size=64, verbose=1) https://drive.google.com/open?id=0B-9aw4q1sDcgYWFZRU9EYzVKRFk Is it an issue of overfitting? If it is so, why does my model work ok with the X_test and y_test generated by train_test_split?
favorite count: 0
accepted answer: http://stackoverflow.com/a/46791461
tagged with: python
type: AnsweredQuestion
upvote count: 2
tagged with: regression
tagged with: machine-learning
type: Question
has title: Why my model work ok with test data from train_test_split while doesn't with the new data?
possible better answer: http://stackoverflow.com/a/46847370
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/46847370
downvote count: 0
tagged with: neural-network
tagged with: train-test-split
has answer: http://stackoverflow.com/a/46791461

http://stackoverflow.com/q/46808342
score: 1
tagged with: queue
has answer: http://stackoverflow.com/a/46808475
answer count: 2
upvote count: 1
favorite count: 0
tagged with: worker
tagged with: redis
has comment: http://stackoverflow.com/comment/80563735
tagged with: python
has title: Is it common to run 20 python workers which uses Redis as Queue ?
has body: This program listen to Redis queue. If there is data in Redis, worker start to do their jobs. All these jobs have to run simultaneously that's why each worker listen to one particular Redis queue. My question is : Is it common to run more than 20 workers to listen to Redis ? python /usr/src/worker1.py python /usr/src/worker2.py python /usr/src/worker3.py python /usr/src/worker4.py python /usr/src/worker5.py .... .... python /usr/src/worker6.py
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80563967
type: Question
has comment: http://stackoverflow.com/comment/80567071
has answer: http://stackoverflow.com/a/46808422

http://stackoverflow.com/comment/80612196
type: Comment
has text: `count` returns the number of occurrences by value. It doesn't search by partial strings
comment on: http://stackoverflow.com/q/46832361
score: 0
type: QuestionComment

http://stackoverflow.com/q/46753393
has answer: http://stackoverflow.com/a/53967684
has answer: http://stackoverflow.com/a/55834112
has answer: http://stackoverflow.com/a/65463559
linked to: http://stackoverflow.com/q/46920243
tagged with: python
possible better answer: http://stackoverflow.com/a/55834112
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/74067141
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77032732
downvote count: 2
has answer: http://stackoverflow.com/a/46768243
score: 198
tagged with: firefox-headless
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/63973276
upvote count: 200
has comment: http://stackoverflow.com/comment/86883839
has answer: http://stackoverflow.com/a/63150512
accepted answer: http://stackoverflow.com/a/46768243
linked to: http://stackoverflow.com/q/75858506
has title: How to run headless Firefox with Selenium in Python?
tagged with: selenium-firefoxdriver
linked to: http://stackoverflow.com/q/58461862
has body: I am running this code with python, selenium, and firefox but still get 'head' version of firefox: binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', log_file=sys.stdout) binary.add_command_line_options('-headless') self.driver = webdriver.Firefox(firefox_binary=binary) I also tried some variations of binary: binary = FirefoxBinary('C:\\Program Files\\Nightly\\firefox.exe', log_file=sys.stdout) binary.add_command_line_options("--headless")
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80711857
comment on: http://stackoverflow.com/a/46881938
score: 0
type: AnswerComment
type: Comment
has text: @A.kaisis that should still work if you are feeding the words separated by commas.

http://stackoverflow.com/comment/84422416
comment on: http://stackoverflow.com/q/46821554
score: 0
type: Comment
type: QuestionComment
has text: These sounds kind of confusing. If you want two charts to show up, use two separate dcc.Graph(). You can put them in their own html.Div boxes but don't have too. It may be easier to move them around the screen if you do that. If you want to make sure they have live updates than give them both and "ID" element like dcc.Graph(id='chart1'). then in the call back you can refer right to it. Perhaps define a little more or provide an example?

http://stackoverflow.com/comment/80466279
score: 0
comment on: http://stackoverflow.com/q/46760318
type: QuestionComment
type: Comment
has text: Add it to the question in an edit! I cannot understand it like this. Thanks.

http://stackoverflow.com/comment/80697677
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46875201
type: Comment
has text: Glad I could help.

azure-batch
tags question: http://stackoverflow.com/q/46892796
type: Tag
tags question: http://stackoverflow.com/q/46749871
tags question: http://stackoverflow.com/q/46756780
tag name: azure-batch
tags question: http://stackoverflow.com/q/46774650

http://stackoverflow.com/q/46831246
has comment: http://stackoverflow.com/comment/80609912
tagged with: python
has comment: http://stackoverflow.com/comment/80703833
has answer: http://stackoverflow.com/a/46840455
type: AnsweredQuestion
upvote count: 0
tagged with: popen
type: Question
score: -2
has body: I have written basic port scanner for target ip and when I run it through kali vm it says sh: 1: nmap-F192.168.234.135: not found. but when I run nmap -F 192.168.234.135 ... its perfectly working. Can anyone point out the reason behind it. thanks import os def get_nmap(options,ip): command = "nmap" + options + "" + ip process = os.popen(command) result = str(process.read()) return result print(get_nmap('-F','192.168.234.135'))
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/46831467
has answer: http://stackoverflow.com/a/46831467
has comment: http://stackoverflow.com/comment/80610082
has title: Nmap not found when run from Python script
accepted answer: http://stackoverflow.com/a/46840455
favorite count: 0
tagged with: python-3.x
tagged with: linux

http://stackoverflow.com/comment/80561005
type: QuestionComment
type: Comment
has text: But if tuples are not csv format, is it in my best interest, to unpack the tuples?
score: 0
comment on: http://stackoverflow.com/q/46806715

http://stackoverflow.com/q/46806947
tagged with: unique
favorite count: 0
has title: Group by pandas data frame unique first values - numpy array returned
has answer: http://stackoverflow.com/a/46807547
possible better answer: http://stackoverflow.com/a/46807832
tagged with: python
has answer: http://stackoverflow.com/a/46807832
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80561907
upvote count: 1
has comment: http://stackoverflow.com/comment/80560914
accepted answer: http://stackoverflow.com/a/46807547
has comment: http://stackoverflow.com/comment/80561784
has comment: http://stackoverflow.com/comment/80561172
type: Question
tagged with: numpy
has body: From a two string columns pandas data frame looking like: d = {'SCHOOL' : ['Yale', 'Yale', 'LBS', 'Harvard','UCLA', 'Harvard', 'HEC'], 'NAME' : ['John', 'Marc', 'Alex', 'Will', 'Will','Miller', 'Tom']} df = pd.DataFrame(d) Notice the relationship between NAME to SCHOOL is n to 1. I want to get the last school in case one person has gone to two different schools (see "Will" case). So far I got: df = df.groupby('NAME')['SCHOOL'].unique().reset_index() Return: NAME SCHOOL 0 Alex [LBS] 1 John [Yale] 2 Marc [Yale] 3 Miller [Harvard] 4 Tom [HEC] 5 Will [Harvard, UCLA] PROBLEMS: unique() return both school not only the last school. This line return SCHOOL column as a np.array instead of string. Very difficult to work further with this df.
tagged with: group-by
has comment: http://stackoverflow.com/comment/80561562
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/a/46827498
accepted answer of: http://stackoverflow.com/q/46827087
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46827087
has comment: http://stackoverflow.com/comment/80603057
has body: Discover awk language: awk -F'[[:space:]][[:space:]]+' 'NR==FNR{ if(NR&gt;1) a[$2]=($2 in a? a[$2]",":"")$1","$3; next} FNR==1{ print $0,"songs" } $1 in a{ print $0,a[$1] }' file2.csv OFS='\t' file1.csv &gt; output.csv The output.csv content: id_album name date songs 001 Nevermind 24/09/1991 001,Smells Like Teen Spirit,002,In Bloom
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80602343
type: Answer

dialog
tag name: dialog
tags question: http://stackoverflow.com/q/46822951
type: Tag
tags question: http://stackoverflow.com/q/46858082

http://stackoverflow.com/q/46782427
answer count: 1
has body: import urllib.request import bs4 as bs sauce = urllib.request.urlopen("http://www.nhl.com/scores/htmlreports/20172018/TH020070.HTM").read() soup = bs.BeautifulSoup(sauce, "html.parser") table = soup.table table = soup.find('table') table_rows = table.find_all('tr') for tr in table_rows: td = tr.find_all('td') row = [i.text for i in td] print(row) I am trying to output this to a csv and json. How would i do both(not at the same time). Eventually when i get it properly formatted i would like to dump it straight into postgres. New to python so any help and suggestions would be appreciated. I got help previously with output to csv using pandas but i cant get it to format the way i would like it using pandas although ive been told its much easier..
accepted answer: http://stackoverflow.com/a/46782610
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/46782610
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
score: 0
has title: Looking to get a json and csv file from this
has comment: http://stackoverflow.com/comment/80511180

http://stackoverflow.com/a/46898724
score: 0
has comment: http://stackoverflow.com/comment/80827827
type: Answer
has body: Remove alter_ego from Membership. Change AlterEgo class and add related_name: class AlterEgo(models.Model): name = CharField(max_length=255) person = ForeignKey('someapp.Person', related_name = 'alter_ego') group = ForeignKey('someapp.Group', blank=True, null=True) In template iterate over members: &lt;td&gt; {% for member in group.members.all %} {% if member.alter_ego.group == group }} {{ member.alter_ego}} {% else %} {{ member.name }} {% endif %} {% endfor %} &lt;/td&gt; P.S. Small task for you is to form string from names in template and separate with &amp;
answers question: http://stackoverflow.com/q/46898217
has comment: http://stackoverflow.com/comment/80828608

http://stackoverflow.com/comment/80688635
comment on: http://stackoverflow.com/q/46870557
has text: I dont think index is being considered at all in rolling function
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80728936
type: Comment
has text: I used one review as an example. If there are more reviews on the page, the output of extract() will consist of more reviews. So if I would use join(text), I would have the text of all reviews combined in one element.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46890676

http://stackoverflow.com/comment/80446174
score: 0
has text: Much better! Still missing is the error or exception.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46750071

http://stackoverflow.com/q/46896457
upvote count: 16
has comment: http://stackoverflow.com/comment/104450135
has body: Here is an example for nested tqdm bar import time import tqdm for i in tqdm.tqdm(range(3)): for j in tqdm.tqdm(range(5)): print(i," : ", j) I try it on jupyter notebook but it does not show any thing without error! However, it works coorectly on ipython console!
type: Question
answer count: 1
downvote count: 0
tagged with: tqdm
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90312814
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51675263
tagged with: pycharm
type: UnansweredQuestion
has title: how to make a nested tqdm bars on jupyter notebook
score: 16

http://stackoverflow.com/comment/80499964
has text: Thanks, @Ajax1234, but I wanted to conserve the original pairs of numbers, which will be lost in that output
type: Comment
comment on: http://stackoverflow.com/a/46777178
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80566359
type: AnswerComment
has text: @EamonnKenny I think we're all on the same page, barring terminology. Python is written in C. The `float` datatype in python is implemented as a C `double`, which happens to be the same as a c++ `double`. I think we all appreciate that in c++ both `float` and `double` are floating point types of differing precisions.
type: Comment
comment on: http://stackoverflow.com/a/46771805
score: 0

http://stackoverflow.com/comment/80522290
has text: Not likely to make sense to someone who has "no idea how to begin". OP would have to know that `Counter` is a class in the `collections` package.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46788024
score: 1

http://stackoverflow.com/comment/80582493
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46817265
has text: I agree. But sometimes one comes with the other. In some cases, optimization leads to more readability. And I think my question is a good example of that.

http://stackoverflow.com/a/46862593
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46862450
type: Answer
downvote count: 0
score: 1
has body: Using remove: x = [[1,2],[2,6],[1,5],[5,6],[5,6], [10,11], [11,12], [3,4],[4,8],[8,7],[3,7]] y = {'first':[[1,2],[2,6],[1,5],[5,6]], 'second':[[2,3], [3,7],[7,6],[2,6]]} for v in y.values(): for _x in x: if _x in v: v.remove(_x) print(y) # {'first': [], 'second': [[2, 3], [7, 6]]}
accepted answer of: http://stackoverflow.com/q/46862450

http://stackoverflow.com/comment/80740869
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46881045
has text: Thanks! that makes sense to pull out the embeddings right there. Haha, definitely going to need to tweak some things [autoencoder plot](https://i.imgur.com/FdlUF1M.png) but this will help get me started
score: 0

http://stackoverflow.com/comment/80705842
score: 0
type: Comment
type: QuestionComment
has text: @percusse this expression is part of the gradient of the likelihood of a probit regression model. I know libraries can execute probit regression for me, but this expression illustrates the type of calculations I'd like to do.
comment on: http://stackoverflow.com/q/46879273

http://stackoverflow.com/comment/80451561
type: AnswerComment
comment on: http://stackoverflow.com/a/46751803
type: Comment
has text: Sorry! that was confusing. I was having trouble formatting it correctly but figured out how and update the question. I am still having issues with your solution unfortunately. It displays a grey cursor and leaves chars in the terminal window if the previous header was longer than the current one. See [here](https://imgur.com/a/TNQWo) for picture
score: 0

http://stackoverflow.com/a/46751455
downvote count: 0
has body: Error: The brew link step did not complete successfully The formula built, but is not symlinked into /usr/local Could not symlink bin/idle3 Target /usr/local/bin/idle3 already exists. You may want to remove it: rm '/usr/local/bin/idle3' HomeBrew installed Python 3.6.3, but could not symlink these files in /usr/local/bin: Possible conflicting files are: /usr/local/bin/idle3 -> /Library/Frameworks/Python.framework/Versions/3.5/bin/idle3 /usr/local/bin/pydoc3 -> /Library/Frameworks/Python.framework/Versions/3.5/bin/pydoc3 /usr/local/bin/python3 -> /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 /usr/local/bin/python3-config -> /Library/Frameworks/Python.framework/Versions/3.5/bin/python3-config /usr/local/bin/pyvenv -> /Library/Frameworks/Python.framework/Versions/3.5/bin/pyvenv To force the link and overwrite all conflicting files: brew link --overwrite python3
type: Answer
accepted answer of: http://stackoverflow.com/q/46751271
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80449900
answers question: http://stackoverflow.com/q/46751271
type: AcceptedAnswer

http://stackoverflow.com/a/46847268
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46846766
has comment: http://stackoverflow.com/comment/80674584
has comment: http://stackoverflow.com/comment/80645005
has body: You can just put the functions within the except block inside another try/except and tell it to ignore the exception with pass except(KeyboardInterrupt): # redundancy to make sure that a keyboard interrupt to close the program also closes the sockets and connections try: conn.close() sock.close() except: pass print 'Manual Close' sys.exit()

http://stackoverflow.com/a/46815037
accepted answer of: http://stackoverflow.com/q/46813151
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: see np.where. The numpy way is coords = pn['point.coords'] z = coords[:,2] q, = np.where(z&gt;0.001950) high_points=coords[q] The other point is that this is a linear time program. Yours is quadratic, because p in coords have a hidden complexity. For little value of zmax, the execution time will quickly augment.
score: 2
has comment: http://stackoverflow.com/comment/80579586
answers question: http://stackoverflow.com/q/46813151
has comment: http://stackoverflow.com/comment/80580805

http://stackoverflow.com/q/46757698
score: 1
type: Question
has answer: http://stackoverflow.com/a/46757722
has title: Getting the index of the first K values in a mixed index pandas Series
answer count: 2
tagged with: pandas
has body: L'ets say I have a pandas Series called z: index items 155 14 2 555 1445 23 855 3 and so on. As you can see, the indexes were mixed. How can I, without changing the current indexing, get a list of the index of the K first few rows? For exemple, for K=3, I want this: [155,2,1445] Thank you.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46757738
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/46870164
has body: If you would look at the api being called on the form action, you'll see that you've to make a post request to this url : https://www.horseracebase.com/excelresults.php with following parameters: data = { "user": "41495", # looks like this varies with login, so update in case you change your login id "racedate": "2005-3-15", "downloadbutton": "Excel" } you can do something like this: response = raceSession.post(reqUrl, json=data) If this doesn't work, try adding headers to the request like: headers=postHeaders. For ex. you should set the content type header in this case, as you're sending form encoded data, so: headers = {"Content-Type": "application/x-www-form-urlencoded"} Read this for more info on how to save the excel to a file Here's the response for this request in Postman, so looks like you won't need any additional headers except the content-type : EDIT This is what you need to do: raceSession = Session() RaceUrl = 'https://www.horseracebase.com/excelresults.php' RaceDataDetails = {"user": "41495", "racedate": "2005-3-15", "downloadbutton": "Excel"} PostHeaders = {"Content-Type": "application/x-www-form-urlencoded"} Response = raceSession.post(RaceUrl, data=RaceDataDetails, headers=PostHeaders) # from StringIO import StringIO #for python 2.x #import StringIO #for python 3.x Table = pd.read_table(StringIO(Response.text))
has comment: http://stackoverflow.com/comment/80693599
has comment: http://stackoverflow.com/comment/80691680
score: 0
has comment: http://stackoverflow.com/comment/80694391
has comment: http://stackoverflow.com/comment/80691358
has comment: http://stackoverflow.com/comment/80693318
answers question: http://stackoverflow.com/q/46868630
type: Answer
has comment: http://stackoverflow.com/comment/80691336
has comment: http://stackoverflow.com/comment/80691631
has comment: http://stackoverflow.com/comment/80694477
has comment: http://stackoverflow.com/comment/80692128
has comment: http://stackoverflow.com/comment/80693922

vorbis
tag name: vorbis
tags question: http://stackoverflow.com/q/46789568
type: Tag

http://stackoverflow.com/comment/80697182
type: QuestionComment
has text: You have only one imagefield in your forms.py . but in your form.html you try to upload lots of images? am I right?
comment on: http://stackoverflow.com/q/46874472
score: 0
type: Comment

http://stackoverflow.com/a/46862238
has body: These matrices are called Hankel matrices. Most platforms offer already a specific routine for creating them. You can also implement yourself by removing the unnecessary parts to increase speed. It's a pretty concise code from scipy.linalg import hankel A = hankel([1,2,3,4], [4,1,2,3]) A array([[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]) It seems that it's only ~2x slower than Divakar's solution which is surprisingly fast.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46859304
type: Answer
upvote count: 2

http://stackoverflow.com/q/46872385
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80693236
has comment: http://stackoverflow.com/comment/80693389
has comment: http://stackoverflow.com/comment/80692904
upvote count: 1
tagged with: python
has body: In my df I have a multiindex like this: df.index.names FrozenList([u'Ticker', u'Date']) &lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: 189667 entries, (AAPL, 1992-08-31 00:00:00) to (^DJI, 2017-08-31 00:00:00) On a single index df I would do: from sklearn.model_selection import train_test_split df_train, df_test = train_test_split(df, test_size=0.2, shuffle=False) However, this does not work with multiindex, it just cuts the rows in 80/20. Note: I do not want random sampling, just splitting 80/20 based on date. Any clues? Edit: This is how I fetch the data in question (apart from many more than two tickers): import pandas as pd import pandas_datareader.data as web tickers = ['AAPL', 'AXP'] def get_data(tickers): ''' Dowloads daily O/H/L/C data for all symbols''' def data(ticker): return web.DataReader(ticker, 'yahoo') datas = map(data, tickers) return pd.concat(datas, keys=tickers, names=['Ticker', 'Date']) stock_data = get_data(tickers)
has comment: http://stackoverflow.com/comment/80693461
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/46874649
answer count: 1
accepted answer: http://stackoverflow.com/a/46874649
tagged with: scikit-learn
has title: How to split a multiindex df in 80/20 parts based on date?
tagged with: pandas
type: AnsweredQuestion
downvote count: 0

sqlalchemy
tags question: http://stackoverflow.com/q/46841912
tags question: http://stackoverflow.com/q/46771386
tags question: http://stackoverflow.com/q/46775801
tags question: http://stackoverflow.com/q/46904273
tags question: http://stackoverflow.com/q/46801123
tags question: http://stackoverflow.com/q/46748896
tags question: http://stackoverflow.com/q/46838929
tags question: http://stackoverflow.com/q/46855004
tags question: http://stackoverflow.com/q/46867148
tags question: http://stackoverflow.com/q/46863993
tags question: http://stackoverflow.com/q/46905119
tags question: http://stackoverflow.com/q/46891629
tags question: http://stackoverflow.com/q/46783346
tags question: http://stackoverflow.com/q/46838068
tags question: http://stackoverflow.com/q/46869376
tags question: http://stackoverflow.com/q/46812717
tags question: http://stackoverflow.com/q/46858626
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/46749550
tags question: http://stackoverflow.com/q/46793064
tags question: http://stackoverflow.com/q/46802739
tags question: http://stackoverflow.com/q/46781184
tags question: http://stackoverflow.com/q/46818858
tags question: http://stackoverflow.com/q/46864673
tags question: http://stackoverflow.com/q/46892386
tags question: http://stackoverflow.com/q/46830131
tags question: http://stackoverflow.com/q/46802063
tags question: http://stackoverflow.com/q/46893654
tags question: http://stackoverflow.com/q/46832855
tags question: http://stackoverflow.com/q/46789423
type: Tag
tags question: http://stackoverflow.com/q/46756197
tags question: http://stackoverflow.com/q/46800183
tags question: http://stackoverflow.com/q/46856436
tags question: http://stackoverflow.com/q/46879611

http://stackoverflow.com/q/46770748
type: Question
has comment: http://stackoverflow.com/comment/80487071
has comment: http://stackoverflow.com/comment/80487245
tagged with: sorting
has title: Python - binary search in sorted list of lists
has comment: http://stackoverflow.com/comment/80487072
tagged with: search
has body: Is it a way in Python 3 to binary search in sorted list of lists? Let's assume I have a list of lists: list = [['A', 'B', 3], ['C', 'D', 1], ['E', 'F', 2]] I've sorted it by 3d element in inner list with: list = sorted(list , key=itemgetter(2)) and now list is [['C', 'D', 1], ['E', 'F', 2], ['A', 'B', 3]] And now how can I search in this sorted list with binary search (O(log(n)) time complexity) using element from inner list by which sorting was done? Like findBy(list, index_of_inner_list, value_of_inner_list_to_find) Outer list is huge. Inner lists have len 50. And I need to make many queries to extract some elements from outer list based on condition related to inner lists. I was thinking about bisect but inner arrays would be a problem for it I think.
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/121249077
tagged with: list
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/80487856
linked to: http://stackoverflow.com/q/42146482

http://stackoverflow.com/comment/80651177
type: QuestionComment
type: Comment
has text: Possible duplicate of [What is the best way to call a Python script from another Python script?](https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script)
score: 1
comment on: http://stackoverflow.com/q/46851780

http://stackoverflow.com/comment/80715437
has text: Thank you for your answer. I have revised my code and removed any dependencies on `a, b` (acutally, `.args` works just fine as well). I wouldn't necessarily say that I was confused by generic textbook definitions -- just general ignorance ;-)
comment on: http://stackoverflow.com/a/46855308
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80504050
has text: Also, your "vulnerable c code" doesn't actually reach the buffer overflow vulnerability; it just unconditionally launches a shell and exits after the shell does.
comment on: http://stackoverflow.com/q/46778979
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46865263
has answer: http://stackoverflow.com/a/46866274
has answer: http://stackoverflow.com/a/46865320
tagged with: twitter
has comment: http://stackoverflow.com/comment/80722309
has comment: http://stackoverflow.com/comment/80678129
type: Question
answer count: 2
score: 0
tagged with: utf-8
type: UnansweredQuestion
has title: Streaming AP: Tracked keywords result in "error: Non-UTF-8 code... but no encoding declared"
tagged with: python
has body: I have a running code using tweepy's stream listener to stream tweets. It works just fine and I have run it a couple of times successfully, both using arabic, English, and French keywords combined. For some reason, when I insert my whole set of keywords (397) the code results in the error reading SyntaxError: Non-UTF-8 code starting with '\xd9' in file twitter_streaming_copy.py on line 67, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details Quite oddly, I have tried to run the code using different parts of the set of keywords and it works fine, it is only when I put them all together that is stops working. Any idea? Here is my code: (I'm using python 3) # Chap02-03/twitter_streaming.py #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import string import time import tweepy from tweepy import Stream from tweepy.streaming import StreamListener consumer_key = ".." consumer_secret = ".." access_key = ".-." access_secret = ".." class CustomListener(StreamListener): """Custom StreamListener for streaming Twitter data.""" def __init__(self, fname): safe_fname = format_filename(fname) self.outfile = "stream_%s.jsonl" % safe_fname def on_data(self, data): try: with open(self.outfile, 'a') as f: f.write(data) return True except BaseException as e: sys.stderr.write("Error on_data: {}\n".format(e)) time.sleep(5) return True def on_error(self, status): if status == 420: sys.stderr.write("Rate limit exceeded\n") return False else: sys.stderr.write("Error {}\n".format(status)) return True def format_filename(fname): """Convert fname into a safe string for a file name. Return: string """ return ''.join(convert_valid(one_char) for one_char in fname) def convert_valid(one_char): """Convert a character into '_' if "invalid". Return: string """ valid_chars = "-_.%s%s" % (string.ascii_letters, string.digits) if one_char in valid_chars: return one_char else: return '_' if __name__ == '__main__': query = sys.argv[1:] # list of CLI arguments query_fname =…
tagged with: tweepy

http://stackoverflow.com/q/46801367
has answer: http://stackoverflow.com/a/46801414
possible better answer: http://stackoverflow.com/a/46801382
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80549547
type: Question
has answer: http://stackoverflow.com/a/46801382
has title: Return the maximum value of two columns in a dataframe (Pandas)
accepted answer: http://stackoverflow.com/a/46801414
upvote count: 3
answer count: 3
tagged with: pandas
has body: I currently have a dataframe and would like to return the minimum value of two columns (eg. X and Y). I have tried: print(df.loc[:, ['X', 'Y']].min()) However, it prints out: Control NSAF -9.851210 Wild NSAF -9.730507 dtype: float64 Whereas I just want -9.851210. Is there a way to just get the single minimum number? Thank you
has answer: http://stackoverflow.com/a/46801539
favorite count: 0

http://stackoverflow.com/a/50259536
type: Answer
has body: You should not name your scripts with the names of python packages.This will make your python scripts in the same location to try to import modules from these files instead of original packages.Here you should not name the script as 'pywinauto.py'.Rename it and try.Also there should not be any scripts with name 'pywinauto.py' in the same location.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46774030
upvote count: 1

http://stackoverflow.com/a/46836769
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46836735
has body: Your While shouldn't be capitalized. It should be while. Also watch your indents, don't see anything inside that while block.
type: Answer
has comment: http://stackoverflow.com/comment/80621187
accepted answer of: http://stackoverflow.com/q/46836735
upvote count: 1
downvote count: 1

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/46802777
tags question: http://stackoverflow.com/q/46840875

http://stackoverflow.com/comment/80637407
type: AnswerComment
comment on: http://stackoverflow.com/a/46844700
has text: How to use a for loop in {% url %}??
type: Comment
score: 0

http://stackoverflow.com/a/46884691
upvote count: 2
score: 2
has body: You may want to check this tutorial about Using Google Service Accounts with Google Apps Script. This sample code shows how to use OAuth in Google Apps Script using Service Accounts. For this code to work, you need to create a Google Service account with domain-wide delegation, substitute the private key and client client email with the actual values and also add the Client Id to your Google Apps admin console with the Drive API Scope. The OAuth 2.0 access tokens are stored in the Script Properties. var JSON = { "private_key": "Your Private Key", "client_email": "serviceacount@project-ctrlq.iam.gserviceaccount.com", "client_id": "1234567890", "user_email": "amit@labnol.org" }; function getOAuthService(user) { return OAuth2.createService("Service Account") .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setPrivateKey(JSON.private_key) .setIssuer(JSON.client_email) .setSubject(JSON.user_email) .setPropertyStore(PropertiesService.getScriptProperties()) .setParam('access_type', 'offline') .setScope('https://www.googleapis.com/auth/drive'); } function getUserFiles() { var service = getOAuthService(); service.reset(); if (service.hasAccess()) { var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1'; var response = UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + service.getAccessToken() } }); Logger.log(response.getContentText()); } } function reset() { var service = getOAuthService(); service.reset(); } Also, if you are getting the 403 Insufficient permission error, it is likely because the application is requesting access to API scopes that are not authorized in the Google Apps admin console. The invalid_grant error is likely due to incorrect date and time settings of the server that is hosting the application.
accepted answer of: http://stackoverflow.com/q/46773093
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46773093
type: Answer

http://stackoverflow.com/comment/80749536
comment on: http://stackoverflow.com/q/46901247
score: 0
type: QuestionComment
has text: I'd say you need `pd.crosstab` with a custom `aggfunc` but nothing more can be said without some sample data.
type: Comment

http://stackoverflow.com/comment/80746826
comment on: http://stackoverflow.com/q/46899816
has text: And Remove the extra () in the first url.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80736573
type: QuestionComment
has text: Instead of regex, how about `if key in string`
comment on: http://stackoverflow.com/q/46893798
score: 0
type: Comment

http://stackoverflow.com/a/66252406
downvote count: 0
score: 1
has body: For that kind of problems, do not think language specific. Let me clarify your problem first. I will give an example of my previous experiment. (I have created a new account, so that my reputation is very low and images are shown as links) This was my original image: original_image When I used HoughLinesP, I got a result like this: houghlinep_result I would be happy to see only two lines, but I got a list of similar lines like this: [[[ 0 59 104 3]] [[ 2 59 56 32]] [[ 96 3 174 57]] [[ 4 59 49 36]] [[125 25 174 58]] [[ 53 34 99 7]] [[111 12 165 50]]] My target is to have two lines: better_result [[ 0 59 104 3] [ 96 3 174 57]] This is what I wanted because they were on same line with different lengths and very similar angles. If this solution to my problem is what you need, you can find the angle between two points and check if a similar angle already exists. A small piece of example: lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), min_line_length, max_line_gap) cleans = np.empty(shape=[0,4], dtype=np.int32) for l in lines: alfa = degrees(atan2(l[0][2]-l[0][0], l[0][3]-l[0][1])) if len(cleans) == 0: cleans = np.append(cleans, [l[0]], axis=0) continue similar = False for c in cleans: beta = degrees(atan2(c[2]-c[0], c[3]-c[1])) if abs(alfa-beta) &lt;= 3.5: similar = True break if not similar: cleans = np.append(cleans, [l[0]], axis=0) print(cleans) for line in [cleans]: for x1,y1,x2,y2 in line: cv2.line(img,(x1,y1),(x2,y2),255,2) It finds the angle between two points with atan2 function. Please remember, the code is not optimized. It compares the angles with a threshold, 3.5 in the example. If it is lower than the threshold, it thinks that it is a similar line and does not add into the clean array. In your problem, if you have more than 2 lines and may have similar angles in different coordinates, you have to make an extra check, maybe with a grid size. If that is the case, please share a couple of screenshots.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/46845648

pyinstaller
tags question: http://stackoverflow.com/q/46882932
tags question: http://stackoverflow.com/q/46815533
type: Tag
tags question: http://stackoverflow.com/q/46818993
tags question: http://stackoverflow.com/q/46819980
tag name: pyinstaller
tags question: http://stackoverflow.com/q/46878270
tags question: http://stackoverflow.com/q/46888362
tags question: http://stackoverflow.com/q/46889668
tags question: http://stackoverflow.com/q/46876110

http://stackoverflow.com/comment/80645576
comment on: http://stackoverflow.com/a/46849108
score: 0
type: Comment
has text: it's a typo while writing the question!
type: AnswerComment

http://stackoverflow.com/q/46867907
answer count: 3
has answer: http://stackoverflow.com/a/47372117
possible better answer: http://stackoverflow.com/a/47015828
has answer: http://stackoverflow.com/a/47015828
downvote count: 0
score: 11
has title: Starting Kivy service on bootup (Android)
linked to: http://stackoverflow.com/q/32031178
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47372117
has comment: http://stackoverflow.com/comment/80712138
has answer: http://stackoverflow.com/a/74140962
favorite count: 0
has comment: http://stackoverflow.com/comment/81024409
has comment: http://stackoverflow.com/comment/81067618
type: Question
linked to: http://stackoverflow.com/q/47362161
tagged with: android
tagged with: python
tagged with: kivy
upvote count: 11
has comment: http://stackoverflow.com/comment/80745594
has body: I'm trying to start my kivy app's service on bootup. I'm sure that my service is ok because it works when I start my app. But on bootup I have a problem. I've read this article and tried to make it: package net.saband.myapp; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.Context; import org.kivy.android.PythonActivity; public class MyBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Intent ix = new Intent(context, PythonActivity.class); ix.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(ix); } } It works but starts the app but not the service. So I've studied some questions on StackOverflow and changed my code for this: package net.saband.myapp; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.Context; import net.saband.myapp.ServiceMyservice; public class MyBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Intent ix = new Intent(context, ServiceMyservice.class); ix.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(ix); } } ... and got an error: 10-21 19:16:44.784 1513 1569 I ActivityManager: Start proc 6334:net.saband.myapp:service_myservice/u0a116 for service net.saband.myapp/.ServiceMyservice 10-21 19:16:44.786 6334 6334 I art : Late-enabling -Xcheck:jni 10-21 19:16:44.885 6334 6334 D AndroidRuntime: Shutting down VM 10-21 19:16:44.888 6334 6334 E AndroidRuntime: FATAL EXCEPTION: main 10-21 19:16:44.888 6334 6334 E AndroidRuntime: Process: net.saband.myapp:service_myservice, PID: 6334 10-21 19:16:44.888 6334 6334 E AndroidRuntime: Theme: themes:{} 10-21 19:16:44.888 6334 6334 E AndroidRuntime: java.lang.RuntimeException: Unable to start service net.saband.myapp.ServiceMyservice@8c96929 with Intent { cmp=net.saband.myapp/.ServiceMyservice }: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.…
tagged with: java

http://stackoverflow.com/comment/138408646
type: Comment
comment on: http://stackoverflow.com/a/46860649
has text: what a relief, so bad
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80499302
type: QuestionComment
has text: See [here](https://stackoverflow.com/questions/8717179/chunking-data-from-a-large-file-for-multiprocessing) for an example of using multiprocessing to read chunks of data from a CSV. I would also think about using something like HDF5 (and python package h5py) for managing data files that large.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46776588

http://stackoverflow.com/comment/80643297
comment on: http://stackoverflow.com/a/46846714
has text: Your code is full of errors. As I said, use one of the built-in examples provided to you when creating a lambda function and start from there
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/46869238
has comment: http://stackoverflow.com/comment/80685650
has body: Since you are assigning a variable, you only use 1 equal sign. So Max_Force == Force needs to be Max_Force = Force and these lines: else: Max_Force == Max_Force #there should only be 1 equal sign btw are unnecessary since there is no reason to set a variable to itself. You also need to move Max_Force = 0 above the while True loop since you are constantly setting Max_Value back to 0.
accepted answer of: http://stackoverflow.com/q/46869099
has comment: http://stackoverflow.com/comment/80685784
answers question: http://stackoverflow.com/q/46869099
has comment: http://stackoverflow.com/comment/80685814
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80685745
type: Answer

http://stackoverflow.com/comment/80641375
type: QuestionComment
comment on: http://stackoverflow.com/q/46846794
score: 0
has text: the proper solution is not to weakens your site's security by allowing to reset the superuser's password TTW if the superuser has no password (which would allow anyone to reset the superuser's password...), but to create the superuser with a password right from the start. The question I linked to has many suggestions on how to do this, the best one IMHO being the custom management command.
type: Comment

lemmatization
type: Tag
tag name: lemmatization
tags question: http://stackoverflow.com/q/46779116

http://stackoverflow.com/comment/109838414
has text: I tested this solution and it didn't work for some gifs. The issue was, that PIL tries to optimize the pallet again during the save process, which can change the transparency index. To avoid this, you need to pass `optimize=False` to the save function.
comment on: http://stackoverflow.com/a/51219787
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/80752516
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46902090
has text: Generally AJAX is used when no page navigation is needed. Any specific reason for you to use AJAX instead of the HTML form, which according to you is working perfectly fine??
type: Comment

http://stackoverflow.com/comment/80470058
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46761013
type: QuestionComment
has text: Thanks very much for that.

http://stackoverflow.com/comment/80508776
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46781256
type: AnswerComment
has text: @alvas should be a `list`

http://stackoverflow.com/comment/108428164
type: Comment
has text: You shouldn't define self type because you can call some function from an inherited class.
type: AnswerComment
comment on: http://stackoverflow.com/a/46779290
score: 0

http://stackoverflow.com/comment/80619260
type: QuestionComment
comment on: http://stackoverflow.com/q/46835757
type: Comment
has text: @PatrickHaugh - I am using sorted. What should I be doing differently?
score: 0

http://stackoverflow.com/q/46842225
possible better answer: http://stackoverflow.com/a/46842260
has body: I have following dataframe: name gender count 0 A M 3 1 A F 2 2 A Nan 3 3 B NaN 2 4 C F 4 5 D M 5 6 D Nan 5 I would like to build a resulting dataframe df1 which deletes that last row of group of name attribute if the count of that group is greater than 1. For eq- name A is present 3 times, hence the last row containing A should be removed. B and C are only present once, hence the rows containing them should be retained. Resulting dataframe df1 should be like this: name gender count 0 A M 3 1 A F 2 2 B NaN 2 3 C F 4 4 D M 5 Please advice.
type: AnsweredQuestion
score: 2
has title: Removing last rows of each group based on condition in a pandas dataframe
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/46842252
type: Question
answer count: 2
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/46842260
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/46842252
upvote count: 2

http://stackoverflow.com/q/46870769
score: 0
has comment: http://stackoverflow.com/comment/80688896
answer count: 1
has comment: http://stackoverflow.com/comment/80689917
has body: import urllib.request def read_text(): quotes = open(r"C:\Users\Intel\Google Drive\Udacity\Full Stack\AbdoulCoverLetter.txt") contents_of_files = quotes.read() print(contents_of_files) quotes.close() check_profanity(contents_of_files) My code is showing the following error: UnicodeEncodeError: 'ascii' codec can't encode character '\u2022' in position 154: ordinal not in range(128) I am not sure what is the issue. Please help.. def check_profanity(text_to_check): with urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check) as response: connection = response.read() output = connection.read() connection.close() read_text()
has answer: http://stackoverflow.com/a/46871480
has comment: http://stackoverflow.com/comment/80688865
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80689616
has comment: http://stackoverflow.com/comment/80688810
has comment: http://stackoverflow.com/comment/80689028
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/46871480
has comment: http://stackoverflow.com/comment/80689032
has title: Udacity Fundamental of programming with Python:

http://stackoverflow.com/comment/80707118
has text: @Parfait, OP did the same problem two different ways, only experimenting with pandas to see if it was faster (it was not.) There's no reason to use pandas at all, so we should ignore that part. I'm comparing `test2` computed by my code to the first `test` list computed by the python list comprehension several lines above.
comment on: http://stackoverflow.com/a/46879774
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/46892078
has answer: http://stackoverflow.com/a/46892142
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/80731343
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46892142
downvote count: 1
type: Question
upvote count: 0
has body: rock paper scissors code. supposed to choose a random one and put it against a user inputed choice, it works sometimes but others on the same possibility where it should be the same it changes outcomes import random def one_game(): score_bot = 0 score_player = 0 a = ["rock", "paper", "scissors"] UI = raw_input('(enter your choice rock, paper, or scissors)') print(random.choice(a)) if (random.choice(a)) == (UI): print ('Tie') score_bot+1 score_player+1 elif 'rock' in (UI) and 'scissors' in (random.choice(a)): print ('You win!') score_player+1 elif 'rock' in (UI) and 'paper' in (random.choice(a)): print ('You lose!') score_bot+1 elif 'paper' in (UI) and 'scissors' in (random.choice(a)): print ('You lose!') score_bot+1 elif 'paper' in (UI) and 'rock' in (random.choice(a)): print ('You win!') score_player+1 elif 'scissors' in (UI) and 'rock' in (random.choice(a)): print ('You lose!') score_bot+1 elif 'scissors' in (UI) and 'paper' in (random.choice(a)): print ('You win!') score_player+1 print (score_player) print (score_bot) if (score_bot) &gt; (score_player): print ('bot wins!') elif (score_bot) &lt; (score_player): print ('Player wins!') the issue
tagged with: python-2.7
has title: Program getting elif messed up
answer count: 1

http://stackoverflow.com/comment/132712097
type: Comment
comment on: http://stackoverflow.com/a/73497694
type: AnswerComment
score: 0
has text: If you're going this route, a cleaner way is to use [SimpleNamespace](https://docs.python.org/3/library/types.html?highlight=simplenamespace#types.SimpleNamespace).

http://stackoverflow.com/comment/80692871
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46872808
has text: I added the class definition to OP, you are right im having trouble when I do that one. it gives me 'missing 3 required positional arguments: 'weight', 'height', and 'age'.

http://stackoverflow.com/comment/80536321
type: Comment
comment on: http://stackoverflow.com/a/46794762
has text: This helped with the y-axis! But the first row in my file is years written as (64 65 66 ... 14 15 16). How do I get the x-axis to display this? Currently it displays 1-37. Also, I do not want there to be a legend. I just want the same color for all bars. Write now my legend reflects the years properly. I want what is in my legend to be displayed as the x-axis.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80617403
type: AnswerComment
has text: I've extracted 50 elements, trained the model without them and evaluate the probability in those items. Output looks more clearly more logical (between 50% - 50% to 68% - 32%). I'll focus on this solution for now, Thanks for the solution !
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46834162

http://stackoverflow.com/comment/80687927
comment on: http://stackoverflow.com/a/46869944
type: AnswerComment
score: 0
type: Comment
has text: Yes I do use namespace to improve the url constructions

http://stackoverflow.com/q/46813982
accepted answer: http://stackoverflow.com/a/46814144
has comment: http://stackoverflow.com/comment/80575347
has comment: http://stackoverflow.com/comment/80575276
possible better answer: http://stackoverflow.com/a/46815616
tagged with: n-gram
has answer: http://stackoverflow.com/a/46815616
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80575242
has answer: http://stackoverflow.com/a/46814144
tagged with: python
tagged with: text
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/80575318
upvote count: 2
has title: Number of times a bigram has been seen in a list up to a point
has answer: http://stackoverflow.com/a/46814091
type: Question
has body: Let's say I have a text like this: 'he is hdajs asdas da he is not asd as da s i am a da daas you am a' I have created all the bigrams from this text: &gt;&gt;&gt; bigrams_ [('he', 'is'), ('is', 'hdajs'), ('hdajs', 'asdas'), ('asdas', 'da'), ('da', 'he'), ('he', 'is'), ('is', 'not'), ('not', 'asd'), ('asd', 'as'), ('as', 'da'), ('da', 's'), ('s', 'i'), ('i', 'am'), ('am', 'a'), ('a', 'da'), ('da', 'daas'), ('daas', 'you'), ('you', 'am'), ('am', 'a')] Now I like to create a new list of bigrams where the first element of each bigram would be a positional index that shows how many times a certain bigram from the above format has been seen up to a point in text, and the second element would be the bigram of words from the initial list. For example, in the above list, the last element ('am', 'a') has been seen 2 times, so in the new list it would correspond to this bigram: (2, ('am', 'a')). What would be a concise Pythonic way of doing this.

http://stackoverflow.com/q/46897417
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80754141
score: 1
tagged with: methods
has comment: http://stackoverflow.com/comment/80742036
type: Question
has title: Convert a bound method in python to a function (and reduce arg count)
has answer: http://stackoverflow.com/a/79412956
tagged with: function
possible better answer: http://stackoverflow.com/a/61155832
has answer: http://stackoverflow.com/a/46985404
has answer: http://stackoverflow.com/a/61155832
tagged with: flask
has comment: http://stackoverflow.com/comment/80742013
favorite count: 0
has comment: http://stackoverflow.com/comment/80742759
accepted answer: http://stackoverflow.com/a/46985404
has answer: http://stackoverflow.com/a/46921516
has body: I am adding a URL handler to a Flask application using add_url_rule. It requires a function as a handler (not a method). However, for proper encapsulation, my intended function is a bound method that uses the self variable. Is there any way I can somehow make Flask see my function: def action(self, param) as def action(param) ? class A(): def __init__(self): self._localvar = 5 self._flask = Flask("testapp") def add_rules(self): self._flask.add_url_rule("/","root",????) def action(self, value): print("The value is {}".format(self._localvar)) def run(self): self._flask.run() app = A() app.add_rules() app.run() what I want to do is replace ???? with app.action, a bound method. However, add_url_rule expects a function. I tried app.action.__func__ and app.action.im_func which are function pointers. However, the function signature is still going to require self and will give me a runtime error. My current solution is to have some loose functions in my module and have app just use them directly, but it just seems that there has to be a cleaner way since the handlers are really tightly coupled to the app object and I don't want them floating around outside of it.
has comment: http://stackoverflow.com/comment/80742624
tagged with: python
has comment: http://stackoverflow.com/comment/80742425
answer count: 4
has comment: http://stackoverflow.com/comment/80743828
has comment: http://stackoverflow.com/comment/80742709
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/80742687
linked to: http://stackoverflow.com/q/963965

http://stackoverflow.com/comment/80694193
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46830666
has text: I have added it
score: 0

http://stackoverflow.com/q/46779154
has answer: http://stackoverflow.com/a/46779335
downvote count: 0
has title: Override Enum metaclass initialization
possible better answer: http://stackoverflow.com/a/46779335
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46780742
has body: Although pylint raises a warning on enum.Enum(value=..., names=...), I see from the enum doc that one could programmatically create an Enum like the following import re import enum import termios def termios_baud_rates(): regexp = r"(?:^|,)B(?P&lt;rate&gt;\d+)" rates = sorted(map(int, re.findall(regexp, ",".join(dir(termios))))) return {"B{:d}".format(r): r for r in rates} BAUD_RATES = enum.Enum("BAUD_RATES", termios_baud_rates()) But I'd also like to add methods: @classmethod def valid_rate(cls, value): return (any(value == item.value for item in cls)) I think this should involve overloading metaclass __prepare__(mcls, names, bases) to augment bases with the names dict, but apparently bases is not how the Enum attributes are created. Anyone have any tips?
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80504280
tagged with: enums
accepted answer: http://stackoverflow.com/a/46780742
answer count: 3
has answer: http://stackoverflow.com/a/47302436

http://stackoverflow.com/comment/89572074
score: 2
has text: But would putting a dictionary in SQL DB is the recommended practice when the same is fetched and further processed
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46899529

http://stackoverflow.com/a/46824416
accepted answer of: http://stackoverflow.com/q/46824333
answers question: http://stackoverflow.com/q/46824333
score: 0
has body: In def union instead of print use return. def union(A, B): AuB = A.union(B) total = (AuB,len(AuB)) return total
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/46769520
type: Question
has body: I tried to read some Korean text file encoded in 'euc-kr' in python but had some errors raised. After inspecting encodings module for a while, I learned that this module encodes Korean characters seemingly very weird way. Let me take an example Korean character 탇 (which is an rarely used character, but i need this for pronunciation dictionary) is supposed to be encoded to B5 6E according to EUC-KR spec (I referred to this site). But encodings module gives me somewhat different result. # python3 &gt;&gt; from encodings import euc_kr &gt;&gt; euc_kr.codec.decode(b'\xB5\x6E') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'euc_kr' codec cant decode byte 0xb5 in position 0: illegal multibyte sequence &gt;&gt; euc_kr.codec.encode('탙') (b'\xa4\xd4\xa4\xbc\xa4\xbf\xa4\xbc', 1) As you can see, I get an error when I try to decode B5 6E and euc_kr.codec.encode gives me longer bytes than I expected. I have no clue what's happening there. How can I avoid raising an error when I decode B5 6E(and many other Korean characters)? Is there another document about EUC-KR specification that I can read to understand how python implementation of EUC-KR work?
score: 5
tagged with: encoding
has comment: http://stackoverflow.com/comment/80490122
has answer: http://stackoverflow.com/a/46774355
accepted answer: http://stackoverflow.com/a/46774355
answer count: 1
tagged with: unicode
favorite count: 0
upvote count: 5
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: character-encoding
has title: Python encodes (Korean) characters in an unexpected way with euc-kr encoding (codecs, encodings module)

http://stackoverflow.com/comment/80550341
score: 10
type: QuestionComment
comment on: http://stackoverflow.com/q/46801747
type: Comment
has text: Python `list`s can already be used as stacks. `lst.append` is push, `lst[-1]` is peek, `lst.pop()` is... pop. [Relevant docs](https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks)

http://stackoverflow.com/comment/80485286
type: Comment
comment on: http://stackoverflow.com/a/46769787
has text: @JafferWilson just edited the answer, check it to see if it is clearer now.
score: 0
type: AnswerComment

http://stackoverflow.com/a/46792970
answers question: http://stackoverflow.com/q/46792667
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: I would do it this way: original = '{(Entertainment (Adult), S), (Performing Arts, S), (Comedy Club, S), ($, S), (Comedy, P), (18+, S), (Plays &amp; Shows, P)}' splited = original[1:-1].split(',') splited = list(map(lambda x: x.strip(), splited)) grouped = [] for i in range(0, len(splited), 2): grouped.append((splited[i][1:], splited[i+1][:-1])) print(grouped) Use the variable names you prefer. I first use [1:-1] to delete the first and last chars ({ &amp; }) and then split by commas. I then .strip() every part to delete initial and final white-spaces. Last I iterate over the list with an step of 2 and delete the first char of odd elements (() and the last char of even elements ()). I append the resulting tuple into a new list.

http://stackoverflow.com/comment/80462527
comment on: http://stackoverflow.com/a/46758564
score: 0
has text: Ah! I forgot that spaces mean multiple classes. Thank you.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80451476
has text: Is there any way to publish these graphs (live) to a URL and just embed that URL in the website, without having to constantly run the Python file?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46752813
score: 0

http://stackoverflow.com/comment/80622763
type: AnswerComment
has text: Yes! That did it. I think this is actually the answer to another question I posted, too:https://stackoverflow.com/questions/46819746/import-error-from-django-core-handlers-wsgi-import-status-code-text, could you post this answer there and I'll mark it as the answer as well?
type: Comment
comment on: http://stackoverflow.com/a/46837369
score: 0

http://stackoverflow.com/comment/80564774
has text: Your output doesn't match the corpus you provided.
type: Comment
comment on: http://stackoverflow.com/q/46808855
score: 1
type: QuestionComment

http://stackoverflow.com/q/46820963
type: Question
answer count: 1
downvote count: 0
tagged with: while-loop
has answer: http://stackoverflow.com/a/46820992
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: Adding game names to a file?
upvote count: 1
has body: Hello I'm doing a school assignment with these instructions Write a while loop that prompts users for their favorite game. When they enter the name of the game, print a message to the screen and add a line recording their log in a file called games.txt. Make sure each entry appears on a new line in the file. I'm having trouble making the loop ask multiple times instead of just adding the game over and over again. Also, I don't want the games.txt file to lose the previous games that were added. This is my current code: filename = 'games.txt' print("When you want to finish adding games just type 'done'") game = input('Whats your favorite game? ') with open(filename, 'w') as file_object: while game != 'done': print(game) file_object.write(game + str("\n) As you can see if I run it and I put "Destiny 2" as a game it will keep adding the destiny 2 to the file named games.txt until I stop the program.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46820992
score: 1

tic-tac-toe
tags question: http://stackoverflow.com/q/46902467
tag name: tic-tac-toe
type: Tag

http://stackoverflow.com/comment/80547323
type: Comment
comment on: http://stackoverflow.com/q/46799619
score: 0
has text: Can you [edit] this to make it more obvious to a casual reader why it isn't a duplicate of [How to clone or copy a list](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list)?
type: QuestionComment

http://stackoverflow.com/comment/80486422
has text: An example data would be better to understand
comment on: http://stackoverflow.com/q/46770134
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/134977935
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46788110
has text: While it is true that Pandas offers that option, doesn't it create a copy of the data to store it as a pd.DataFrame object, therefore (at least) duplicating the memory needed? Because that might be costly in some applications where the dictionary is not just a small one.
type: AnswerComment

http://stackoverflow.com/comment/120530850
score: 1
has text: Python3 has committed that dicts will be ordered going forward, so you can rely on it.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46788137

http://stackoverflow.com/q/46893770
has comment: http://stackoverflow.com/comment/80736016
has comment: http://stackoverflow.com/comment/80735320
has comment: http://stackoverflow.com/comment/80734819
type: Question
score: 0
has body: Hi guys i want to convert link into proper format for example i have text like This is google link https://www.google.com This is gmail link https://www.gmail.com And what i want is This is google link https://www.google.com This is gmail link https://www.gmail.com and here is code that i have written body_without_quotes = request.POST.get('stripped-text', '') data1 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body_without_quotes) for da in data1: link = ""+da+"" body_without_quotes = body_without_quotes.replace(da, link) print body_without_quotes but it does not print required output can anyone tell me what i am doing wrong here.This is the output i am getting right now This is gogle link https://www.google.com>https://www.google.com This is gmail link https://www.gmail.com <https://www.google.com>https://www.google.com> Thanks
has comment: http://stackoverflow.com/comment/80735169
has comment: http://stackoverflow.com/comment/80734761
has comment: http://stackoverflow.com/comment/80734848
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/80734867
has comment: http://stackoverflow.com/comment/80735198
has comment: http://stackoverflow.com/comment/80735673
has title: Replace string with other string python django
has comment: http://stackoverflow.com/comment/80735812

http://stackoverflow.com/q/46895157
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/80737381
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46895656
possible better answer: http://stackoverflow.com/a/46895322
tagged with: python
has body: I am tackling a problem with a dictionary containing a chemical reaction and its associated voltage. The dictionary is made from a .txt file, and I would very much like to be able to input a desired voltage (i.e. 2), and have the code give me the reaction with the value closest to the input. The .txt file looks like this (shortened): left side of reaction|right side of reaction|voltage. F2(g)+2e–|2F–(aq)|+2.87 Co3+(aq)+e–|Co2+(aq)|+1.82 Pb4+(aq)+2e–|Pb2+(aq)|+1.8 H2O2(aq)+2H+(aq)+2e–|2H2O|+1.77 I have made this code here to get the voltages as keys, and only the left side of reaction as a value. from collections import defaultdict import operator with open('redoxacid.txt', 'r') as document: next(document) answer = {} for line in document: line = line.strip('\n') line = line.split('|') if not line: continue answer[line[0]] = line[2] #here we have the reactions as key, and volt as value. res = dict((v, k) for k, v in answer.items()) #flipping values in dictionary sorted(answer.items(), key=lambda x: x[-1]) #print(res) userinput = input("Voltage? ") for k, v in res.items(): print(k,v) #I now have two values here, voltage and reaction #????? when I print I get this: +2.87 F2(g)+2e– +1.82 Co3+(aq)+e– +1.8 Pb4+(aq)+2e– +1.77 H2O2(aq)+2H+(aq)+2e– +1.7 NiO2(s)+4H+(aq)+2e– ....and so on How can I now take a user input(a number) and find the value most like it inside my dict/list ? say if I take input = 2, then the code finds the value approximately equal to that and prints the corresponding reaction.
tagged with: dictionary
has answer: http://stackoverflow.com/a/46895322
accepted answer: http://stackoverflow.com/a/46895361
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has title: Finding a key corresponding to an approximate user input value
has answer: http://stackoverflow.com/a/46895361

http://stackoverflow.com/q/46850850
answer count: 5
tagged with: python
has body: I was asked once to create a function that given a string, remove a few characters from the string. Is it possible to do this in Python? This can be done for lists, for example: def poplist(l): l.pop() l1 = ['a', 'b', 'c', 'd'] poplist(l1) print l1 &gt;&gt;&gt; ['a', 'b', 'c'] What I want is to do this function for strings. The only way I can think of doing this is to convert the string to a list, remove the characters and then join it back to a string. But then I would have to return the result. For example: def popstring(s): copys = list(s) copys.pop() s = ''.join(copys) s1 = 'abcd' popstring(s1) print s1 &gt;&gt;&gt; 'abcd' I understand why this function doesn't work. The question is more if it is possible to do this in Python or not? If it is, can I do it without copying the string?
possible better answer: http://stackoverflow.com/a/46850944
has answer: http://stackoverflow.com/a/46850969
has comment: http://stackoverflow.com/comment/80649165
upvote count: 5
accepted answer: http://stackoverflow.com/a/46850949
has title: Python function to modify string
downvote count: 1
has answer: http://stackoverflow.com/a/46850991
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46850957
has answer: http://stackoverflow.com/a/46850949
has comment: http://stackoverflow.com/comment/80649109
has answer: http://stackoverflow.com/a/46850944
has comment: http://stackoverflow.com/comment/80650074
has comment: http://stackoverflow.com/comment/80649594
type: Question
has comment: http://stackoverflow.com/comment/80649241
tagged with: string
score: 4
has comment: http://stackoverflow.com/comment/80649885
favorite count: 0
has comment: http://stackoverflow.com/comment/80651195
tagged with: python-2.7

http://stackoverflow.com/a/46844517
answers question: http://stackoverflow.com/q/46844231
score: 1
accepted answer of: http://stackoverflow.com/q/46844231
type: AcceptedAnswer
downvote count: 0
has body: I found a solution : from urllib.request import urlopen xml = open("import.xml", "r+") xml.write(urlopen('URL').read().decode('utf-8')) xml.close() Thanks for your help.
has comment: http://stackoverflow.com/comment/96790502
type: Answer
upvote count: 1

http://stackoverflow.com/q/46825989
tagged with: pyqt5
has title: How set options for a QInputDialog
type: AnsweredQuestion
tagged with: qinputdialog
score: 1
has body: I am trying to set some options for my QInputDialog. But if I call getText these settings have no effect. How do I change the appearance of the window that pops up from getText? import sys from PyQt5 import QtWidgets, QtCore class Mywidget(QtWidgets.QWidget): def __init__(self): super(Mywidget, self).__init__() self.setFixedSize(800, 600) def mousePressEvent(self, event): self.opendialog() def opendialog(self): inp = QtWidgets.QInputDialog() ##### SOME SETTINGS inp.setInputMode(QtWidgets.QInputDialog.TextInput) inp.setFixedSize(400, 200) inp.setOption(QtWidgets.QInputDialog.UsePlainTextEditForTextInput) p = inp.palette() p.setColor(inp.backgroundRole(), QtCore.Qt.red) inp.setPalette(p) ##### text, ok = inp.getText(w, 'title', 'description') if ok: print(text) else: print('cancel') if __name__ == '__main__': qApp = QtWidgets.QApplication(sys.argv) w = Mywidget() w.show() sys.exit(qApp.exec_())
type: Question
tagged with: pyqt
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46831348
accepted answer: http://stackoverflow.com/a/46831348
tagged with: python

http://stackoverflow.com/q/46757806
has comment: http://stackoverflow.com/comment/80460853
has answer: http://stackoverflow.com/a/46757922
has comment: http://stackoverflow.com/comment/80461063
has body: So I'm still relatively new to Python programming and so at the moment I'm just trying to create a simple password program. If the use has opened the program before, then it will skip the create a password bit. I have done this by creating a file which will contain the number of times the file has been opened. If the number is less than 1 then it will ask for the new password. This bit works fine, I just have the problem that when running the following code, "None" is printed. I understand the whole function return bit but the code I'm using isn't in a function so I'm not sure why it is happening. Would really appreciate help in fixing this! fo = open("openNo.txt", "r") openNo = fo.read() if int(openNo)&lt;1: pw = input(print("Please enter a password: ")) #creating a new password pwCheck = pw else: pwCheck = input(print("Please enter your password: ")) #using an existing password fo.close() if pwCheck == "password": print("Welcome!") else: print("access denied")
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80460994
type: AnsweredQuestion
has title: Python prints None despite not being inside function
has comment: http://stackoverflow.com/comment/80460927
type: Question
has answer: http://stackoverflow.com/a/46757861
accepted answer: http://stackoverflow.com/a/46757861
possible better answer: http://stackoverflow.com/a/46757922
answer count: 2

http://stackoverflow.com/a/46755128
answers question: http://stackoverflow.com/q/46755095
has body: Given: a = [1, 2, 1, 4, 5, 7, 8, 4, 6] One liner: b = [x for x in a if a.count(x) == 1]
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/46764981
score: -1
has title: TypeError: Can't convert 'int' object to str implicitly even after trying conversion and formatting
answer count: 1
downvote count: 1
has body: I'm trying to create a simple histogram in the shell to give a dictionary with keys which have their values as the probability of the key being chosen if the keys were selected at random. I used formatting which for some reason didn't work. I also did the explicit conversion as usual by using the str() function but i still got the same error. I used a for loop and for some reason it worked when the probability of the key was 1 but it gave an error afterwards. This is the debug window: def histogram(word): 'takes a word and returns an histogram of it' d = dict() for letter in word:`enter code here` d[letter] = d.get(letter,0) + 1 return (d) &gt;&gt;&gt; h = histogram('mississipi') &gt;&gt;&gt; print (h) {'i': 4, 'p': 1, 's': 4, 'm': 1} This part worked fine but then the problem surfaced def histogram(word): 'takes a word and returns an histogram of it' d = dict() for letter in word: d[letter] = '{}/{}'.format((d.get(letter,0) + 1),len(word)) return d &gt;&gt;&gt; print (histogram('mississippi')) Traceback (most recent call last): File "&lt;pyshell#4&gt;", line 1, in &lt;module&gt; print (histogram('mississippi')) File "&lt;pyshell#3&gt;", line 5, in histogram d[letter] = '{}/{}'.format((d.get(letter,0) + 1),len(word)) TypeError: Can't convert 'int' object to str implicitly def histogram(word): 'takes a word and returns an histogram of it' d = dict() for letter in word: d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word)) return d &gt;&gt;&gt; print (histogram('mississippi')) Traceback (most recent call last): File "&lt;pyshell#8&gt;", line 1, in &lt;module&gt; print (histogram('mississippi')) File "&lt;pyshell#7&gt;", line 5, in histogram d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word)) TypeError: Can't convert 'int' object to str implicitly After this it seemed to work but still showed error def histogram(word): 'takes a word and returns an histogram of it' d = dict() for letter in word: d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word)) p…
has comment: http://stackoverflow.com/comment/80475443
favorite count: 0
has answer: http://stackoverflow.com/a/46765216
type: UnansweredQuestion
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/80475386
type: Question

http://stackoverflow.com/comment/80747682
has text: Many thanks. It worked. I might need to change this a bit.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46895458
type: AnswerComment

http://stackoverflow.com/a/46907564
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46905049
accepted answer of: http://stackoverflow.com/q/46905049
has body: You simply need to set the variable assigned to the variable attribute of the Radiobutton to a value not assigned in your Radiobutton, like the below: from tkinter import * root = Tk() var = StringVar() var.set(None) radio = Radiobutton(root, text="Option1", variable=var, value=True) radio.pack() root.mainloop()
type: AcceptedAnswer

http://stackoverflow.com/comment/80565599
comment on: http://stackoverflow.com/a/46808198
type: Comment
has text: The SVM code in dlib is nearly 10 years old and used by a lot of people as well. So I'm not worried about robustness. As for names, yes, the names are funny. This is because the trainers in C++ are templated. So you can have svm_c_trainer<liner_kernel> or svm_c_linear_trainer<linear_kernel> or svm_c_trainer<rbf_kernel> or whatever. The python names are trying to reflect the combination of class and kernel selection.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/80658043
type: QuestionComment
score: 2
has text: If you don't have a `readline` library, you're going to need one. Dunno what you'd install to get that on Mint.
comment on: http://stackoverflow.com/q/46855278
type: Comment

http://stackoverflow.com/a/46829731
answers question: http://stackoverflow.com/q/46813667
downvote count: 0
score: 5
has body: I don't think there exists a more elegant solution to this, because this the designed behavior. tf.control_dependencies is a shortcut of tf.Graph.control_dependencies call using a default graph, and here's the quote from its documentation: N.B. The control dependencies context applies only to ops that are constructed within the context. Merely using an op or tensor in the context does not add a control dependency. The following example illustrates this point: # WRONG def my_func(pred, tensor): t = tf.matmul(tensor, tensor) with tf.control_dependencies([pred]): # The matmul op is created outside the context, so no control # dependency will be added. return t # RIGHT def my_func(pred, tensor): with tf.control_dependencies([pred]): # The matmul op is created in the context, so a control dependency # will be added. return tf.matmul(tensor, tensor) So just use tf.identity(summary), as suggested in the comments.
type: AcceptedAnswer
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/46813667

http://stackoverflow.com/comment/80570967
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the pointers. I narrowd the issue to this line `value = pdf.pq('LTTextLineHorizontal:in_bbox("%s, %s, %s, %s")' % ( left_corner, bottom_corner - 20, right_corner + 200, top_corner)).text()`. `print(value)` was throwing exception. Changing it to `print(value.encode('ascii', 'ignore')` fixed it. Is there a better way to do this? Or do I need to encode all values extracted from PDF?
comment on: http://stackoverflow.com/q/46811245

http://stackoverflow.com/q/46902138
tagged with: python
answer count: 1
has body: So I have this problem of making batch in my code, the thing is, I tried to search how we do batching but all I found was using some method like next_batch in MNIST sample program. I would really appreciate if someone could actually give me some tips on how I should make batch in my program below. import tensorflow as tf import numpy as np from sklearn import cross_validation import pandas as pd np.random.seed(20160612) tf.set_random_seed(20160612) #this is input data, data is a 7x86594 and label is a 5x86594 data2 = pd.read_csv('rawdata.csv', sep=',', header=None) data = np.array(data2) label2=pd.read_csv('class.csv', sep='\t', header=None) label=np.array(label2) train_x,test_x,train_t,test_t=cross_validation.train_test_split(data,label,test_size=0.1,random_state=None) #this is supposed to be neural size in hidden layer num_units = 15 x = tf.placeholder(tf.float32, [None, 7]) t = tf.placeholder(tf.float32, [None, 5]) w1 = tf.Variable(tf.truncated_normal([7, num_units], mean=0.0, stddev=0.05)) b1 = tf.Variable(tf.zeros([num_units])) hidden1 = tf.nn.relu(tf.matmul(x, w1) + b1) w0 = tf.Variable(tf.zeros([num_units, 5])) b0 = tf.Variable(tf.zeros([5])) p = tf.nn.softmax(tf.matmul(hidden1, w0) + b0) loss = -tf.reduce_sum(t * tf.log(tf.clip_by_value(p,1e-10,1.0))) train_step = tf.train.AdamOptimizer().minimize(loss) correct_prediction = tf.equal(tf.argmax(p, 1), tf.argmax(t, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) #this is how i think batching is batch_size = 100 for j in range(0, 86594, batch_size): xs,ys= train_x[j:j+batch_size], train_t[j:j+batch_size] i = 0 for _ in range(4000): i += 1 sess.run(train_step, feed_dict={x: xs, t: ys}) if i % 100 == 0: loss_val, acc_val = sess.run([loss, accuracy],feed_dict={x:test_x, t: test_t}) print ('Step: %d, Loss: %f, Accuracy: %f'% (i, loss_val, acc_val)) The result of this program, of course, isn't right.
upvote count: 1
tagged with: tensorflow
has title: Making batch tensorflow
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46905232
tagged with: batch-processing
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/54309556
has body: That depends on what you want to profile: If it is general debugging, see Debugging Spiders If it is memory usage, see Debugging memory leaks If it is crawling rate and other statistics, see Stats Collection If you want to interact with the spider at runtime, the Telnet Console might be the way to go. There is also Logging, of course.
answers question: http://stackoverflow.com/q/46865284
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/80743427
has text: More like, open_file() gives me a product called "a." read_file() reads "a" and gives me "b." get_data() takes "b" and gives me "c" etc. Does that make any sense? I'm happy to clarify anything!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46897852
type: Comment

http://stackoverflow.com/comment/80496172
type: Comment
comment on: http://stackoverflow.com/q/46775308
has text: `df['range'] = pd.cut(df['a'],[-np.inf,3,8,np.inf], labels =['<3','3-8','>8']).astype(str)`
score: 0
type: QuestionComment

http://stackoverflow.com/q/46750670
score: 1
type: Question
has title: how to display a certain subset of data on prettytable in a descending order
downvote count: 0
tagged with: sorting
has comment: http://stackoverflow.com/comment/80447565
tagged with: prettytable
tagged with: python
has body: i have a PrettyTable with two headers and over 500 rows, the structure is like this Email Address number of contacts aaa@goo.com 99 aaa@foo.com 123 and my code: table =pt.PrettyTable(["Email Address", "Number of Contacts"]) for n in g3.nodes(): table.add_row([n.title(),g3.in_degree(n)]) table.reversesort=True print table.get_string(sortby="Number of Contacts") i'm trying to organise the table in a descending order by sorting the number of contacts. what i actually want, is a table that displays the 20 e-mail addresses with the highest number of contacts . i dont want the rest to be on the table. with the help of some other questions on here, i could do the descending order but im stuck there and couldn't find a way of doing what i want. i've looked here but couldn't find a solution either. any suggestions?
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/80450399

http://stackoverflow.com/q/46810439
upvote count: 5
has comment: http://stackoverflow.com/comment/80568645
type: Question
has comment: http://stackoverflow.com/comment/80568002
score: 5
has answer: http://stackoverflow.com/a/46810501
accepted answer: http://stackoverflow.com/a/46810501
has answer: http://stackoverflow.com/a/46810537
has title: What is the exact term for 'argv' in python?
downvote count: 0
has body: I am currently trying to grasp the exact name of argv function (if it can be called a function) that can be imported from sys or system-specific parameters. I found 3 definitions: argument vector argument value argument variable So which one is it? Perhaps it doesn't matter how one calls it? Does it even have an accepted name? Thanks everyone!
has comment: http://stackoverflow.com/comment/80568216
linked to: http://stackoverflow.com/q/12118752
tagged with: terminology
tagged with: python-2.7
linked to: http://stackoverflow.com/q/27363115
answer count: 3
has answer: http://stackoverflow.com/a/46810599
tagged with: argv
linked to: http://stackoverflow.com/q/25580814
favorite count: 0
possible better answer: http://stackoverflow.com/a/46810537
has comment: http://stackoverflow.com/comment/80568387
tagged with: python
has comment: http://stackoverflow.com/comment/80569520
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3024197

http://stackoverflow.com/a/46751362
has body: sqlite3 is not installed.Try to install them $ pip install sqlite3 # or pysqlite2
upvote count: 2
type: Answer
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/46751295

http://stackoverflow.com/comment/80594470
comment on: http://stackoverflow.com/a/46778014
score: 0
type: Comment
type: AnswerComment
has text: Plus, I wonder, how you detect the incorrect sorting - does anything in your app do something with the retrieved data that might change the order?

http://stackoverflow.com/comment/80460997
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46757841
has text: God Bless you bro
type: AnswerComment

http://stackoverflow.com/q/46880748
score: 1
has body: I have a dataset about users taking online courses. It has features like, 'id', 'event', 'time'. I groupby them and want to know the frequency of a user doing every event on specific days. I want to count them in days. lt = log_train.groupby(['enrollment_id','event','time']).size() print(lt) enrollment_id event time 1 access 2014-06-14T09:38:39 2 2014-06-14T09:38:48 1 2014-06-19T06:21:16 2 2014-06-19T06:21:32 1 2014-06-19T06:21:45 1 .. 200887 navigate 2014-07-24T03:27:16 1 200887 navigate 2014-07-24T03:27:16 1 page_close 2014-07-24T04:19:55 1 video 2014-07-24T04:19:57 1 200888 access 2014-07-24T03:48:14 2 discussion 2014-07-24T03:47:57 1 navigate 2014-07-24T03:47:17 1 2014-07-24T03:47:28 1 2014-07-24T03:48:01 1 From the information I have seen in another dataset there are userIDs, courseIDs and course range time. usercourse = pd.merge(enroll,date,how="left", on= 'course_id' ) enrollment_id username \ 0 1 9Uee7oEuuMmgPx2IzPfFkWgkHZyPbWr0 1 3 1qXC7Fjbwp66GPQc6pHLfEuO8WKozxG4 2 4 FIHlppZyoq8muPbdVxS44gfvceX9zvU7 course_id from to 0 DPnLzkJJqOOPRJfBxIHbQEERiYHu5ila 2014-06-12 2014-07-11 1 7GRhBDsirIGkRZBtSMEzNTyDr2JQm4xx 2014-06-19 2014-07-18 2 DPnLzkJJqOOPRJfBxIHbQEERiYHu5ila 2014-06-12 2014-07-11 Every single user has only 1 course and all the courses have the same range with 30 days. So what I want to have should be similar like this, enrollment_id event #ofDays #ofActionTimes 1 access 2 2 10 6 30 2 .. 200887 navigate 23 1 page_close 30 1 video 1 1 200888 access 12 2 discussion 2 1 navigate 5 3 29 4 **#ofDays means at the Nth day of a course. #ofActionTimes means how often an event happens on the Nth day.** Since every course started from different dates I have no idea how to generate this data form on python. Hope someone could help me to solve the problem!
tagged with: dataframe
has title: How to convert time of the date and count the days in python?
has comment: http://stackoverflow.com/comment/80709613
type: Question
tagged with: numpy
upvote count: 1
has answer: http://stackoverflow.com/a/46882443
accepted answer: http://stackoverflow.com/a/46882443
has comment: http://stackoverflow.com/comment/80709124
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/46988238
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/80550930
has text: `df['running time']=df['running time']-df['waiting time']`
score: 0
comment on: http://stackoverflow.com/q/46802046
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46793107
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46793033
has comment: http://stackoverflow.com/comment/80533484
answers question: http://stackoverflow.com/q/46793033
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80532944
score: 12
upvote count: 12
has body: Test with any, since empty dicts are falsy: &gt;&gt;&gt; collection_a = {} &gt;&gt;&gt; collection_b = {"test": {}} &gt;&gt;&gt; any(collection_a.values()) False &gt;&gt;&gt; any(collection_b.values()) False This assumes that the dictionary value is always a dictionary.
type: Answer
has comment: http://stackoverflow.com/comment/80532864

http://stackoverflow.com/a/46868865
score: 0
has body: The first application has only one running consumer because it's executed once. Each request "blocks" (only one at a time is the loop) the consumer, so the next one will be processed after the previous. The latter app starts a new consumer loop with each request (since RequestHandler is created per req). So the first request does not "block" the next one, 'cause there is brand new while True with get and submit...
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/46868024
accepted answer of: http://stackoverflow.com/q/46868024
has comment: http://stackoverflow.com/comment/80691883

http://stackoverflow.com/comment/80731413
type: AnswerComment
has text: also can we use -F with -p at the same time ?
comment on: http://stackoverflow.com/a/46891585
type: Comment
score: 0

http://stackoverflow.com/comment/80543282
type: QuestionComment
comment on: http://stackoverflow.com/q/46798077
has text: Don't download the wheels for numpy/scipy base libraries, Anaconda sorts that. If it's openCV causing the issue, see :https://www.scivision.co/install-opencv-python-windows/ or tackle that problem specifically.
score: 0
type: Comment

http://stackoverflow.com/q/46803702
type: AnsweredQuestion
score: 1
answer count: 2
tagged with: firefox
linked to: http://stackoverflow.com/q/45097302
downvote count: 0
has title: What is wrong with this selenium firefox profile to download file into customized folder?
has body: I am using selenium and python v3.6 to automate firefox to download file into a customized folder. The location of the folder is C:/Users/username/Dropbox/Inv/. Below is my firefox profile. profile = webdriver.FirefoxProfile() profile.set_preference('browser.download.folderList', 2) # custom location profile.set_preference('browser.download.manager.showWhenStarting', False) profile.set_preference('browser.download.dir', 'C:/Users/username/Dropbox/Inv/') profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/plain') profile.set_preference('browser.helperApps.neverAsk.openFile', 'text/plain') Currently, the file is always downloaded in the default folder C:\Users\username\Downloads. How do I get the downloaded folder location to be C:/Users/username/Dropbox/Inv/?
favorite count: 0
has answer: http://stackoverflow.com/a/46805238
has comment: http://stackoverflow.com/comment/80555131
tagged with: python
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46804118
tagged with: selenium
upvote count: 1
accepted answer: http://stackoverflow.com/a/46805238
has answer: http://stackoverflow.com/a/46804118
type: Question

http://stackoverflow.com/q/46890665
has answer: http://stackoverflow.com/a/56802592
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/46891054
tagged with: pymongo
has answer: http://stackoverflow.com/a/46890922
has comment: http://stackoverflow.com/comment/80738386
tagged with: pymongo-3.x
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/80733720
possible better answer: http://stackoverflow.com/a/46890922
has body: I have a python flask based app, which writes to mongo database. I am using python 3 with the following requirements.txt Flask Jinja2 Werkzeug certifi chardet gunicorn requests flask_restful flask pymongo I run into this issue : Traceback (most recent call last): File "bin/app.py", line 4, in &lt;module&gt; from helper import save_message_2_db File "/app/bin/helper.py", line 1, in &lt;module&gt; from database import DataAccess, MongoDB File "/app/bin/database.py", line 1, in &lt;module&gt; import pymongo File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/__init__.py", line 83, in &lt;module&gt; from pymongo.collection import ReturnDocument File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 21, in &lt;module&gt; from bson.code import Code File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 19, in &lt;module&gt; from bson.py3compat import string_type, PY3, text_type ModuleNotFoundError: No module named 'bson.py3compat' I am trying to understand why does this happen? This section is what I am concerned with File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/__init__.py", line 83, in &lt;module&gt; from pymongo.collection import ReturnDocument File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 21, in &lt;module&gt; from bson.code import Code File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 19, in &lt;module&gt; from bson.py3compat import string_type, PY3, text_type ModuleNotFoundError: No module named 'bson.py3compat' Most of the internet blogs/links tell me bson and pymongo dont play well with eachother. pymongo has its own version of bson and i dont need it in my requirements.txt. I am looking for help to see why this happens, and how to remidiate this. Update #1 I was using pymongo-3.5.1, and thats where the problem persists. I just downgraded to pymongo-3.5.0 and the problem vanished. This means I know the workaround to fix this, but t…
accepted answer: http://stackoverflow.com/a/46891054
linked to: http://stackoverflow.com/q/53441445
has comment: http://stackoverflow.com/comment/80728670
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53491715
has title: pymongo import errors in python3 flask application
has comment: http://stackoverflow.com/comment/80738170
tagged with: python
answer count: 4

fractions
type: Tag
tags question: http://stackoverflow.com/q/46781697
tag name: fractions

http://stackoverflow.com/comment/80493492
type: Comment
has text: The only difference between maintaining the variables separately and zipping them is the use of zip. There are plenty of real-world examples where you'll have two separate sets of data. @Unapiedra, please remember the goal of Stack Overflow is to create a repository of knowledge for future users. It is valid to assert that in this instance, not separating the two lists would be the better solution; it is not valid to claim that an answer that provides enough information to help future questioners is "not a great answer" because of an implementation you provide for this specific instance.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46773156

http://stackoverflow.com/comment/80757541
type: QuestionComment
comment on: http://stackoverflow.com/q/46905380
has text: Can you please give the input and the expected output? As examples I mean, not onyl descriptions, as being acurate with descriptions and leaving no room for asumption is quite hard.
score: 0
type: Comment

http://stackoverflow.com/q/46862018
has title: Remove comment lines from a file
tagged with: comments
upvote count: 2
has comment: http://stackoverflow.com/comment/80671506
has comment: http://stackoverflow.com/comment/80671637
answer count: 2
favorite count: 0
accepted answer: http://stackoverflow.com/a/46862049
has body: I'm making a file type to store information from my program. The file type can include lines starting with #, like: # This is a comment. As shown, the # in front of a line denotes a comment. I've written a program in Python that can read these files: fileData = [] file = open("Tutorial.rdsf", "r") line = file.readline() while line != "": fileData.append(line) line = file.readline() for item in list(fileData): item.strip() fileData = list(map(lambda s: s.strip(), fileData)) print(fileData) As you can see, it takes the file, adds every line as an item in a list, and strips the items of \n. So far, so good. But often these files contain comments I've made, and such the program adds them to the list. Is there a way to delete all items in the list starting with #? Edit: To make things a bit clearer: Comments won't be like this: Some code: {Some Code} #Foo They'll be like this: #Foo Some code: {Some Code}
tagged with: python
tagged with: file-type
type: AnsweredQuestion
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/80671516
possible better answer: http://stackoverflow.com/a/46862060
downvote count: 0
has answer: http://stackoverflow.com/a/46862049
has answer: http://stackoverflow.com/a/46862060
type: Question

http://stackoverflow.com/comment/80491010
has text: @Bharathshetty I want to extract all the text following the last description tag for a particular id. In my case, the text has not been formatted properly and is split up in different rows, hence i need to put it in one row. I hope that answers your question
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46771137
score: 0

http://stackoverflow.com/comment/80593037
score: 1
type: AnswerComment
has text: Yes, `Word2Vec` and `Doc2Vec` both support the `iter` parameter in their initialization-method!
comment on: http://stackoverflow.com/a/46816101
type: Comment

http://stackoverflow.com/comment/80617841
score: 1
comment on: http://stackoverflow.com/q/46834364
type: Comment
type: QuestionComment
has text: `self.getRootVal()` is probably returning an int on the offending line.

http://stackoverflow.com/a/46910796
downvote count: 0
has comment: http://stackoverflow.com/comment/80970832
has body: You can do that using pdfrw pip install pdfrw Then run from pdfrw import PdfReader, PdfWriter trailer = PdfReader("myfile.pdf") trailer.Info.WhoAmI = "Tarun Lalwani" PdfWriter("edited.pdf", trailer=trailer).write() And then check the PDF Custom Properties
score: 15
answers question: http://stackoverflow.com/q/46849733
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133760505
accepted answer of: http://stackoverflow.com/q/46849733
type: Answer
upvote count: 15

http://stackoverflow.com/q/46751063
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80448842
linked to: http://stackoverflow.com/q/40976880
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: cython
tagged with: c++11
type: Question
has comment: http://stackoverflow.com/comment/80448048
score: 1
has body: I would like to use the C++11 &lt;random&gt; header in Cython code. I notice here that it is not included by default with Cython: https://github.com/cython/cython/tree/master/Cython/Includes/libcpp It's just a bit overwhelming to get the pxd and pyx files figured out and get a working setup file to install and use them. Could you please help me figure out a simple example? Thank you!
has comment: http://stackoverflow.com/comment/80452189
has title: Wrapping the C++11 <random> header in a Cython pxd package that can be cimport'ed
has comment: http://stackoverflow.com/comment/80452171
upvote count: 1

http://stackoverflow.com/comment/80684624
has text: Thanks for the help. I really appreciate it. That code edit worked.
type: AnswerComment
comment on: http://stackoverflow.com/a/46868677
score: 0
type: Comment

http://stackoverflow.com/q/46874233
tagged with: python
tagged with: mongodb-query
has comment: http://stackoverflow.com/comment/80700732
has comment: http://stackoverflow.com/comment/80695506
answer count: 0
type: UnansweredQuestion
tagged with: pymongo
type: Question
has title: I have a collection in mongo db which is of 89.8 gb and I want to extract all the elements of the collection
tagged with: database
has body: Here is my piece of code where am getting the elements. ` client = MongoClient('localhost:27017') db = client.cdiscount for e in db.train_data.find({}, {"category_id": 1, "imgs": 1}): img_arr = [] category_id = e["category_id"] if str(category_id) in list(img_dict.keys()): img_arr = img_dict[str(category_id)] img_arr += [imread(io.BytesIO(img["picture"])) for img in e["imgs"]] img_dict[str(category_id)] = img_arr if len(list(img_dict.keys())) &gt; 500: print("Saving images...") save_as_numpy(img_dict) img_dict = {} ` I have a RAM of 32 gb the code works fine initially, but as the cache gets filled up it gets slow and ultimately hangs when the memory is full. Is there any way to retrieve all the documents in a collection whose size is bigger than the memory?
score: 0
tagged with: mongodb

http://stackoverflow.com/q/46898382
tagged with: ipython
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/80744490
has comment: http://stackoverflow.com/comment/80744056
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80744013
has answer: http://stackoverflow.com/a/46898444
tagged with: python
has title: Why can't I assign a value to the name `_i` in iPython?
possible better answer: http://stackoverflow.com/a/46898446
has comment: http://stackoverflow.com/comment/80744382
has answer: http://stackoverflow.com/a/46898446
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80744002
has comment: http://stackoverflow.com/comment/80744137
has body: If I do: _j = 1 print(_j) 1 This is as expected But if I: _i = 1 print(_i) _i = 1 Not at all what I expected. Why is _i special and what other names have this property that I cannot overwrite it?
type: Question
accepted answer: http://stackoverflow.com/a/46898444
upvote count: 5

http://stackoverflow.com/comment/80729355
comment on: http://stackoverflow.com/a/46890987
score: 2
has text: When checking for membership, sets are the way to go. By the way, the whole if else block can be rewritten as `return bool(common_elements)`.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46793305
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46793110
type: Answer
answers question: http://stackoverflow.com/q/46793110
score: 8
downvote count: 0
upvote count: 8
has body: When you are specifying the estimators for VotingClassifier, you need to give each of them a name: from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import VotingClassifier p1 = Pipeline('clf1', RandomForestClassifier()) p2 = Pipeline('clf2', AdaBoostClassifier()) p3 = Pipeline([['clf3', VotingClassifier(estimators=[("p1",p1), ("p2",p2)])]]) p3.get_params() This will output: {'clf3': VotingClassifier(estimators=[('p1', Pipeline(steps='clf1', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction...SAMME.R', base_estimator=None, learning_rate=1.0, n_estimators=50, random_state=None)))], n_jobs=1, voting='hard', weights=None), 'clf3__estimators': [('p1', Pipeline(steps='clf1', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False))), ('p2', Pipeline(steps='clf2', AdaBoostClassifier(algorithm='SAMME.R', base_estimator=None, learning_rate=1.0, n_estimators=50, random_state=None)))], 'clf3__n_jobs': 1, 'clf3__p1': Pipeline(steps='clf1', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False)), 'clf3__p1__clf1': RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impur…

http://stackoverflow.com/comment/80743194
comment on: http://stackoverflow.com/q/46897974
score: 1
has text: For starters: ```BFGS``` does not allow constraints. Not sure how scipy is behaving with your call. [docs:](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.optimize.minimize.html): ```Constraints definition (only for COBYLA and SLSQP)```
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80734348
score: 0
has text: [root] INFO: https://imgs.xkcd.com/comics/state_borders.png Does this look right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46892962

http://stackoverflow.com/comment/80572332
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46810801
has text: It determines your data structure,these problems occur because you already use non-unique mold. `your data, your computer and your unique pattern` which guide can help you ? Don't search db, only add an entry to `INSERTED-DB` !

http://stackoverflow.com/q/46880576
duplicate of: http://stackoverflow.com/q/23056460
has comment: http://stackoverflow.com/comment/80708386
score: 0
linked to: http://stackoverflow.com/q/23056460
has title: Fit classifier with more data
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/80708398
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/80708411
type: Question
has body: I am currently using scikit-learn to create and fit a SVC classifier. To do this, I wrote the following code: clf = SVC(probability=True).fit(X_labeled, Y_labeled) I then use an active learning technique to get more data to improve the classifier's performance. To train the classifier on the new data, can I do this: clf.fit(newData, newY) or do I need to do this: clf.fit(newData+X_labeled, newY+Y_labeled) #pseudocode

http://stackoverflow.com/comment/80462564
type: Comment
type: QuestionComment
has text: @user2426320 , seems fair I do a +1 there.
comment on: http://stackoverflow.com/q/46758244
score: 0

http://stackoverflow.com/a/46793160
has comment: http://stackoverflow.com/comment/80534577
has comment: http://stackoverflow.com/comment/80533300
upvote count: 5
score: 4
has comment: http://stackoverflow.com/comment/80533482
has comment: http://stackoverflow.com/comment/80534880
has comment: http://stackoverflow.com/comment/80533980
has comment: http://stackoverflow.com/comment/80535105
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80533810
has comment: http://stackoverflow.com/comment/80533708
has comment: http://stackoverflow.com/comment/80534081
type: Answer
has comment: http://stackoverflow.com/comment/80534129
has comment: http://stackoverflow.com/comment/80533210
has comment: http://stackoverflow.com/comment/80534183
accepted answer of: http://stackoverflow.com/q/46793112
has body: f(x) is not a function (even in mathematics). The function is f. In python there is no problem to store functions in array: def my_func(): print("Foo") my_other_func = lambda: print("Bar") my_arr = [my_func, my_other_func]
answers question: http://stackoverflow.com/q/46793112
has comment: http://stackoverflow.com/comment/80534352
downvote count: 1
has comment: http://stackoverflow.com/comment/80534953

http://stackoverflow.com/a/54495499
type: Answer
upvote count: 6
has body: For me using app.run(debug=False) worked when using port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) did not. I can't tell if this is a firewall issue or why it didn't work. Do note that after doing this it started hosting at http://127.0.0.1:5000/.
score: 6
has comment: http://stackoverflow.com/comment/139236604
downvote count: 0
answers question: http://stackoverflow.com/q/46835568

http://stackoverflow.com/q/46864368
favorite count: 0
upvote count: 3
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80676178
has comment: http://stackoverflow.com/comment/80676228
tagged with: c++
has comment: http://stackoverflow.com/comment/80676153
has comment: http://stackoverflow.com/comment/80676161
tagged with: constructor
has body: I have worked with Python for about a while and have recently started learning C++. In C++ you create a constructor method for each class I I was wondering if it is correct to think that this is equivalent to the __init__(self) function in Python? Are there any notable differences? Same question for a C++ destructor method vs. Python _exit__(self)
accepted answer: http://stackoverflow.com/a/46864702
has comment: http://stackoverflow.com/comment/80676313
score: 2
has comment: http://stackoverflow.com/comment/80676304
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46864702
has comment: http://stackoverflow.com/comment/80676233
has comment: http://stackoverflow.com/comment/80676214
has title: Python __init__ Compared to C++ Constructor
has comment: http://stackoverflow.com/comment/80676271
has comment: http://stackoverflow.com/comment/80676342
possible better answer: http://stackoverflow.com/a/46864771
type: Question
has answer: http://stackoverflow.com/a/46864771
answer count: 3
has comment: http://stackoverflow.com/comment/80676227
has answer: http://stackoverflow.com/a/46864529
has comment: http://stackoverflow.com/comment/80676138
linked to: http://stackoverflow.com/q/388242

http://stackoverflow.com/comment/80753269
has text: Instead of using port 443, try using 0 and see if that help anyways? Also do you have redis available? can that be used for caching of these results?
comment on: http://stackoverflow.com/q/46836616
score: 0
type: QuestionComment
type: Comment

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/46838929
tags question: http://stackoverflow.com/q/46898990
tags question: http://stackoverflow.com/q/46785478

http://stackoverflow.com/comment/80524859
has text: Thanks Rathan. your suggestion worked fine
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46788751

http://stackoverflow.com/a/46824279
has comment: http://stackoverflow.com/comment/80595953
score: 0
type: Answer
has body: data = """10/14/2017 21:02 11/04/2017 134 15 10/14/2017 21:02 11/04/2017 134 15 10/14/2017 21:02 11/04/2017 134 15 10/13/2017 20:58 11/03/2017 132 10 10/13/2017 20:58 11/03/2017 132 10 10/13/2017 20:58 11/03/2017 132 10 10/13/2017 20:58 11/03/2017 132 10 """ result = {} for line in data.splitlines(): key = line.split(' ')[0] value = line.split(' ')[11] if result.get(key): result[key] = result[key] + int(value) else: result[key] = int(value) print(result)
answers question: http://stackoverflow.com/q/46824043

http://stackoverflow.com/a/46911340
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46903848
type: Answer
downvote count: 0
score: 1
has body: You can try the below: f = df1.dropna() f['days'] = np.busday_count(pd.to_datetime(f['On hold']).values.astype('datetime64[D]'), \ pd.to_datetime(f['Off hold']).values.astype('datetime64[D]')) df1.merge(f'ID', 'days',on='ID', how='left')
answers question: http://stackoverflow.com/q/46903848

http://stackoverflow.com/comment/80466912
has text: `len(self.EPG_Channel_Number)` - presuming that's the string you want the length for.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46760753

http://stackoverflow.com/comment/80835374
comment on: http://stackoverflow.com/q/46842951
has text: Also I am not sure this code is actually using the GPU for calculation. When the code is running I checked the GPU usage using msi afterburner application and the percentage barely went higher than 2%. Is this calculation too lightweight to really use the GPU resources ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80449365
score: 0
comment on: http://stackoverflow.com/q/46751725
has text: it keeps printing 'test' but there is no '[xx]: ' in there and i can't write some input
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46857117
upvote count: 2
type: Answer
score: 2
has body: First, the assumption about unfolding the list is just wrong. beg, end = time.time(), time.time() can provide different values of time, since the time() function is calculated twice, and can return separate results. Specifically, Python builds a tuple of two time values first (time.time(), time.time()). And then unpacks that tuple into the variables beg, end. There is no special magic with paralellisation or values caching or even var-by-var assignment (consider: a,b = b,a value-swapping pattern: it literally does t = (b,a); (a,b) = t). Second, the timestamps comparison highly depends on your system (OS mostly). For time.time(), the fine-grained resolution is just not guaranteed: Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. On the unix systems (not MacOSX), you can try using time.clock_getres(clk_id) to get the clock resolution. On Windows, as it seems to be your case, you can probably find the information from the Win32 calls to QueryPerformanceCounter() mentioned in the manual for time.clock() (I do not have enough knowledge to comment on the Windows APIs). You should also google for the time precision on your OS to answer this question, as it is not much python-related. If the resolution is not enough for such measurements, and the CPU is very fast (typical for nowadays), then the time measurements will be too close to distinguish them. They will be different and far apart if measured in the CPU tacts, of course. But not different in the minimum available time units. To notice that, try executing your code on the much slower machine or when the CPU is highly overloaded with some computational tasks (i.e. 99-100% CPU used), and cannot spend too much time on your process. It is better if the CPU is not just busy with one process, but switches the context very often between multiple processes — e.g. by having few hundreds of CPU-intensive processes or maybe 1-2 thous…
answers question: http://stackoverflow.com/q/46856981
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46856981

http://stackoverflow.com/comment/80675448
comment on: http://stackoverflow.com/a/46863986
score: 0
type: Comment
has text: Play around with the [`map`](https://docs.python.org/3/library/functions.html#map) built-in function and make sure you understand how that works. `ProcessPoolExecutor.map` is doing the same thing, but with each calculation being farmed out to a different process, and then the results gathered up in the correct order.
type: AnswerComment

http://stackoverflow.com/comment/80448394
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46751249
score: 0
has text: Those aren't objects, they're dictionaries.

http://stackoverflow.com/a/46853395
score: 0
type: Answer
has body: Just an idea but you could write a function to make a batch file and use os.startfile("batch.bat")
answers question: http://stackoverflow.com/q/46844090

http://stackoverflow.com/comment/80562648
has text: Isn't it the same? #@interntseekho
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46807792
type: AnswerComment

http://stackoverflow.com/a/46834437
answers question: http://stackoverflow.com/q/46833160
has body: Dictionary can't have duplicate keys. What you can do is to define dictionary to hold a list of values. In your case change {Tag1:{Tag2:Tag3}} to be {Tag1:[{Tag2:Tag3}]}
type: Answer
score: 0

http://stackoverflow.com/q/46895686
tagged with: python
has comment: http://stackoverflow.com/comment/80738846
answer count: 0
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/80739067
type: Question
has title: Trying to install selenium package in Pycharm (Python and Selenium) and getting timeout error message
has comment: http://stackoverflow.com/comment/80738511
score: 0
linked to: http://stackoverflow.com/q/30992717
has comment: http://stackoverflow.com/comment/80738508
has comment: http://stackoverflow.com/comment/80768581
has body: ran the command:: pip install -U Selenium and getting timeout error message. Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'Connect TimeoutError(&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03F4 9670&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/selenium/

http://stackoverflow.com/q/46853624
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80654729
downvote count: 0
has answer: http://stackoverflow.com/a/46932531
has comment: http://stackoverflow.com/comment/80721661
has comment: http://stackoverflow.com/comment/80801628
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80807749
has comment: http://stackoverflow.com/comment/80754074
has title: Python lxml library includes None in empty tags
type: Question
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/46932531
has answer: http://stackoverflow.com/a/46914608
favorite count: 0
accepted answer: http://stackoverflow.com/a/46914608
has body: As has been suggested by mzjn I am changing the whole question and trying to simplify it. I have this XML: &lt;Content Version="1.0" Name="Cont"&gt; &lt;Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content"&gt; &lt;body&gt; &lt;p&gt;Some content is here.&lt;/p&gt; &lt;/body&gt; &lt;/Element&gt; &lt;Element Ref="List_585" ElementType="ListElements" GroupName="Lists"&gt; &lt;body&gt; &lt;p&gt;&lt;span class="bold"&gt;A list of things&lt;/span&gt;: Element1, element2, element3, element4 element5.&lt;/p&gt; &lt;/body&gt; &lt;/Element&gt; &lt;/Content&gt; I want to modify the content of the lists and replace "," for "&lt;,>". And I have this code: from lxml import etree as et def replace_commas(file): parser = et.parse(str(file)) root = parser.getroot() xpath_expr = "//Element[starts-with(@Ref,'List_') \ or @GroupName='Lists']/descendant::*" elements = root.xpath(xpath_expr) for element in elements: if element.text is not None or element.tail is not None: text = str(element.text) text = text.replace(',', '&lt;,&gt;') tail = str(element.tail) tail = tail.replace(',','&lt;,&gt;') element.text = text element.tail = tail tree = et.ElementTree(root) tree.write(file, pretty_print=True) The expected output should be: &lt;Content Version="1.0" Name="Cont"&gt; &lt;Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content"&gt; &lt;body&gt; &lt;p&gt;Some content is here.&lt;/p&gt; &lt;/body&gt; &lt;/Element&gt; &lt;Element Ref="List_585" ElementType="ListElements" GroupName="Lists"&gt; &lt;body&gt; &lt;p&gt;&lt;span class="bold"&gt;A list of things&lt;/span&gt;: Element1&amp;lt;,&amp;gt; element2&amp;lt;,&amp;gt; element3&amp;lt;,&amp;gt; element4 element5.&lt;/p&gt; &lt;/body&gt; &lt;/Element&gt; &lt;/Content&gt; However my result is: &lt;Content Version="1.0" Name="Cont"&gt; &lt;Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content"&gt; &lt;body&gt; &lt;p&gt;Some content is here.&lt;/p&gt; &lt;/body&gt; &lt;/Element&g…
tagged with: lxml

http://stackoverflow.com/comment/80449996
type: Comment
type: QuestionComment
has text: Yes, is not problem if signed your question as dupe?
score: 1
comment on: http://stackoverflow.com/q/46751465

http://stackoverflow.com/comment/80561191
comment on: http://stackoverflow.com/q/46806552
has text: you can try to look on `print (qs.query)` and execute printed sql in the sqlpplus( or what you use)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46812446
has comment: http://stackoverflow.com/comment/80573766
upvote count: 1
has comment: http://stackoverflow.com/comment/80572953
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80571993
has answer: http://stackoverflow.com/a/46813490
answer count: 2
has body: I am trying to solve this issue with sorting a particular nested dictionary. Structure is as follows: dct = { "test": { 0: [1, 3], 1: [5, 6], }, "test2": { 7: [9], 3: [4, 6], } } I would love to be able to sort by the "test" term and the key so in the "test2" I would have first 3 and then 7. I have tried this arr = OrderedDict(sorted(dct.items(), key=lambda x: (x[0], x[1]))) But that doesn't seem to work. Is there any way to perform this kind of sort?
tagged with: sorting
favorite count: 0
possible better answer: http://stackoverflow.com/a/46813220
score: 0
has answer: http://stackoverflow.com/a/46813220
has comment: http://stackoverflow.com/comment/80572689
tagged with: python
has title: Sorting nested dictionaries python
accepted answer: http://stackoverflow.com/a/46813490

http://stackoverflow.com/a/49968682
has body: Allocation of the shared array is slow, because apparently it's written to disk first, so it can be shared through a mmap. For reference see heap.py and sharedctypes.py. This is why tempfile.py shows up in the profiler. I think the advantage of this approach is that the shared memory is cleaned up in case of a crash, and this cannot be guaranteed with POSIX shared memory. There is no pickling happening with your code, thanks to fork and, as you said, the memory is inherited. The reason the 2nd run doesn't work is because the child processes are not allowed to write in the memory of the parent. Instead, private pages are allocated on the fly, only to be discared when the child process ends. I only have one suggestion: You don't have to specify a ctype yourself, the right type can be figured out from the numpy dtype through np.ctypeslib._typecodes. Or just use c_byte for everything and use the dtype itemsize to figure out the size of the buffer, it will be casted by numpy anyway.
upvote count: 3
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46811709

http://stackoverflow.com/q/46778899
has answer: http://stackoverflow.com/a/46779069
has body: I want to read book-crossing dataset table: BX-Books. using pandas. When I write: #load book informations dataset books = pd.read_csv("BX-CSV-Dump/BX-Books.csv",sep=';') I get an error: CParserError: Error tokenizing data. C error: Expected 8 fields in line 6452, saw 9 How to correct this? I tried with '\t' as a separator but it didn't work too, I get all the columns in one column separated by ";" in that case.
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80503741
type: Question
accepted answer: http://stackoverflow.com/a/46779069
has title: CParserError: Error tokenizing data. when reading book-crossing dataset
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/80705045
type: AnswerComment
has text: is there a way to know what is the largest degree of polynomials I can try without getting into these issues for a given interval size?
comment on: http://stackoverflow.com/a/46859873
type: Comment
score: 0

http://stackoverflow.com/a/46918732
has comment: http://stackoverflow.com/comment/130715551
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/113512073
answers question: http://stackoverflow.com/q/46898131
type: Answer
accepted answer of: http://stackoverflow.com/q/46898131
has body: I think you missed the part where it says but no group of (num_required - 1) bunnies can. I can explain my solution further, but I will ruin the fun. (I'm the owner of that repo). Let's try it with your answer. [[0], [0, 1, 2], [0, 1, 2], [1], [2]] Your consoles are 3. Bunny 2 can open it on its own, Bunny 3 can open it also on his own -> it does NOT satisfy the rule.
has comment: http://stackoverflow.com/comment/80792834
has comment: http://stackoverflow.com/comment/131953345

http://stackoverflow.com/a/46868799
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/80685133
accepted answer of: http://stackoverflow.com/q/46868790
downvote count: 0
has body: Reassigning columns just means you are changing the object that the variable references, it does not imply that the original df.columns will be updated. I'd recommend using a list comprehension and assigning the result back: df.columns = [Asset(x) for x in df.columns] Based on your edit, asset = [Asset(x) for x in df.columns] Or, asset = {x : Asset(x) for x in df.columns}
answers question: http://stackoverflow.com/q/46868790
score: 3
has comment: http://stackoverflow.com/comment/80685223
has comment: http://stackoverflow.com/comment/80685331
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80685117

http://stackoverflow.com/comment/80757556
comment on: http://stackoverflow.com/q/46905380
score: 0
type: Comment
type: QuestionComment
has text: I want to but its too big, haha. see this is what it looks like now:

http://stackoverflow.com/q/46840135
has title: Exporting nested lists to an excel file in Python
has body: So I have a list of lists. For example: l = [[1,2,3],['a','b','c'],['a,b','d,c','a,e']] I am having trouble exporting this properly because I need the two letters in the same cell, so if I use commas as a delimiter, it separates them. I have attached a photo of what i would want it to look like. I have already tried a few things but I am not sure how to do this. Any help would be great.
has comment: http://stackoverflow.com/comment/80628188
type: UnansweredQuestion
tagged with: python
tagged with: excel
tagged with: list
score: 0
type: Question
answer count: 1
tagged with: export
has answer: http://stackoverflow.com/a/46840832
has comment: http://stackoverflow.com/comment/80628413
has comment: http://stackoverflow.com/comment/80628292

http://stackoverflow.com/q/46795006
tagged with: dictionary
has answer: http://stackoverflow.com/a/46795124
has comment: http://stackoverflow.com/comment/80536600
has body: Hi this is my current text file format; A:{'1': [6, 4, 3, 8, 5], '2': [2, 1, 5, 4, 4], '3': []} B:{'1': [3, 6, 4, 3, 7], '2': [3, 2, 9, 2, 7], '3': []} C:{'1': [5, 4, 3, 6, 1], '2': [], '3': []} How would I call the key of the dictionary and make it print the data in a formatted manner, from the text file.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80536690
score: 0
has answer: http://stackoverflow.com/a/46795436
has title: How to read back data from a text file when the dictionary is formatted in a certain way? [Python]
has comment: http://stackoverflow.com/comment/80536648
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80498944
score: 1
has text: I added what I am running and the result so you can. Not sure how I am breaking it.
comment on: http://stackoverflow.com/a/46775010
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80744985
type: AnswerComment
comment on: http://stackoverflow.com/a/46898736
type: Comment
has text: @izn I fixed it a bit based on your comment, now you will get keys out like "place_id" and "place_location_city"
score: 1

http://stackoverflow.com/q/46812096
has title: nltk / re : nothing to repeat while trying to tokenize with regex
has comment: http://stackoverflow.com/comment/80571898
type: Question
has comment: http://stackoverflow.com/comment/80571594
has comment: http://stackoverflow.com/comment/80579050
has comment: http://stackoverflow.com/comment/80572348
has answer: http://stackoverflow.com/a/46843905
tagged with: nltk
has comment: http://stackoverflow.com/comment/80572061
has comment: http://stackoverflow.com/comment/80571411
has comment: http://stackoverflow.com/comment/80602415
has comment: http://stackoverflow.com/comment/80572405
has comment: http://stackoverflow.com/comment/80572290
score: 0
has body: import nltk text = """The Buddha, the Godhead, resides quite as comfortably in the circuits of a digital computer or the gears of a cycle transmission as he does at the top of a mountain or in the petals of a flower. To think otherwise is to demean the Buddha...which is to demean oneself.""" sentence_re = r'''(?:(?:[A-Z])(?:.[A-Z])+.?)|(?:\w+(?:-\w+)*)|(?:$?\d+(?:.\d+)?%?)|(?:...|)(?:[][.,;"'?():-_`])''' toks = nltk.regexp_tokenize(text, sentence_re) but I get: File "C:\Users\AppData\Local\Continuum\Anaconda2\envs\Python35\lib\sre_parse.py", line 638, in _parse source.tell() - here + len(this)) error: nothing to repeat I understand previously there was a bug, but I am using the latest NLTK and Python3.5 where I am lead to believe I should not be experiencing the bug. Anyone have any idea what is going on? Run within Spyder3 from a Python 3.5 virtualenv The regex is trying to obtain (in order): abbreviations (optional) hyphenated words currency and percentages ellipsis and ad-hoc tokens i.e. ? [ ( : etc etc...
has comment: http://stackoverflow.com/comment/80572008
has comment: http://stackoverflow.com/comment/80571442
answer count: 1
linked to: http://stackoverflow.com/q/1832893
has comment: http://stackoverflow.com/comment/80601871
has comment: http://stackoverflow.com/comment/80572530
has comment: http://stackoverflow.com/comment/80602775
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80601895
tagged with: python
has comment: http://stackoverflow.com/comment/80572355
has comment: http://stackoverflow.com/comment/80596222
tagged with: regex

http://stackoverflow.com/q/46851356
tagged with: terminal
tagged with: colors
has comment: http://stackoverflow.com/comment/80650190
has comment: http://stackoverflow.com/comment/80650424
tagged with: python
tagged with: logging
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80650444
has body: I'm trying to print log/print text to the terminal with custom colors using Python. I looked around, but couldn't find anything other than ANSI colors. Do I have to use ANSI colors, or am I able to log/print text with custom colors (for example, using RGB or hexadecimal values) to the terminal?
upvote count: 2
score: 1
has title: Is it possible to print from Python using non-ANSI colors?
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/46875258
has answer: http://stackoverflow.com/a/46875258
has answer: http://stackoverflow.com/a/46851467
has comment: http://stackoverflow.com/comment/80650138
tagged with: ansi-colors
answer count: 2
has comment: http://stackoverflow.com/comment/80650965
accepted answer: http://stackoverflow.com/a/46851467
favorite count: 0
has comment: http://stackoverflow.com/comment/80683349

http://stackoverflow.com/comment/80526917
score: 0
has text: I would recommend to go step by step. Which step is not doing what it is supposed to? have you imshow the contours for example? or the threshold image? I suggest you first see the threshold and see if it shows what you want, then show the contour, is this the outer border? finally the bounding rect it will surround all the contour (including the contour) you need to change the x and y to x+10 or something like that, and then the w to w-10. this way it will be the inside part not the outside. 10 is just an example, you have to figure this number
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46789896

http://stackoverflow.com/q/46840152
tagged with: plot
has title: Invalid RGBA argument: nan
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/80628219
tagged with: colors
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to display a scatter plot with 5 different colors: one for each 'district'. Unfortunately I have this error showing up: Invalid RGBA argument: nan My dataframe looks like this: &gt; price surface district &gt; 0 1850 46 1.0 &gt; 1 1900 41 4.0 &gt; 2 1925 55 4.0 &gt; 3 1960 52 2.0 &gt; 4 2025 57 3.0 &gt; 5 2055 60 10.0 ... ... ... ... Here is what i did: colors =['red', 'pink', 'limegreen', 'violet', 'cyan'] color_dict = dict(zip(np.unique(house['district']),colors)) thus the color dictionnary looks like this: {1.0: 'red', 2.0: 'pink', 3.0: 'limegreen', 4.0: 'violet', 10.0: 'cyan'} Then I created a variable col: col = house['district'].map(color_dict) Finally, i draw the plot: df.plot(kind = 'scatter', x = 'surface', y = 'price', c = col) Can someone explain what's the problem here ?
has answer: http://stackoverflow.com/a/46840285
has comment: http://stackoverflow.com/comment/80628262
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/62080682
upvote count: 30
type: Answer
has comment: http://stackoverflow.com/comment/116440876
has comment: http://stackoverflow.com/comment/114343964
answers question: http://stackoverflow.com/q/46854395
has comment: http://stackoverflow.com/comment/111290832
has comment: http://stackoverflow.com/comment/137703230
downvote count: 0
has body: Sorry for this necroposting, but this theme is so important and really simple answer exists, just create a custom manager for your user model and override the get method with select_related like this: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): def get(self, *args, **kwargs): return super().select_related('&lt;put fields that you want&gt;').get(*args, **kwargs) class CustomUser(AbstractUser): ... objects = CustomUserManager() Now, whenever Django will retrieve user instance for request.user, it will be using this manager. Also all your CustomUser.objects.get() queries will select specified related fields too.
score: 30

http://stackoverflow.com/comment/80569547
score: 0
type: AnswerComment
has text: How to do what exactly? I've given two options here... I might suggest stepping back, generating fake data, and learn the ins and outs of DictWriter, and determine if you really need it. I will point out that `w.writerow(header_names,)` looks unnecessary unless you do want "double" headers
type: Comment
comment on: http://stackoverflow.com/a/46811195

http://stackoverflow.com/comment/80541336
type: QuestionComment
has text: Search for "collation".
score: 0
comment on: http://stackoverflow.com/q/46797306
type: Comment

http://stackoverflow.com/a/46867633
score: 0
type: AcceptedAnswer
has body: I am not going to write the code for you, but this will probably help. If I am understanding the question correctly you are trying to take a big block of text (paragraph) split it into sentences then get the average len of characters in each sentence. So: 1) Break text block into sentences. Here is a post that should help you do that. 2) Count the letters in a sentence. Here is another post that will help remove the whitespace from the sentence. If you need to remove all the punctuation (everything except letters) from the string check out this post. Now you have a string that you can simply do a len(sentence_string) to get how many characters are in the sentence. Next time please post the code you have tried, the errors you have gotten, and the text of the data you are trying to use. DON'T post pictures of words. It makes it a lot harder to help when we can't just copy and paste everything and debug it ourselves.
type: Answer
accepted answer of: http://stackoverflow.com/q/46867536
answers question: http://stackoverflow.com/q/46867536

http://stackoverflow.com/q/46784727
tagged with: python
has answer: http://stackoverflow.com/a/46785541
has answer: http://stackoverflow.com/a/46785210
has body: I have seen here and here on how to return every nth row; but my problem is different. A separate column in the file provides specifics about which nth element to return; which are different depending on the group. Here is a sample of the dataset where the Nth column provides the rows to return. That is, for Id group a every 3rd row and forId group b every 4th row. The data is quite sizable which with several Id groups. Id TagNo Nth a A-A-3 3 a A-A-1 3 a A-A-5 3 a A-A-2 3 a AX-45 3 a AX-33 3 b B-B-5 4 b B-B-4 4 b B-B-3 4 b BX-B2 4 Desired output: Id TagNo Nth a A-A-3 3 a A-A-2 3 b B-B-5 4 Thank you for your help. Edit: Please kindly note that I want to start picking from the first and every nth item; that is every 3rd for a and 4th for b. For group a it will be 1st,4th, 7th... for group b it will be 1st,5th, 9th rows. The original output has error and an edit has been done. My sincere apologies.
has comment: http://stackoverflow.com/comment/80516574
upvote count: 5
linked to: http://stackoverflow.com/q/12850386
has answer: http://stackoverflow.com/a/46785306
has comment: http://stackoverflow.com/comment/80516139
linked to: http://stackoverflow.com/q/25189882
possible better answer: http://stackoverflow.com/a/46785049
has answer: http://stackoverflow.com/a/46785430
has answer: http://stackoverflow.com/a/46785049
downvote count: 0
has comment: http://stackoverflow.com/comment/80515997
has answer: http://stackoverflow.com/a/46785046
tagged with: http://stackoverflow.com/tag/r
tagged with: bash
type: Question
accepted answer: http://stackoverflow.com/a/46785306
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46786830
has answer: http://stackoverflow.com/a/46785600
tagged with: awk
tagged with: shell
has title: Take every nth row from a file with groups and n is a given in a column
linked to: http://stackoverflow.com/q/30903967
favorite count: 0
has comment: http://stackoverflow.com/comment/80516103
has comment: http://stackoverflow.com/comment/80516184
answer count: 8
has comment: http://stackoverflow.com/comment/80516150
score: 5

http://stackoverflow.com/comment/80674755
type: Comment
comment on: http://stackoverflow.com/q/46863047
score: 1
has text: "I am almost half way through it": I like your optimism.
type: QuestionComment

http://stackoverflow.com/q/46860747
type: Question
has comment: http://stackoverflow.com/comment/80740144
has body: While putting together tests for my Flask app, I have stumbled upon behaviour I can't quite understand. In my tests I'm using approach suggested by Flask documentation for accessing and modifying session from the tests. Say I have, really basic, project structure: root |-- my_app.py |-- tests |-- test_my_app.py my_app.py from flask import ( Flask, session, request ) app = Flask(__name__) app.secret_key = 'bad secret key' @app.route('/action/', methods=['POST']) def action(): the_action = request.form['action'] if session.get('test'): return 'Test is set, action complete.' else: return 'Oy vey!' test_my_app.py import flask from unittest import TestCase import my_app class TestApp(TestCase): def setUp(self): self.test_client = my_app.app.test_client() def testUnsetKeyViaPostNegative(self): with self.test_client as client: response = client.post('/action/') expected_response = 'Oy vey!'.encode('ascii') self.assertTrue(expected_response == response.data) Now, if I run the test it will fail, because response returns 400 Bad Request. If the_action = request.form['action'] is commended out, everything goes smooth. The reason I need it there is because there is a logic in app (and subsequently tests), that depends on data received (which I have omitted for brevity). I thought changing the_action = request.form['action'] to something like the_action = request.form['action'] or '' would solve the problem, but it won't. An easy fix to this is to add some stub data to the post request, like so response = client.post('/action/', data=dict(action='stub')) It feels to me like I'm missing some important points on how accessing&amp;modifying session from tests work, and thus I'm not able to understand the described behaviour. What I would like to understand is: Why simply getting data from request without adding any other logic (i.e. line the_action = request.form['action'] causing 400 Bad Request response on empty POST Why won't the_action = request.form['action'] or '' or the_acti…
accepted answer: http://stackoverflow.com/a/46902453
has comment: http://stackoverflow.com/comment/80669123
tagged with: flask
score: 0
linked to: http://stackoverflow.com/q/14105452
tagged with: http-post
answer count: 1
has comment: http://stackoverflow.com/comment/80710382
has comment: http://stackoverflow.com/comment/80669187
tagged with: python
tagged with: request
type: AnsweredQuestion
has title: Why adding request to a function in flask, causes 'Bad Request' on empty POST?
has answer: http://stackoverflow.com/a/46902453

http://stackoverflow.com/comment/80706062
type: Comment
comment on: http://stackoverflow.com/a/46877297
type: AnswerComment
score: 0
has text: Nicely explained with comments on each row. +1

http://stackoverflow.com/a/46816176
score: 0
answers question: http://stackoverflow.com/q/46815710
has body: Instead of using sys.path you could also add a *.pth-file to your python or anaconda "site-packages"-folder which contains the path to the folder "A". Import via from A.spam import func as @bikemule already proposed.
type: Answer

http://stackoverflow.com/a/46798108
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80543300
has body: You may want to do it differently: def split_file(file): all_words = set() for ln in open(file, 'rU').readlines(): words = ln.strip().split() dot_split = [] for w in words: dot_split.extend(w.split('.')) comma_split = [] for w in dot_split: comma_split.extend(w.split(',')) all_words = all_words.union(set(comma_split)) print(sorted(all_words)) split_file('test_file.txt') or simpler, using regular expressions: import re def split_file2(file): all_words2 = set() for ln in open(file, 'rU').readlines(): words2 = re.split('[ \t\n\.,]', ln.strip()) # note the escaped '.'! all_words2 = all_words2.union(set(words2)) print(sorted(all_words)) As a side note I would refrain from using split as function name as it hides the very function you may want to use from the standard library / string library.
has comment: http://stackoverflow.com/comment/80544341
type: Answer
answers question: http://stackoverflow.com/q/46798074
upvote count: 1
has comment: http://stackoverflow.com/comment/80544555
has comment: http://stackoverflow.com/comment/80553345

http://stackoverflow.com/comment/80655487
comment on: http://stackoverflow.com/q/46838169
score: 0
type: Comment
type: QuestionComment
has text: I can't say without knowing the details of how each program renders, but it's unlikely given your evidence so far.

http://stackoverflow.com/q/46793064
tagged with: python
has title: Python, Flask, SQLAlchemy 500 error with no error message
answer count: 0
tagged with: sqlalchemy
type: Question
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/80533798
has comment: http://stackoverflow.com/comment/80534490
has body: I have a class in my model setup like this: User(db.Model): properties = db.relationship( 'Property', backref='user', lazy='joined') where Property is it's own class, with a foreign key referencing the User table. When I try to access this data like so (I'm omitting a lot of needless code so bear with me): users = User.query.all() return { 'users': [{ 'properties': user.properties } for user in users] } My console just says: 127.0.0.1 - - [17/Oct/2017 10:46:08] "GET /api/auth/me HTTP/1.1" 200 - 127.0.0.1 - - [17/Oct/2017 10:46:09] "GET /api/user/users?page=0&amp;size=25&amp;multiproperty=false&amp;qs=&amp;qc= HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1542, in handle_exception raise e AssertionError No actual error message telling me what is wrong. If my understanding is correct, then user.properties is an array (or list I guess) of objects, each one representing a row i…
has comment: http://stackoverflow.com/comment/80534788
type: UnansweredQuestion

http://stackoverflow.com/comment/80572462
comment on: http://stackoverflow.com/a/46812283
type: AnswerComment
has text: You din't assign groupby to variable `df`. See the edit.
score: 0
type: Comment

http://stackoverflow.com/comment/80641145
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46846752
has text: Is there any documentation indicating that `a` and `b` can be used to access the distribution's limits?
score: 0

http://stackoverflow.com/comment/80737520
has text: Please always post a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) here and read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask).
score: 0
comment on: http://stackoverflow.com/q/46894174
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/125078473
type: AnswerComment
has text: Nice template for using PowerPoint via win32com.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46830300

http://stackoverflow.com/comment/80573938
type: QuestionComment
has text: One thing is certain; `numpy` is the way to do this. Vanilla Python will be much slower with `filter` implementations.
score: 0
comment on: http://stackoverflow.com/q/46813151
type: Comment

http://stackoverflow.com/q/46787181
tagged with: serialization
has answer: http://stackoverflow.com/a/46788103
has body: sorry for my basic question, but I am new to python. I'm trying to read data off an IMU connected through a com port to my PC. I've tried the script: import serial ser = serial.Serial('COM9', 115200, timeout=None) while True: data = ser.readline() but i got the following error: File "", line 2, in File "C:\Program Files (x86)\miControl\mPLC\Python25\lib\site-packages\serial\serialutil.py", line 171, in init self.open() File "C:\Program Files (x86)\miControl\mPLC\Python25\lib\site-packages\serial\serialwin32.py", line 53, in open raise SerialException("could not open port %s: %s" % (self.portstr, msg)) serial.serialutil.SerialException: could not open port COM9: (5, 'CreateFile', 'Access is denied.') was wondering how can I connect the IMU properly and then read the data, knowing that each new data line starts with 'AA 55' thanks in advance.
type: UnansweredQuestion
tagged with: python
has title: reading data off a com port
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/46836518
accepted answer: http://stackoverflow.com/a/46837764
has comment: http://stackoverflow.com/comment/81322684
tagged with: cluster-analysis
has title: Clustering by repeated data
score: 0
has body: Is there a way to split a data set consisting of pairs of 3D points (or just their index numbers) into connected clusters? That is, two pairs (a,b) and (c,d) should be in the same cluster if they share a common point (i.e. a = c, b = c, a = d or b = d) or if there is a chain of one or more other pairs, each sharing a common point with the previous one, from one pair to the other. For example, the list of pairs: [[1,2],[2,3],[4,5],[6,7],[7,8],[9,4],[8,5]] would be grouped as follows: [[1,2],[2,3]] [[4,5],[6,7],[7,8],[9,4],[8,5]] In the first cluster, the pairs (1,2) and (2,3) have the point 2 in common, and share no points with any pairs outside the cluster. In the second cluster, the pair (4,5) shares common points with (9,4) and (8,5), while (8,5) has a common point with (7,8), which has a common point with (6,7). The data is originally stored in a numpy array, but the output format is not too important. I need to be able to access the data that makes up each individual cluster afterwards.
has comment: http://stackoverflow.com/comment/80634074
tagged with: grouping
answer count: 1
has comment: http://stackoverflow.com/comment/80622504
has comment: http://stackoverflow.com/comment/80620680
favorite count: 0
tagged with: connected-components
has answer: http://stackoverflow.com/a/46837764
has comment: http://stackoverflow.com/comment/80622401
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80622603
has comment: http://stackoverflow.com/comment/80951197
has comment: http://stackoverflow.com/comment/80622673
has comment: http://stackoverflow.com/comment/81322928
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80622605
type: Question

http://stackoverflow.com/comment/80718650
score: 0
has text: I am limited to brute-force because there are many of local minima of the SSR but I need to make sure to find the global minimum.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46885031

http://stackoverflow.com/comment/80455037
score: 0
type: AnswerComment
has text: That works, however, in my original program I have 71 list which are displayed in 71 labels and writing this 71 times would be a pain in the ... is there an alternative?
type: Comment
comment on: http://stackoverflow.com/a/46754703

http://stackoverflow.com/a/46856675
upvote count: 10
has comment: http://stackoverflow.com/comment/80704586
has body: A better way of doing this is write this on the root directory of your terminal: find . -regex '.*requirements.txt$' It will search in your root directory and all subfolders for a file called requirements.txt. After the command response, you can get the directory and run the pip install -r requirements.txt on it.
has comment: http://stackoverflow.com/comment/80665584
score: 10
answers question: http://stackoverflow.com/q/46854451
has comment: http://stackoverflow.com/comment/80662962
downvote count: 0
type: Answer

http://stackoverflow.com/comment/80575893
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46806994
has text: @AyodhyankitPaul thank you! problem solved :) I actually check this one https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python, more handy for me to understand
score: 0

http://stackoverflow.com/a/46871865
answers question: http://stackoverflow.com/q/46871767
upvote count: 2
score: 2
has body: Use isin: df = df[df[var].isin(dct.keys())] This gets rid of the loop (well, it doesn't result in an empty dataframe, but why would you want an empty dataframe?). Note that you cannot use the dot notation when referring to columns with variable names. You'll need to use [...] syntax. For more information on where you can, and cannot use the dot notation, see here. You cannot use the dot notation to access columns if the column name begins with a digit contains whitespace characters contains operator symbols and punctuation conflicts with an existing method name or attribute The dot notation is similar to accessing object's attributes, and you must follow python's variable naming rules if you want to access them that way. For anything else, you'll have to use [...]. For a more detailed view, view the note at the bottom of the documentation. Furthermore, don't use dict to name variables, that shadows the builtin dict class with the same name. Now you have used it, use del dict to get back dict functionality.
downvote count: 0
type: Answer

http://stackoverflow.com/a/46755362
score: 8
upvote count: 8
type: Answer
type: AcceptedAnswer
has body: You could use merge with index as well. In [2313]: df1.merge(df2, left_on='accountname', right_index=True).reset_index() Out[2313]: ip accountname name gsm 0 192.168.1.1 aaaa john doe 850 1 192.168.1.2 bbbb jane doe 860
accepted answer of: http://stackoverflow.com/q/46755146
answers question: http://stackoverflow.com/q/46755146
downvote count: 0

linechart
tag name: linechart
tags question: http://stackoverflow.com/q/46790600
tags question: http://stackoverflow.com/q/46755784
tags question: http://stackoverflow.com/q/46870672
type: Tag

http://stackoverflow.com/q/46772932
has answer: http://stackoverflow.com/a/46773597
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/80495814
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
has title: Scraping with BeautifulSoup showing too many rows
has comment: http://stackoverflow.com/comment/80491711
tagged with: css
has body: Thank you for your help in advance! I'm a beginner at this stuff so any help is appreciated. If there is a helpful guide to using beautifulsoup to do this, I'll take a link. Haven't been able to make it work. I would like to scrape this page for wineRatings_initials and wineRatings_rating and averageRating_average and averageRating_number from ul.wineRatings_list, span.pipSecContent_copy, and latitude/longitude from href link under figure.pipWineryImage_map (38.417216 / -122.336862) This brings back all instances of wineRatings_initials, even those under div.prodPedigree, which I don't need. soup.find_all("span", {"class": "wineRatings_initials"}) import urllib2 from bs4 import BeautifulSoup wine_page = 'wine.com/product/shafer-red-shoulder-ranch-chardonnay-2014/‌​…; page = urllib2.urlopen(wine_page) soup = BeautifulSoup(page, 'html.parser') soup.find_all(class_='wineRatings_initials')
tagged with: beautifulsoup
type: UnansweredQuestion
downvote count: 2
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/80492411
type: Question

http://stackoverflow.com/comment/80547389
score: 0
has text: @0TTT0 I have edited it. I prefer not to use turtle.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46800178

http://stackoverflow.com/comment/80680179
score: 2
has text: `spotifydata` is a Python dictionary. You need to pass a JSON formatted _string_ as the `data=` argument—so you'll need to convert the dictionary to JSON format first. This could be done with something like `json_string = json.dumps(spotifydata)`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46866048

http://stackoverflow.com/comment/80539784
score: 0
comment on: http://stackoverflow.com/q/46791439
type: Comment
type: QuestionComment
has text: Hanzy: Not according to https://github.com/pypa/pip/milestone/23

http://stackoverflow.com/a/46886022
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46885938
answers question: http://stackoverflow.com/q/46885938
type: AcceptedAnswer
downvote count: 0
has body: You need to pass the argument to the Check_InActive functin. You should call it this way: Policy = raw_input("Enter Policy Name: ") Flag = Check_InActive(Policy) if (Flag in "Inactive"): print(Policy,"is ",Flag)
has comment: http://stackoverflow.com/comment/80720429

http://stackoverflow.com/q/46785199
tagged with: http://stackoverflow.com/tag/csv
has body: I have a kind of CSV file where the input for one logical line may be split over multiple physical lines. Data example: ":T1","A1","B1","C1" ":T2","A2","B2","C2", "D2","E2" ":T3","A3","B3","C3", "D3" ":T4","A4" This is four logical lines, with the continuation denoted by the trailing comma on the end of lines which split. I tried to use the csv module in python: import csv with open('2.dat','r') as csvfile: datreader = csv.reader(csvfile, delimiter=',' , quotechar='"') for row in datreader: print (', '.join(row)) print ("*******************************") Which gives: :T1, A1, B1, C1 ******************************* :T2, A2, B2, C2, ******************************* D2, E2 ******************************* :T3, A3, B3, C3, ******************************* D3 ******************************* :T4, A4 ******************************* What I'd like: :T1, A1, B1, C1 ******************************* :T2, A2, B2, C2, D2, E2 ******************************* :T3, A3, B3, C3, D3 ******************************* :T4, A4 ******************************* I'm unsure of the best way to use csv module to parse this data correctly. Input data set could be millions of rows.
has title: Reading a CSV in Python where input lines are split
accepted answer: http://stackoverflow.com/a/46785791
answer count: 4
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46785358
possible better answer: http://stackoverflow.com/a/46785591
has answer: http://stackoverflow.com/a/46786057
has answer: http://stackoverflow.com/a/46785591
has comment: http://stackoverflow.com/comment/80516832
type: AnsweredQuestion
score: 0
downvote count: 1
has answer: http://stackoverflow.com/a/46785791
type: Question

http://stackoverflow.com/q/46795018
has comment: http://stackoverflow.com/comment/80543543
has comment: http://stackoverflow.com/comment/80542058
type: AnsweredQuestion
score: 2
tagged with: tkinter
downvote count: 0
has answer: http://stackoverflow.com/a/46798512
accepted answer: http://stackoverflow.com/a/46798512
type: Question
has comment: http://stackoverflow.com/comment/80539909
has title: ttk.OptionMenu has no outline/border
upvote count: 2
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/80540463
has body: I am using ttk.Optionmenu() in my GUI but am annoyed that when there is no mouse-over condition, the menu/button does not have any visuals showing its border. It is not giving me any element_options to see if I can change specific styling for this widget. I would love it if there was a way for the button to look like a button all the time instead of just when it gets focus... otherwise it looks sort of blaghh. import tkinter as tk from tkinter import ttk root = tk.Tk() var = tk.StringVar(root) opmenu = ttk.OptionMenu(root, var, 'One', 'Two', 'Three') opmenu.pack() root.mainloop() I know how to change the style for the widgets but none address its at-rest appearance. I've tried 'googling' in hopes to find a solution but to no avail. Using Python 3.5.2 and tkinter 8.6
possible better answer: http://stackoverflow.com/a/48821908
has answer: http://stackoverflow.com/a/48821908
has comment: http://stackoverflow.com/comment/80542587
tagged with: python

http://stackoverflow.com/q/46762933
has body: I am a beginner. I would like to get list employees have age > 25 and calculate the average age of employees. Currently, we need to get age from birthday (I have no idea about it ^^) . Please help me create sample QuerySet/Manager about it. Thanks all :)) My model: class Employee(models.Model): """"Employee model""" first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthday = models.DateField(max_length=8) Note: Not get all employees and filter from the results. (results = Employee.objects.all()) and not use Raw SQL.
score: 3
has answer: http://stackoverflow.com/a/46765454
answer count: 2
has answer: http://stackoverflow.com/a/46772611
tagged with: django-queryset
linked to: http://stackoverflow.com/q/34772465
downvote count: 0
favorite count: 0
has title: Django QuerySet/Manager filter employees by age from birthday
tagged with: python
upvote count: 3
linked to: http://stackoverflow.com/q/2364952
type: UnansweredQuestion
tagged with: django
type: Question

http://stackoverflow.com/comment/80592369
type: Comment
score: 0
has text: Thank you very much, that last information you added did the work. I still don't have very clear what is it doing. But I'll find out. Thank you.
comment on: http://stackoverflow.com/a/46821740
type: AnswerComment

http://stackoverflow.com/comment/80524192
type: Comment
type: QuestionComment
has text: @titusjan, you are both correct, removing the selected node and inserting a new one is a bad idea, and does not work. If I do appendRow, then I will have parent2 appearing more than once also as I believe self.model.appendRow(parent_item) would add the new parent_item to the bottom of the model. All I want to do is to Update the selected row
comment on: http://stackoverflow.com/q/46778623
score: 0

http://stackoverflow.com/comment/80628932
comment on: http://stackoverflow.com/q/46840536
score: 0
has text: There is no need to try to do it yourself since there are already modules that do it for you. You don't have to reinvent the wheel.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80688776
score: 0
has text: yes, it could be say number of meters walked
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46870718

http://stackoverflow.com/a/48194725
downvote count: 0
answers question: http://stackoverflow.com/q/46805662
upvote count: 2
has body: i don't know if this helps. I always add the id field in the serializer due to that similar issue: id = serializers.ModelField(model_field=YourModel._meta.get_field('id'), required=False) Make sure it's required=False because when you create a new record the id field is not present.
type: Answer
score: 2

http://stackoverflow.com/comment/80762337
score: 0
type: AnswerComment
has text: I think that the problem with your solution is that K value (K-permutations from N) will also be incremented every time when N will be incremented.
type: Comment
comment on: http://stackoverflow.com/a/46873419

http://stackoverflow.com/q/46900364
has comment: http://stackoverflow.com/comment/80747939
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/80747959
upvote count: 10
tagged with: python
has title: Select columns with name matching str with wildcard for t-test (Python)
has body: I have Apple f2 m Apple f2 t Apple f3 m Apple f3 t 0 3 4 5 3 1 12 7 4 7 2 5 9 7 5 3 3 3 4 8 4 7 1 2 6 I would like to select columns with str = 'Apple f* m' to do a t-test against columns with str = 'Apple f* t' I have tried ttest_ind(df.loc[:,df.columns.str.contains('Apple R* m')], df.loc[:,df.columns.str.contains('Apple R* t')] However, it doesn't recognise my wildcard has a wildcard. Thank you if you an help me solve or guide me for this problem.
downvote count: 0
has answer: http://stackoverflow.com/a/46900526
accepted answer: http://stackoverflow.com/a/46900526
type: Question
type: AnsweredQuestion
score: 10
has comment: http://stackoverflow.com/comment/80747788
linked to: http://stackoverflow.com/q/21197394
answer count: 2
possible better answer: http://stackoverflow.com/a/46900555
has answer: http://stackoverflow.com/a/46900555

http://stackoverflow.com/comment/115343934
has text: Do you know if there has been any progress on getting the ability to write out CSV values? In my case I don't even have dicts, just tuples in my `PCollection`. I think what's needed is something like `WriteToCSV` similar to `WriteToText`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46796204

http://stackoverflow.com/a/46806154
answers question: http://stackoverflow.com/q/46805851
upvote count: 1
has body: My suggestion: import io import pandas as pd from collections import defaultdict string = u"""province_id,wave,value 1,2014,10 1,2014,10 1,2013,10 2,2010,10 3,2010,10""" df = pd.read_csv(io.StringIO(string)) # Output: d = defaultdict(dict) # This splits the dataframe by province_id and wave dfs = df.groupby(["province_id","wave"]) # Loop through the dataframes and stucture them for ind,df in dfs: d[ind[0]][ind[1]] = df The resulting dictionary structure looks like this: { "1": { "2013": "dataframe: 1 2013", "2014": "dataframe: 1 2014" }, "2": { "2010": "dataframe: 2 2010" }, "3": { "2010": "dataframe: 3 2010" } } And you access the dataframes by e.g.: d[1][2013]
has comment: http://stackoverflow.com/comment/80607675
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/80454015
comment on: http://stackoverflow.com/a/46750919
score: 0
type: AnswerComment
type: Comment
has text: Thank you! I will definitely take a look at this as well.

http://stackoverflow.com/q/46758146
tagged with: keras
favorite count: 0
tagged with: python
has title: ImportError: cannot import name get_uid 2
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I am using Python 2.7, with keras 1.2.2 from sklearn.datasets import load_files import numpy as np from keras.utils import np_utils from glob import glob # define function to load train, test, and validation datasets def load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data['target']), 133) return dog_files, dog_targets # load train, test, and validation datasets train_files, train_targets = load_dataset('dogImages/train') valid_files, valid_targets = load_dataset('dogImages/valid') test_files, test_targets = load_dataset('dogImages/test') # load list of dog names dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))] # print statistics about the dataset print('There are %d total dog categories.' % len(dog_names)) print('There are %d total dog images.\n' % len(np.hstack([train_files, valid_files, test_files]))) print('There are %d training dog images.' % len(train_files)) print('There are %d validation dog images.' % len(valid_files)) print('There are %d test dog images.'% len(test_files)) I get the following error: ImportErrorTraceback (most recent call last) &lt;ipython-input-10-c760281b33b0&gt; in &lt;module&gt;() 1 from sklearn.datasets import load_files 2 import numpy as np ----&gt; 3 from keras.utils import np_utils 4 from glob import glob 5 C:\Users\ElPanda\Anaconda2\lib\site-packages\keras\__init__.py in &lt;module&gt;() 1 from __future__ import absolute_import ----&gt; 2 from . import backend 3 from . import datasets 4 from . import engine 5 from . import layers C:\Users\ElPanda\Anaconda2\lib\site-packages\keras\backend\__init__.py in &lt;module&gt;() 8 from .common import set_epsilon 9 from .common import set_floatx ---&gt; 10 from .common import get_uid 11 from .common import cast_to_floatx 12 from .common import image_dim_ordering ImportError: cannot import name get_uid I don't see any similar questions like with the appropriate answer. Any help would be g…
has answer: http://stackoverflow.com/a/47195963
accepted answer: http://stackoverflow.com/a/47195963
upvote count: 1
answer count: 1

apache
tag name: apache
tags question: http://stackoverflow.com/q/46881243
tags question: http://stackoverflow.com/q/46890013
tags question: http://stackoverflow.com/q/46780954
tags question: http://stackoverflow.com/q/46874385
tags question: http://stackoverflow.com/q/46863628
tags question: http://stackoverflow.com/q/46791164
tags question: http://stackoverflow.com/q/46805863
tags question: http://stackoverflow.com/q/46890464
tags question: http://stackoverflow.com/q/46787428
tags question: http://stackoverflow.com/q/46772117
tags question: http://stackoverflow.com/q/46814197
tags question: http://stackoverflow.com/q/46891408
tags question: http://stackoverflow.com/q/46812957
tags question: http://stackoverflow.com/q/46889709
tags question: http://stackoverflow.com/q/46759730
type: Tag

http://stackoverflow.com/comment/80749010
has text: This is what i used: `def encrypt(text, rot): lis = [] key = 0 for i in range(len(text)): if text[i].isalpha(): lis.append(rotate_character(text[i], alphabet_position(rot[key % len(rot)])))` if text[i] == " ": key = key -1 else: key +=1` ` else:` ` lis.append(text[i])` ` return (''.join(lis))`
comment on: http://stackoverflow.com/a/46865070
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80462755
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46757757
type: Comment
has text: Theoretical time complexity often ends up very irrelevant when looking at the algorithm running on real-life data, you shouldn’t be too fixated on this. And even more so in a language like Python, that is run on a virtual machine. I wouldn’t be suprised if the linked list (implemented in Python) would end up being more expensive than the native array implementation of a list, even if it is theoretically of lower complexity.

http://stackoverflow.com/comment/80503262
comment on: http://stackoverflow.com/q/46778621
type: Comment
has text: Too much code, please reduce this to a [mcve].
type: QuestionComment
score: 3

http://stackoverflow.com/comment/99106981
score: 2
comment on: http://stackoverflow.com/a/46779290
type: AnswerComment
has text: By the way, `mypy` allows omitting ` -> None` from `__init__` – although heavily discussed – because of the reason that `__init__` can only have this return type (for type checking ` -> None` is automatically appendend), see https://github.com/python/mypy/issues/604
type: Comment

http://stackoverflow.com/a/46821765
answers question: http://stackoverflow.com/q/46820685
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: You could override the clean method in admin.py: from django.core.exceptions import ValidationError def clean(self): windows = {'HP','otherbrand1','otherbrand2'} if self.cleaned_data['brand'] in windows and \ (self.cleaned_data['mac_os'] or self.cleaned_data['linux']): raise ValidationError('Only windows is allowed') return self.cleaned_data cleaned_data is a dict of values that have been validated by the form. Therefore, you're validating that someone doesn't enter a value for fields mac_os or linux if a windows brand was specified beforehand. Note that this will not be the exact behavior you were expecting. Indeed, this will only raise an error message to the user if he tries to save the model. If you absolutely need to have an in-time solution, you'll need more JS than Django code.

http://stackoverflow.com/a/46899298
score: 3
has comment: http://stackoverflow.com/comment/80783264
has comment: http://stackoverflow.com/comment/80775225
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/46897671
has comment: http://stackoverflow.com/comment/80745831
has body: You need to have a Bool that tells when to show the new input should be shown. You also need to be constantly polling the ComboBox to see if it's value is equal to "Custom". This is what I came up with in about 3 minutes. I didn't try to make the GUI look pretty, just a functional example. from tkinter import * from tkinter.ttk import * class Gui: def __init__(self): self.root = Tk() # Set up the Combobox self.selections = Combobox(self.root) self.selections['values'] = ['Apples', 'Oranges', 'Blueberries', 'Bananas', 'Custom'] self.selections.pack() # The Entry to be shown if "Custom" is selected self.custom_field = Entry(self.root) self.show_custom_field = False # Check the selection in 100 ms self.root.after(100, self.check_for_selection) def check_for_selection(self): '''Checks if the value of the Combobox equals "Custom".''' # Get the value of the Combobox value = self.selections.get() # If the value is equal to "Custom" and show_field is set to False if value == 'Custom' and not self.show_custom_field: # Set show_field to True and pack() the custom entry field self.show_custom_field = True self.custom_field.pack() # If the value DOESNT equal "Custom" elif value != 'Custom': # Set show_field to False self.show_custom_field = False # Destroy the custom input self.custom_field.destroy() # Set up a new Entry object to pack() if we need it later. # Without this line, tkinter was raising an error for me. # This fixed it, but I don't promise that this is the # most efficient method to do this. self.custom_field = Entry(self.root) # If the value IS "Custom" and we're showing the custom_feild elif value == 'Custom' and self.show_custom_field: pass # Call this method again to keep checking the selection box self.root.after(100, self.check_for_selection) app = Gui() app.root.mainloop() Hope this helps! EDIT: To open a new window instead of packing it inside the same window as the Combobox, replace the function check_for_selection with this: def check_for_selection(self): …
answers question: http://stackoverflow.com/q/46897671
downvote count: 0
has comment: http://stackoverflow.com/comment/80787492
has comment: http://stackoverflow.com/comment/80818056

http://stackoverflow.com/a/46914882
has body: The solution is to use Kivy NumericProperty and hook it up. Please refer to the example below for details. Example main.py from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import NumericProperty class ScreenManagement(ScreenManager): pass class Start(Screen): startvalue = NumericProperty(0) class End(Screen): def which_color(self, startvalue): print("startvalue={}".format(startvalue)) if startvalue == 1: self.bg_image.source = 'blue.png' elif startvalue == 2: self.bg_image.source = 'red.png' elif startvalue == 3: self.bg_image.source = 'yellow.jpg' elif startvalue == 4: self.bg_image.source = 'green.jpg' class TestApp(App): def build(self): return ScreenManagement() if __name__ == "__main__": TestApp().run() test.kv #:kivy 1.10.0 &lt;ScreenManagement&gt;: Start: id: start End: startvalue: start.startvalue &lt;Start&gt;: name: 'start' BoxLayout: Button: name: 'btn1' id: btn1 text: "btn1" on_release: root.startvalue = 1 app.root.current = 'end' Button: name: 'btn2' id: btn2 text: "btn2" on_release: root.startvalue = 2 app.root.current = 'end' Button: name: 'btn3' id: btn3 text: "btn3" on_release: root.startvalue = 3 app.root.current = 'end' Button: name: 'btn4' id: btn4 text: "btn4" on_release: root.startvalue = 4 app.root.current = 'end' &lt;End&gt;: id: end name: "end" endbtn: endbtn bg_image: bg_image on_pre_enter: self.which_color(root.startvalue) Image: id: bg_image source: "" allow_stretch: True Button: name: 'endbtn' id: endbtn text: "end" size_hint_y: .35 size_hint_x: .25 on_release: app.root.current = 'start' Output
answers question: http://stackoverflow.com/q/46903492
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/46903492
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/46898644
favorite count: 0
has body: I am trying to access the text in an element whose content is generated by javascript. For example getting the number of twitter shares from this site. I've tried using urllib and pyqt to obtain the html of the page, however since the content requires javascript to be generated, its HTML is not present in the response of urllib/pyqt. I am currently using selenium for this task, however it is taking longer than I would like it to. Is it possible to get access to this data without opening the page in a browser? This question has already been asked in the past, but the results I found are either c# specific or provide a link to a solution that has since gone dead
tagged with: http://stackoverflow.com/tag/html
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/46898818
has title: Scraping elements generated by javascript queries using python
tagged with: web-scraping
linked to: http://stackoverflow.com/q/24130650
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46898984
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/46898818
has comment: http://stackoverflow.com/comment/80744866
downvote count: 0
possible better answer: http://stackoverflow.com/a/46898984
tagged with: javascript
linked to: http://stackoverflow.com/q/2707108

http://stackoverflow.com/comment/84331464
score: 0
type: AnswerComment
has text: The same window would've popped up and disappeared. You had relative and absolute pathing issues between code and task scheduler set-up (i.e. point the task sched execution to the working directory of the script).
type: Comment
comment on: http://stackoverflow.com/a/46886831

http://stackoverflow.com/a/46901672
type: Answer
has body: You are in while loop of else conditional since you entered 100 at first and you can't get out of there unless you enter a number satisfies 0 &lt;= a &lt;= 99. You can make another if statement for a == 0 to exit the while loop just below a = int(input('Enter a number')) of else conditional. I think it is good to check where you are in while loop using just one print(a). For example, just before if-else conditional or just before while of else conditional. Then, you can check where it gets wrong. a = int(input('Enter a number: ')) total = 0 keep = True while keep: \\ print(a) here to make sure if you are passing here or not. if a == 0: print('Thanks for playing.. goodbye') break; else: \\ print(a) here to make sure if you are passing here or not. while a &gt; 99 or a &lt; 0: \\You are in while loop since you entered 100 at first and you can't get out from here unless you enter a: 0 &lt;= a &lt;= 99. print('INVALID') a = int(input('Enter a number: ')) if a == 0: print('Thanks for playing.. goodbye') break; total = total + a print(total) a = int(input('Enter a number: '))
answers question: http://stackoverflow.com/q/46901509
score: 0

http://stackoverflow.com/q/46852669
type: Question
has body: I want to scrap the following website https://www.shopee.sg: ~$ scrapy shell https://www.shopee.sg But I got a 404 error: [s] request &lt;GET https://www.shopee.sg&gt; [s] response &lt;404 https://shopee.sg/&gt; While urllib2 can open this same url: import urllib2 response = urllib2.urlopen('https://www.shopee.sg') print len(response.read()) shows: 78447
answer count: 1
tagged with: python
type: UnansweredQuestion
score: 0
has title: error 404 with Scrapy but not with urllib2
has answer: http://stackoverflow.com/a/46860962
tagged with: scrapy

http://stackoverflow.com/a/46782229
has comment: http://stackoverflow.com/comment/109873903
answers question: http://stackoverflow.com/q/46758360
has comment: http://stackoverflow.com/comment/109894854
has comment: http://stackoverflow.com/comment/109873892
has comment: http://stackoverflow.com/comment/80528102
type: AcceptedAnswer
upvote count: 16
has comment: http://stackoverflow.com/comment/80528182
has comment: http://stackoverflow.com/comment/109862256
has comment: http://stackoverflow.com/comment/80525847
type: Answer
has body: If you are open for external libraries, you can install vlc binding for python using pip install python-vlc And use player method to play audio file directly from URL as below. import vlc import time url = 'http://prem1.rockradio.com:80/bluesrock?9555ae7caa92404c73cade1d' #define VLC instance instance = vlc.Instance('--input-repeat=-1', '--fullscreen') #Define VLC player player=instance.media_player_new() #Define VLC media media=instance.media_new(url) #Set player media player.set_media(media) #Play the media player.play() Advantage of vlc player is that you can play most media types directly from URL (not just mp3) and also perform player like options such as &gt;&gt;&gt; player.pause() #pause play back &gt;&gt;&gt; player.play() #resume play back &gt;&gt;&gt; player.stop() #stop play back
downvote count: 0
score: 16
accepted answer of: http://stackoverflow.com/q/46758360

http://stackoverflow.com/comment/80601729
type: Comment
has text: @Uriel I'll add that `None` is a singleton object in Python, so you actually are checking for objects being identical. Test `id(None.__class__())` compared to `id(None`)`, or if it's python 2 it will complain you can't create None types.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46826822

http://stackoverflow.com/q/46902563
type: UnansweredQuestion
has title: How to show progress when using apply in dask.dataframe?
upvote count: 1
tagged with: python
score: 1
has body: I used to use pandas and tqdm to show the progress of an apply function with progress_apply which is introduced here. I'm now shifting to use dask which seems not to be supported by tqdm directly. I have tried ProgressBar but it cannot show the time for one iteration. I am wondering how to show a tqdm like progress when using apply in dask.dataframe? P.S. I have tried this but still failed.
has comment: http://stackoverflow.com/comment/80771593
type: Question
downvote count: 0
tagged with: tqdm
favorite count: 0
tagged with: dask
answer count: 0

http://stackoverflow.com/comment/80582781
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46817583
type: Comment
has text: Its a method of a class robot.rotate_left()

http://stackoverflow.com/q/46848079
has title: Bash or Python : Append and prepend a string recursively in all .tex files
accepted answer: http://stackoverflow.com/a/46854623
type: Question
has comment: http://stackoverflow.com/comment/80644298
downvote count: 0
tagged with: bash
has body: I'm trying to find a way to change my master/child document workflow in LaTeX using the package "subfiles", so I'm trying to append and prepend to every file I already have the following lines: Lines to prepend: \documentclass[&lt;mainfile&gt;]{subfiles} \begin{document} Line to appen: \end{document} I was thinking of using bash but I could be nice too with Python, I don't know what would be best. If you have any suggestion :-) ?
answer count: 1
has answer: http://stackoverflow.com/a/46854623
tagged with: prepend
has comment: http://stackoverflow.com/comment/80644302
tagged with: append
favorite count: 0
tagged with: latex
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/80585820
has text: `"".join(sorted((set("cbacdcbc"))))` You can use one line in python to remove duplicates
type: QuestionComment
comment on: http://stackoverflow.com/q/46819013
type: Comment
score: 0

http://stackoverflow.com/comment/80539189
has text: If those "boxes" are inside other "boxes", maybe you should use a nested dictionary, or a dedicated `BoxInABox` class. Or use different dicts/lists and merge them together after the assignments. Or just put some line comments above each group.
score: 1
comment on: http://stackoverflow.com/q/46796211
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46837447
downvote count: 0
has comment: http://stackoverflow.com/comment/80654908
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80633161
has body: To get the total solve time (in wall clock time), you can use the get_time method. To get the value for "Network time", as displayed in the log output, you'll have to parse the log output. Here's an example that demonstrates both of these: from __future__ import print_function import sys import cplex class OutputProcessor(object): """File-like object that processes CPLEX output.""" def __init__(self): self.network_time = None def write(self, line): if line.find("Network time =") &gt;= 0: tokens = line.split() try: # Expecting the time to be the fourth token. E.g., # "Network", "time", "=", "0.48", "sec.", ... self.network_time = float(tokens[3]) except ValueError: print("WARNING: Failed to parse network time!") print(line, end='') def flush(self): sys.stdout.flush() def main(): c = cplex.Cplex() outproc = OutputProcessor() # Intercept the results stream with our output processor. c.set_results_stream(outproc) # Read in a model file (required command line argument). This is # purely an example, thus no error handling. c.read(sys.argv[1]) c.parameters.lpmethod.set(c.parameters.lpmethod.values.network) start_time = c.get_time() c.solve() end_time = c.get_time() print("Total solve time (sec.):", end_time - start_time) print("Network time (sec.):", outproc.network_time) if __name__ == "__main__": main() That should give you an idea of how to parse out other pieces of information from the log (it is not meant to be an example of a sophisticated parser). You may be interested in get_dettime as well; it can be used the same way as get_time (as above), but is not susceptible to the load on your machine.
accepted answer of: http://stackoverflow.com/q/46832501
has comment: http://stackoverflow.com/comment/80652824
answers question: http://stackoverflow.com/q/46832501
type: Answer
score: 2

http://stackoverflow.com/q/46826437
tagged with: python
answer count: 0
downvote count: 0
score: 1
tagged with: mapreduce
type: Question
tagged with: hadoop
has title: People you may know using MapReduce in python
has comment: http://stackoverflow.com/comment/80600556
has comment: http://stackoverflow.com/comment/80615158
upvote count: 1
favorite count: 0
has body: I've trying to build people you may know using MapReduce in python such that it should display result for people(top 5) with maximum no. recommendation. The data set is in the format of &lt;user_id&gt;&lt;tab space&gt;&lt;friend_1_id,friend_2_id_2, . . .&gt; the code I've used is. Explanation: http://andresromero.github.io/People-you-may-know/ Mapper #!/usr/bin/env python2 import itertools import sys for line in sys.stdin: line = line.strip() line = line.split("\t") key = int(line[0]) if len(line)&gt;1: friends = line[1] if friends!='': friends = line[1].split(",") friends = sorted(map(int,friends)) for friend in friends: pair = tuple(sorted([key,friend])) pair = ','.join(map(str,pair)) print pair,"\t",1 for pair in itertools.combinations(friends,2): pair = ','.join(map(str,pair)) print pair,"\t",0 Reducer #!/usr/bin/env python2 import itertools import sys flist={} def checking(k,size): if len(flist)==0 | len(flist)&lt;5: return 0 elif len(flist) &gt; 5: for i in flist.keys(): if len(flist[i]) &lt; size: return i; else: return -1 def addPair(users,k1,k2,friendFlag): if friendFlag==1: friendFlag = True else: friendFlag = False if k1 not in users: users[k1] = {} users[k1][k2] = [1,False] else: if k2 in users[k1]: users[k1][k2][0] += 1 else: users[k1][k2] = [1,False] if friendFlag==True: users[k1][k2][0] -= 1 users[k1][k2][1] = True users = {} for line in sys.stdin: line = line.strip() line = line.split("\t") key = tuple(map(int,line[0].strip().split(","))) friendFlag = int(line[1]) k1,k2 = key addPair(users,k1,k2,friendFlag) addPair(users,k2,k1,friendFlag) for k1 in users.keys(): recommendations = [] for k2 in users[k1].keys(): n,flag = users[k1][k2] if flag==False: recommendations.append((k2,n)) recommendations = sorted(recommendations,key=lambda x: x[0]) recommendations = sorted(recommendations,key=lambda x: x[1],reverse=True) if len(recommendations)&gt;0: recommendations = list(map(str,zip(*recommendations)[0])) flag=checking(k1,len(recommendations)) if flag==0: fl…
type: UnansweredQuestion

http://stackoverflow.com/a/46781428
answers question: http://stackoverflow.com/q/46779605
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80510028
has comment: http://stackoverflow.com/comment/119714581
has body: fit_intercept=False sets the y-intercept to 0. If fit_intercept=True, the y-intercept will be determined by the line of best fit. from sklearn.linear_model import LinearRegression from sklearn.datasets import make_regression import numpy as np import matplotlib.pyplot as plt bias = 100 X = np.arange(1000).reshape(-1,1) y_true = np.ravel(X.dot(0.3) + bias) noise = np.random.normal(0, 60, 1000) y = y_true + noise lr_fi_true = LinearRegression(fit_intercept=True) lr_fi_false = LinearRegression(fit_intercept=False) lr_fi_true.fit(X, y) lr_fi_false.fit(X, y) print('Intercept when fit_intercept=True : {:.5f}'.format(lr_fi_true.intercept_)) print('Intercept when fit_intercept=False : {:.5f}'.format(lr_fi_false.intercept_)) lr_fi_true_yhat = np.dot(X, lr_fi_true.coef_) + lr_fi_true.intercept_ lr_fi_false_yhat = np.dot(X, lr_fi_false.coef_) + lr_fi_false.intercept_ plt.scatter(X, y, label='Actual points') plt.plot(X, lr_fi_true_yhat, 'r--', label='fit_intercept=True') plt.plot(X, lr_fi_false_yhat, 'r-', label='fit_intercept=False') plt.legend() plt.vlines(0, 0, y.max()) plt.hlines(bias, X.min(), X.max()) plt.hlines(0, X.min(), X.max()) plt.show() This example prints: Intercept when fit_intercept=True : 100.32210 Intercept when fit_intercept=False : 0.00000 Visually it becomes clear what fit_intercept does. When fit_intercept=True, the line of best fit is allowed to "fit" the y-axis (close to 100 in this example). When fit_intercept=False, the intercept is forced to the origin (0, 0). What happens if I include a column of ones or zeros and set fit_intercept to True or False? Below shows an example of how to inspect this. from sklearn.linear_model import LinearRegression from sklearn.datasets import make_regression import numpy as np import matplotlib.pyplot as plt np.random.seed(1) bias = 100 X = np.arange(1000).reshape(-1,1) y_true = np.ravel(X.dot(0.3) + bias) noise = np.random.normal(0, 60, 1000) y = y_true + noise # with column of ones X_with_ones = np.hstack((np.ones((X.…
upvote count: 60
type: Answer
has comment: http://stackoverflow.com/comment/119689876
has comment: http://stackoverflow.com/comment/136383161
downvote count: 0
score: 60
has comment: http://stackoverflow.com/comment/127154427
has comment: http://stackoverflow.com/comment/119718678
accepted answer of: http://stackoverflow.com/q/46779605

http://stackoverflow.com/comment/80564307
type: Comment
comment on: http://stackoverflow.com/q/46808438
score: 1
has text: You only have to make the choice **once**, then pick responses based on the user input (use `if userInput == 'rock':`, etc.)
type: QuestionComment

http://stackoverflow.com/q/46852296
score: 0
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/80652752
has title: filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
tagged with: python
has body: I want to find the animal which have brown color (column 'color') and for those animals keep all the information about it (all the rows), and for the animals which have not brown colour, delete all informations about it (all the rows). Any insight? df = pd.DataFrame([['dog','France','white'],['dog','Japon','brown'],['cat','France','white'],['cat','France','dark']],columns=['Animal','localisation','couleur']) output = pd.DataFrame([['dog','France','white'],['dog','Japon','brown']],columns=['Animal','localisation','couleur'])
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46855495
accepted answer: http://stackoverflow.com/a/46852348
possible better answer: http://stackoverflow.com/a/46852408
has answer: http://stackoverflow.com/a/46852408
type: Question
has answer: http://stackoverflow.com/a/46852348
tagged with: dataframe

http://stackoverflow.com/comment/80707474
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46880085
has text: @UKcodeNovice if this answer assisted you, please consider accepting it. Thank you!
score: 0

http://stackoverflow.com/q/46900020
linked to: http://stackoverflow.com/q/46912969
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46900361
upvote count: 1
tagged with: python
has title: Install a newer Python when there are installed packages linked against the old one
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46900361
has answer: http://stackoverflow.com/a/46901541
tagged with: conda
type: Question
answer count: 2
has body: (Please bear with me for the long description, it has been quite a troubleshooting journey.) My ultimate goal is to get python package graph_tool working on my system and also on ipynb if possible. I have already brew install graph-tool, as indicated here, but that's still insufficient. So I follow conda instructions here, and try to fulfill all requirements including having cgal and python3.6. I had anaconda with python2.7 and python3.5 originally, but since python3.6 is necessary, I download anaconda3 with python3.6. (conda update python still kept giving me 3.5) I delete /Users/mymacbook/anaconda, so that /Users/mymacbook/anaconda3 would the default search directory. And I have a mini-success! $ python3 Python 3.6.2 |Anaconda, Inc.| (default, Sep 21 2017, 18:29:43) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. Unfortunately, as I continue to conda install the other packages required (boost, cgal, etc), my python3 is reverted back to 3.5 :( $ python3 Python 3.5.4 |Anaconda custom (x86_64)| (default, Oct 5 2017, 02:58:14) $ conda install python=3.6 Fetching package metadata ........... Solving package specifications: . UnsatisfiableError: The following specifications were found to be in conflict: - cgal -&gt; python 3.5* - python 3.6* Use "conda info &lt;package&gt;" to see the dependencies for each package. $ conda info cgal Fetching package metadata ........... ResolvePackageNotFound: - cgal Quite a pickle isn't it... A recommendation was to uninstall cgal due to ResolvePackageNotFound, but like I mentioned, I need both cgal and python3.6. Thanks in advance for the help! (and please include applicable command lines with your suggestions - I'm a beginner)
downvote count: 0
possible better answer: http://stackoverflow.com/a/46901541

http://stackoverflow.com/q/46853738
has answer: http://stackoverflow.com/a/46857351
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46854043
upvote count: 1
has body: I have a large project where I load in some variables from a config.ini, such as the target_directory of the data that is generated. This target_directory is used all over the project but it is not always set in the same place. It can be set by config.ini, but it can be overridden by command line parameters or also by unit tests. What is the best way to preserve that state in a global way, so I don't have to pass it into every function of my program. The program consists of many different modules and packages and I was wondering if there's a best practice how this could be handled.
favorite count: 0
possible better answer: http://stackoverflow.com/a/46854043
accepted answer: http://stackoverflow.com/a/46857351
tagged with: python
type: AnsweredQuestion
has title: Conserving a state in a large python program without passing variable as parameter
downvote count: 0

http://stackoverflow.com/comment/80514876
type: QuestionComment
has text: Check [this answer](https://stackoverflow.com/questions/17217194/extracting-table-contents-from-a-collection-of-pdf-files/26110587#26110587), it might be useful.
score: 0
comment on: http://stackoverflow.com/q/46783784
type: Comment

http://stackoverflow.com/comment/80707359
comment on: http://stackoverflow.com/a/46879919
has text: To tell you the truth, the days are the values. The table days has two column 'int pk' and 'int day'. The `[1, 3, 5]` represents the entries `(1, 1)`, `2, 3)`, `(3, 5)`. I'd like DRF to look in the table Days and either find those values (1, 3, 5) or create them and make the M2Ms. Your suggestion is probably 100% valid. I just want to understand how would this work if I'm receiving values from the client and not the keys.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46792667
favorite count: 0
tagged with: parsing
tagged with: eval
has answer: http://stackoverflow.com/a/46792893
accepted answer: http://stackoverflow.com/a/46792893
tagged with: python
tagged with: nlp
type: AnsweredQuestion
score: 2
has title: Convert a set of tuples into values
downvote count: 0
has answer: http://stackoverflow.com/a/46792970
has comment: http://stackoverflow.com/comment/80531871
linked to: http://stackoverflow.com/q/7935680
type: Question
has comment: http://stackoverflow.com/comment/80532039
has body: I'm working on an nlp project in which I need to parse tags. I have multiple tags in the following form: a string that is a set of tuples. Example: '{(Entertainment (Adult), S), (Performing Arts, S), (Comedy Club, S), ($, S), (Comedy, P), (18+, S), (Plays &amp; Shows, P)}' But I want it to look like this: {('Entertainment (Adult)', 'S'), ('Performing Arts', 'S'), ('Comedy Club', 'S'), ('$', 'S'), ('Comedy', 'P'), ('18+', 'S'), ('Plays &amp; Shows', 'P')} I tried using literal_eval per this question, but I get an invalid syntax error. I think this is because the tag is a set, which contains tuples, which contain strings that are not cast as strings, so the literal_eval gets confused (just guessing here). I tried doing some bandaid-y string strips and splits, but I can't get a solution that will work dynamically for different tags.
has comment: http://stackoverflow.com/comment/80532230
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/80531911
possible better answer: http://stackoverflow.com/a/46792970
tagged with: string

http://stackoverflow.com/comment/80522554
type: QuestionComment
comment on: http://stackoverflow.com/q/46788125
has text: Can the nginx user actually access that directory?
score: 0
type: Comment

http://stackoverflow.com/q/46782135
has body: Here's the scenario, there's a nested list called board, and it is passed into the function, and I want to do some modification to the content to the list. However, during the process, I found out that by assigning the variable to an empty list actually does something weird and any modifications on the board list does not affect the original board outside the function. Here's what I mean: (It doesn't matter what the function does specifically) This is modifyiing a particular slot in the list, and it works and does affect the original board. def move_up(board): board[1][2] = '.' This is fine also since appending technically is modifying the list, this affects the original board too. def move_up(board): board.append(['.', 'F', '*', 'F', '.']) This, however, doesn't work. This does not affect the original board, and I'm wondering why. The board variable shows gray, it almost feels like by doing =[], it is resetting the variable to something else, a new object, but I'm not really sure why. def move_up(board): board = [] board = [[1,2],[3,4]] board[1][1] = 5 Or, is this something with the scope? Please explain how this works in Python, thanks!
has comment: http://stackoverflow.com/comment/80510588
has comment: http://stackoverflow.com/comment/80510747
has comment: http://stackoverflow.com/comment/80510701
has title: Does setting a variable to empty list in Python reset the variable?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80510679
has comment: http://stackoverflow.com/comment/80510621
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46782295
has comment: http://stackoverflow.com/comment/80510771
has comment: http://stackoverflow.com/comment/80510858
score: 1
has comment: http://stackoverflow.com/comment/80510800
has comment: http://stackoverflow.com/comment/80510876
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80510738
has comment: http://stackoverflow.com/comment/80510849
accepted answer: http://stackoverflow.com/a/46782295
favorite count: 0
has comment: http://stackoverflow.com/comment/80510731

http://stackoverflow.com/q/46788852
tagged with: python
has title: Tkinter Label If-Else Condition
tagged with: tkinter
has answer: http://stackoverflow.com/a/46788905
type: UnansweredQuestion
has body: Trying to make a simple if-else condition like below: from Tkinter import * root = Tk() x = 10 if x = 10: Label(root, text="equal to 10") else: Label(root, text="not equal to 10") pack() root.mainloop() However,i take an error message: File "deneme1.py", line 5 if x = 10: ^ IndentationError: unexpected indent
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80527719
tagged with: if-statement
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/80525802
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
has comment: http://stackoverflow.com/comment/80523831
has answer: http://stackoverflow.com/a/46788888
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722

http://stackoverflow.com/comment/80639877
type: QuestionComment
type: Comment
has text: I recommend reading the answers in that dupe, especially `**kwargs`. Use the dict to index.
score: 0
comment on: http://stackoverflow.com/q/46846149

http://stackoverflow.com/comment/80656683
comment on: http://stackoverflow.com/q/46854408
type: QuestionComment
type: Comment
score: 2
has text: Did you try any R code? Here exactly did you get stuck? R has a `merge()` function too.

http://stackoverflow.com/comment/80541083
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46793923
type: Comment
has text: Any clue why I might me getting this error when i'm trying to set the user with cuser? `File "/usr/local/lib/python2.7/dist-packages/cuser/middleware.py", line 50, in set_user user = User.objects.get(username=user) AttributeError: 'function' object has no attribute 'objects'`

http://stackoverflow.com/comment/80507071
comment on: http://stackoverflow.com/q/46780385
has text: this doesn't make any sense
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80492167
type: Comment
type: QuestionComment
has text: what else would you like the **name** of a variable to be?
score: 0
comment on: http://stackoverflow.com/q/46773220

http://stackoverflow.com/q/46900705
has title: Python Writing LSystem Function
has comment: http://stackoverflow.com/comment/80748594
has comment: http://stackoverflow.com/comment/80748705
score: 0
has body: I want to create a function which is "processString(axiom, rules)" that processes the entire string axiom, and returns the new string Also, I want to create a function "createLSystem(iterations, axiom, rules)" that runs the transformations on the axiom for a number of iterations as specified by iterations And this is what I wrote so far def applyRules(char, rules): for rule_list in (rule.split(':') for rule in rules): char = char.replace(rule_list[0], rule_list[1]) return char def processString(axoism, rules): newstr = "" for ch in rules: newstr = newstr + applyRules(ch) return newstr def createLSystem(iterations, axiom, rules): startString = axiom endString = "" for i in range(iterations): endString = processString(startString) startString = endString return endString axoism, rules and iterations have to be asked to users. But I am not sure if the codes are written right, because it is not working as it should I think.
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80748460
type: Question
has comment: http://stackoverflow.com/comment/80748489

http://stackoverflow.com/comment/80615473
comment on: http://stackoverflow.com/q/46833388
type: QuestionComment
type: Comment
has text: @Bharathshetty - I've elaborated on my question now
score: 0

http://stackoverflow.com/q/46780596
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/46780655
accepted answer: http://stackoverflow.com/a/46780655
tagged with: python
has body: I have n number of csv files in a folder and converted them into pandas dataframes. For all n dataframes I have, I would like to multiply the values of two columns and add values from another column (eg. (['X value'] * ['Slope']) + ['Intercept'])) and create a new column which will have the output Y values. I have tried this way: dfs['Y value'] = [(dfs[n]['X value'] * dfs[n]['Slope']) + dfs[n]['Intercept'] for n in range(len(files))] However it shows [y value] not in index as an error. Thanks for your help. I'm new with Python and new here too, hope I explained my problem well.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46780637
has title: Multiply 2 columns and create a new one in n number of Dataframes in Python
has answer: http://stackoverflow.com/a/46780637
type: Question

http://stackoverflow.com/comment/121745602
type: AnswerComment
score: 0
type: Comment
has text: Darn.. thanks for the quick reply! Also, even if a bit hacky, nice solution wrapped in a function! I had thought about doing something like this for a different reason but didn't want to get in over my head. I'll keep this in mind
comment on: http://stackoverflow.com/a/47039836

http://stackoverflow.com/a/46862594
downvote count: 0
has comment: http://stackoverflow.com/comment/80673431
answers question: http://stackoverflow.com/q/46861946
type: Answer
accepted answer of: http://stackoverflow.com/q/46861946
upvote count: 2
has comment: http://stackoverflow.com/comment/80673735
score: 2
has comment: http://stackoverflow.com/comment/80673465
has body: You have to do that in the View when creating a Note form.py from .models import Note from django.forms import ModelForm class NoteForm(ModelForm): class Meta: model = Note view.py from django.views.generic.edit import CreateView from .form import NoteForm from .models import Note, Notebook class NoteCreateView(CreateView): model=Note form_class=NoteForm def get_form(self, form_class=None): form = super(NoteCreateView, self).get_form(form_class) # Thats the solution: form.fields['notebook'].queryset = Notebook.objects.filter(owner=self.request.user) return form
type: AcceptedAnswer

tensorflow
tags question: http://stackoverflow.com/q/46768863
tags question: http://stackoverflow.com/q/46883276
tags question: http://stackoverflow.com/q/46774412
tags question: http://stackoverflow.com/q/46835380
tags question: http://stackoverflow.com/q/46851689
tags question: http://stackoverflow.com/q/46771194
tags question: http://stackoverflow.com/q/46806127
tags question: http://stackoverflow.com/q/46868866
tags question: http://stackoverflow.com/q/46753508
tags question: http://stackoverflow.com/q/46832162
tags question: http://stackoverflow.com/q/46882307
tags question: http://stackoverflow.com/q/46762932
tags question: http://stackoverflow.com/q/46768626
tags question: http://stackoverflow.com/q/46796566
tags question: http://stackoverflow.com/q/46886770
tags question: http://stackoverflow.com/q/46764464
tags question: http://stackoverflow.com/q/46876213
tags question: http://stackoverflow.com/q/46900643
tags question: http://stackoverflow.com/q/46779659
tags question: http://stackoverflow.com/q/46882503
tags question: http://stackoverflow.com/q/46799261
tags question: http://stackoverflow.com/q/46774997
tags question: http://stackoverflow.com/q/46892880
tags question: http://stackoverflow.com/q/46902947
tags question: http://stackoverflow.com/q/46818376
tags question: http://stackoverflow.com/q/46807597
tags question: http://stackoverflow.com/q/46840539
tags question: http://stackoverflow.com/q/46884338
tags question: http://stackoverflow.com/q/46759151
tags question: http://stackoverflow.com/q/46828476
tags question: http://stackoverflow.com/q/46898519
tags question: http://stackoverflow.com/q/46878312
tags question: http://stackoverflow.com/q/46874209
tags question: http://stackoverflow.com/q/46868852
tags question: http://stackoverflow.com/q/46841896
tags question: http://stackoverflow.com/q/46826108
tags question: http://stackoverflow.com/q/46804666
tags question: http://stackoverflow.com/q/46819088
tags question: http://stackoverflow.com/q/46757986
tags question: http://stackoverflow.com/q/46751800
tags question: http://stackoverflow.com/q/46784295
tags question: http://stackoverflow.com/q/46825257
tags question: http://stackoverflow.com/q/46803186
tags question: http://stackoverflow.com/q/46883327
tags question: http://stackoverflow.com/q/46866208
tags question: http://stackoverflow.com/q/46871302
tags question: http://stackoverflow.com/q/46755616
tags question: http://stackoverflow.com/q/46842398
tags question: http://stackoverflow.com/q/46807125
tags question: http://stackoverflow.com/q/46782575
tags question: http://stackoverflow.com/q/46903154
tags question: http://stackoverflow.com/q/46775242
tags question: http://stackoverflow.com/q/46759009
tags question: http://stackoverflow.com/q/46810996
tags question: http://stackoverflow.com/q/46888616
tag name: tensorflow
tags question: http://stackoverflow.com/q/46779097
tags question: http://stackoverflow.com/q/46810120
tags question: http://stackoverflow.com/q/46832151
tags question: http://stackoverflow.com/q/46857596
tags question: http://stackoverflow.com/q/46791471
tags question: http://stackoverflow.com/q/46903166
tags question: http://stackoverflow.com/q/46894815
tags question: http://stackoverflow.com/q/46846708
tags question: http://stackoverflow.com/q/46759741
tags question: http://stackoverflow.com/q/46892270
tags question: http://stackoverflow.com/q/46856265
tags question: http://stackoverflow.com/q/46870058
tags question: http://stackoverflow.com/q/46777793
tags question: http://stackoverflow.com/q/46799892
tags question: http://stackoverflow.com/q/46856003
tags question: http://stackoverflow.com/q/46808810
tags question: http://stackoverflow.com/q/46836857
tags question: http://stackoverflow.com/q/46894607
tags question: http://stackoverflow.com/q/46786463
tags question: http://stackoverflow.com/q/46896735
tags question: http://stackoverflow.com/q/46902138
tags question: http://stackoverflow.com/q/46807559
tags question: http://stackoverflow.com/q/46814984
tags question: http://stackoverflow.com/q/46878441

http://stackoverflow.com/a/46783609
answers question: http://stackoverflow.com/q/46783101
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: You can do this using win32com: import win32com from win32com.client import gencache, constants, Dispatch # that's the magic part gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 3) app = Dispatch("Word.Application.8") # open a document app.Documents.Open("MyDocument.doc") Now you can do whatever you want with this document. If the line with gencache gives you an error then you will need to create the COM module first by executing: lib\site-packages\win32com\client\makepy.py This will pop-up a Window where you need to select the 'Microsoft Word Object Library'.
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46783101

http://stackoverflow.com/comment/80743787
type: Comment
comment on: http://stackoverflow.com/q/46897380
has text: You need to work on your debugging skills. You can start by reading this: https://stackoverflow.com/help/mcve. The difference comes from the value of the `Delh` variable. Do you see what you're doing differently with the `Delh` variable in the `if` versus the `elif`s?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80597677
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46808796
has text: @Seidhe By the way, I recommend resources such as https://regex101.com when learning regular expressions, I use that particular site all the time when creating my own.
type: AnswerComment

http://stackoverflow.com/q/46840481
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/80629144
has comment: http://stackoverflow.com/comment/80628826
has comment: http://stackoverflow.com/comment/80629168
has comment: http://stackoverflow.com/comment/80629908
has comment: http://stackoverflow.com/comment/80628897
has title: Python module code says path doesn't exist but is readable and statable
type: Question
has comment: http://stackoverflow.com/comment/80629375
has comment: http://stackoverflow.com/comment/80630079
score: 0
has answer: http://stackoverflow.com/a/46840636
has comment: http://stackoverflow.com/comment/80629755
has comment: http://stackoverflow.com/comment/80629591
answer count: 1
has comment: http://stackoverflow.com/comment/80628798
type: UnansweredQuestion
has body: I'm running into a really bizarre problem in a python module and I'm not sure whether or not it's due to some python weirdness or some brokenness in windows or the filesystem being in a weird state. Here's the problem: a module I'm using creates some output that goes into a specified directory, and it creates that directory if it doesn't exist. This works fine if you run it once, running it a second time the module thinks that the directory doesn't exist, tries to create it, then bombs out with a "Cannot create a file when that file already exists" error. So, I went digging. In my main script I can run os.path.exists on the directory and it says it exists just fine. In the module the same exact code returns false however. Also in the module if I do an os.access(path, os.R_OK) it returns true, indicating the path is readable, and if I do an os.stat(path) it returns file info, indicating the path exists. If I run the same code manually in a python shell it all works fine, says the path exists, etc. Here's some code and the outputs: In my main script: print('Path {} exists: {} - readable: {} - stat: {}', filename, os.path.exists(filename), os.access(filename, os.R_OK), os.stat(filename)) Output: File testoutput exists: True - readable: True - stat: nt.stat_result(st_mode=16895, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=0L, st_atime=1508458382L, st_mtime=1508458382L, st_ctime=1508458382L) Inside the module, the same code: File testoutput exists: False - readable: True - stat: nt.stat_result(st_mode=16895, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=0L, st_atime=1508458382L, st_mtime=1508458382L, st_ctime=1508458382L) What the heck is going on here? Is the module code running in some sort of different context with different permissions? Is my filesystem broken in some weird way? Also, I should mention that all of this is being done in an elevated cmd shell so that's not the problem. Solved: It turned out to be some intervening code t…

http://stackoverflow.com/comment/80727916
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46879411
has text: I don't think the problem is "incorrect pseudoinverse", it's probably that pseudoinverse is the wrong tool for the job. Theoretically it should give the least squares solution, but in practice there are dedicated numerical methods to that end. Similar to how we don't actually solve linear systems Ax=b by inverting A and computing A^{-1}*b.

http://stackoverflow.com/a/46839480
has body: Based on Martin Prikryl's answer, below is my solution. def trim_fingerprint(fingerprint): if fingerprint.startswith('ssh-rsa 2048 '): return fingerprint[len('ssh-rsa 2048 '):] return fingerprint def clean_fingerprint(fingerprint): return trim_fingerprint(fingerprint).replace(':', '') class FingerprintKey: def __init__(self, fingerprint): self.fingerprint = clean_fingerprint(fingerprint) def compare(self, other): if callable(getattr(other, "get_fingerprint", None)): return other.get_fingerprint() == self.fingerprint elif clean_fingerprint(other) == self.get_fingerprint(): return True elif md5(other).digest().encode('hex') == self.fingerprint: return True else: return False def __cmp__(self, other): return self.compare(other) def __contains__(self, other): return self.compare(other) def __eq__(self, other): return self.compare(other) def __ne__(self, other): return not self.compare(other) def get_fingerprint(self): return self.fingerprint def get_name(self): return u'ssh-rsa' def asbytes(self): # Note: This returns itself. # That way when comparisons are done to asbytes return value, # this class can handle the comparison. return self usage: options = pysftp.CnOpts() options.hostkeys.clear() options.hostkeys.add('www.example.com', u'ssh-rsa', FingerprintKey("ssh-rsa 2048 d8:4e:f1:f1:f1:f1:f1:f1:21:31:41:14:13:12:11:aa")) with pysftp.Connection( 'www.example.com', username='user', password='password', cnopts=options) as conn: conn.get_d('remote/filedir', 'c:/local/output')
answers question: http://stackoverflow.com/q/46814823
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91883069
score: 3
has comment: http://stackoverflow.com/comment/80633971

http://stackoverflow.com/q/46757648
tagged with: tensorflow
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/80461399
has comment: http://stackoverflow.com/comment/80472042
upvote count: 2
score: 0
favorite count: 0
has answer: http://stackoverflow.com/a/72295757
has body: I'm trying to fit a model to a simple car game that drives a "car" that avoids obstacles. There are some other obstacles that are Ok to collect. The car can only go left or right. The issue I'm having is that the car only moves straight to left or right (and crashes when it hits the border of the screen) no matter what parameters I use for training. I store the x coord of the car, and the obstacle's x and y coordinates in the training data for each frame. First it generates random actions and saves the ones that are above the score_requirement. Then it trains the model against them using tflearn adamoptimizer. Lastly, it displays the game with the trained model for 10 games. What have I done wrong? Below is the code: LR = 1e-3 goal_steps = 400 score_requirement = 100 initial_games = 100 class Game: done = False x = (display_width * 0.5) y = (display_height * 0.8) x_change = 0 x_change_scale = 5 thing_startx = random.randrange(0, display_width-100) thing_starty = -100 thing_speed = 7 thing_width = 100 thing_height = 100 dodged = 0 state = None steps_beyond_done = None def reset(self): self.done = False self.x = (display_width * 0.5) self.y = (display_height * 0.8) self.x_change = 0 self.x_change_scale = 5 self.thing_startx = random.randrange(0, display_width-100) self.thing_starty = -100 self.thing_speed = 7 self.thing_width = 100 self.thing_height = 100 self.dodged = 0 self.steps_beyond_done = None #self.state = np.random.uniform(low=-1, high=1, size=(5,)) self.state = (self.x, self.thing_startx, self.thing_starty) def step(self, action): state = self.state x, thing_startx, thing_starty = state info = "" reward = 0 if action == 0: # right movement x_change = self.x_change_scale elif action == 1: # left movement x_change = -self.x_change_scale else: # stay in position info = "no change" x += x_change thing_starty += self.thing_speed if self.dodged == 30: self.x_change_scale = 6 if self.dodged == 50: self.x_change_scale = 8 if self.dodged == 70: self.x_change_scale = …
has title: python car game A.I. W. tensorflow
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72308175
tagged with: python
tagged with: pygame
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/80467486
downvote count: 2

http://stackoverflow.com/comment/80501993
type: Comment
type: QuestionComment
score: 2
has text: from your code, no code shows how '/campaigns' registered to '/api' blueprint, maybe that's the problem.
comment on: http://stackoverflow.com/q/46762086

http://stackoverflow.com/a/46800349
has comment: http://stackoverflow.com/comment/91324276
has body: Your StringToSign is incorrect. Specifically the HashedCanonicalRequest is incorrect. The Amazon error response will show you the exact StringToSign. This will help you figure out what is wrong. [EDIT - I modified your code to work. Note: I removed the payload calculation and changed it to UNSIGNED-PAYLOAD. There were two minor issues: 1) In the StringToSign the bucket name was not specified in the URL (after the line current_time) 2) You were missing a \n in CanonicalRequest. from collections import OrderedDict from dateutil import parser import datetime import hashlib import hmac import requests key_id = "" secret = "/N6VFTasQCJic3CqL9tj80UGB6Ba1B" region = "" bucket_name = "" service = "s3" def hashb16(message): return hashlib.sha256(message).hexdigest() def HMAC(key, message): return hmac.new(key, message, hashlib.sha256) current_time = datetime.datetime.utcnow() url = "https://s3-us-west-2.amazonaws.com/{}/sometest.txt".format(bucket_name) payload = "Welcome to Amazon S3." headers = { 'date': current_time.strftime("%a, %d %b %Y %H:%m:%S GMT"), 'host': "s3-us-west-2.amazonaws.com", 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD', 'x-amz-date': current_time.strftime('%Y%m%dT%H%M%SZ'), 'x-amz-storage-class': 'REDUCED_REDUNDANCY' } sorted_headers = sorted([k for k in headers]) # step 1 HTTPRequestMethod = "PUT" CanonicalURI = "/{}/sometest.txt".format(bucket_name) CanonicalQueryString = "" CanonicalHeaders = "" for key in sorted_headers: CanonicalHeaders += "{}:{}\n".format(key.lower(), headers[key]) SignedHeaders = "{}".format(";".join(sorted_headers)) HexEncondeHashRequestPayload = hashb16(payload) CanonicalRequest = "{}\n{}\n{}\n{}\n{}\n{}".format(HTTPRequestMethod, CanonicalURI, CanonicalQueryString, CanonicalHeaders, SignedHeaders, 'UNSIGNED-PAYLOAD') # step 2 Algorithm = "AWS4-HMAC-SHA256" RequestDateTime = current_time.strftime('%Y%m%dT%H%M%SZ') CredentialScope = "{}/{}/{}/{}".format(current_time.strftime("%Y%m%d"), region, service, "aws4_request") HashedCanonica…
has comment: http://stackoverflow.com/comment/91325928
has comment: http://stackoverflow.com/comment/91325786
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46799070
has comment: http://stackoverflow.com/comment/91325105
answers question: http://stackoverflow.com/q/46799070
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91356989

http://stackoverflow.com/q/46839394
has body: Code: import tkinter import csv def mainapp(): print ('R') def SigUP(): U = input1.get() P = input2.get() R = input3.get() def P(): myData = U, P, R myFile = open('csvexample3.csv', 'w') with myFile: writer = csv.writer(myFile) writer.writerows(myData) if U == '' or P == '' or R == '': print ('No') else: P() def LogIN(): U = input1.get() P = input2.get() R = input3.get() main = tkinter.Tk() realname = tkinter.Label(main, text='Real Name') input3 = tkinter.Entry(main) Username = tkinter.Label(main, text='Username') input1 = tkinter.Entry(main) Password = tkinter.Label(main, text='Password') input2 = tkinter.Entry(main, show="*") SigUp = tkinter.Button(main, text='Join Us Now', command=SigUP) LogIn = tkinter.Button(main, text='Log In', command=LogIN) input3.grid(column='2', row='1') realname.grid(column='1', row='1') input1.grid(column='2', row='2') Username.grid(column='1', row='2') input2.grid(column='2', row='3') Password.grid(column='1', row='3') SigUp.grid(columnspan='3', row='5') LogIn.grid(columnspan='3', row='4') main.mainloop() In my csv file, I get this: Ben4594,&lt;function SigUP.&lt;locals&gt;.P at 0x101d51950&gt;,Ben I expect that my csv should look like: Ben4594,Password,Ben I'm Using python 3 and tkinter.
upvote count: 1
has answer: http://stackoverflow.com/a/46839613
tagged with: user-interface
accepted answer: http://stackoverflow.com/a/46839613
answer count: 1
has title: Python writes the wrong thing in csv
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80626678
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80626771
type: Question
has comment: http://stackoverflow.com/comment/80626727
downvote count: 0
has comment: http://stackoverflow.com/comment/80627055

http://stackoverflow.com/comment/80605330
type: Comment
has text: @unfolx Assuming you are a little cunning with your code design, such things may not be needed... anyway, I hope this gets you a step in the right direction.
comment on: http://stackoverflow.com/a/46828651
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80704265
has text: Nope, it doesn't work, I tried your solution with an intermediate function (I would like to keep my original function), but I have the following error: `ValueError: too many values to unpack (expected 6)`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46878414

http://stackoverflow.com/q/46856584
downvote count: 0
linked to: http://stackoverflow.com/q/3170211
has answer: http://stackoverflow.com/a/47305036
score: 4
tagged with: unicode
accepted answer: http://stackoverflow.com/a/47318269
linked to: http://stackoverflow.com/q/47020241
favorite count: 0
has comment: http://stackoverflow.com/comment/80665620
possible better answer: http://stackoverflow.com/a/47305036
tagged with: python
tagged with: sublimetext3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80667077
has comment: http://stackoverflow.com/comment/81599546
has body: The problem. I'm using Python 2.7 build on Sublime Text 3 and have an issue with printing out. In some cases I get a pretty confusing output for '\uFFFD' - the 'REPLACEMENT CHARACTER'. For example: print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER' print u'\u0061' # should be 'a' ----------------------------------------------------- [Finished in 0.1s] After inversion of the order: print u'\u0061' print u'\ufffd' ----------------------------------------------------- a � [Finished in 0.1s] So, Sublime can printout the '�' character, but for some reason doesn't do it in the 1st case. And the dependence of the output on the order of statements seems quite strange. The problem with replacement char leads to very unpredictable printout behavior in general. For example, I want to printout decoded bytes with error replacement: cp1251_bytes = '\xe4\xe0' # 'да' in cp1251 print cp1251_bytes.decode('utf-8', errors='replace') ----------------------------------------------------- �� [Finished in 0.1s] Let's replace the bytes: cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251 print cp1251_bytes.decode('utf-8', errors='replace') ----------------------------------------------------- [Finished in 0.1s] And add one more print statement: cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251 print cp1251_bytes.decode('cp1251') print cp1251_bytes.decode('utf-8', errors='replace') ----------------------------------------------------- нет ��� [Finished in 0.1s] Below is the illustration of implementation some other test cases: Summarizing, there are the following patterns in the described printout behavior: it depends on the even/odd number of '\ufffd' chars in print statement it depends on the order of print statements it depends on the specific build run My questions: Why does this happen? How to fix the problem? My Python 2.7 sublime-build file: { "cmd": ["C:\\_Anaconda3\\envs\\python27\\python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "sourc…
type: Question
has answer: http://stackoverflow.com/a/47318269
has title: Python 2.7 build on Sublime Text 3 doesn't print the '\uFFFD' character
tagged with: stdout
upvote count: 4
tagged with: python-2.7
answer count: 2
linked to: http://stackoverflow.com/q/14258500
has comment: http://stackoverflow.com/comment/81606234

http://stackoverflow.com/q/46801285
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I am trying to bar plot the number of each elements in the list: x=[1,1,2] list_pd = pd.DataFrame({'DrawnCards':x}) list_pd.head() list_pd = list_pd.groupby('DrawnCards')['DrawnCards'].count() DrawnCards 1 2 2 1 Name: DrawnCards, dtype: int64 plt.bar(list_pd.DrawnCards) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-117-7f4d4efd9a31&gt; in &lt;module&gt;() ----&gt; 1 plt.bar(list_pd.DrawnCards) C:\Users\mesme\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name) 2968 if name in self._info_axis: 2969 return self[name] -&gt; 2970 return object.__getattribute__(self, name) 2971 2972 def __setattr__(self, name, value): AttributeError: 'Series' object has no attribute 'DrawnCards' So do i need to change the series type to dataframe ? I am bit stuck on this.
upvote count: 0
has answer: http://stackoverflow.com/a/46801310
accepted answer: http://stackoverflow.com/a/46801310
type: Question
has title: Bar plot unique elements in a list
tagged with: matplotlib
tagged with: dataframe
score: -1
tagged with: pandas

http://stackoverflow.com/comment/80752388
score: 0
comment on: http://stackoverflow.com/q/46902801
type: Comment
type: QuestionComment
has text: Thanks for replying. str("Name 1" + x) for x in len(listQ), something like that?

http://stackoverflow.com/a/46769167
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46769097
answers question: http://stackoverflow.com/q/46769097
score: 1
has body: Use isnull with any for check at least one True: a = df[df.isnull().any(axis=1)] For columns with rows: b = df.loc[df.isnull().any(axis=1), df.isnull().any()] Sample: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,np.nan,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,np.nan,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}) print (df) A B C D E F 0 a 4.0 7 1.0 5 a 1 b NaN 8 3.0 3 a 2 c 4.0 9 NaN 6 a 3 d 5.0 4 7.0 9 b 4 e 5.0 2 1.0 2 b 5 f 4.0 3 0.0 4 b a = df[df.isnull().any(1)] print (a) A B C D E F 1 b NaN 8 3.0 3 a 2 c 4.0 9 NaN 6 a b = df.loc[df.isnull().any(axis=1), df.isnull().any()] print (b) B D 1 NaN 3.0 2 4.0 NaN Detail: print (df.isnull()) A B C D E F 0 False False False False False False 1 False True False False False False 2 False False False True False False 3 False False False False False False 4 False False False False False False 5 False False False False False False print (df.isnull().any(axis=1)) 0 False 1 True 2 True 3 False 4 False 5 False dtype: bool print (df.isnull().any()) A False B True C False D True E False F False dtype: bool
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46820543
answers question: http://stackoverflow.com/q/46799450
type: Answer
has body: If I use Canvas instead of Label, i can make a border on three sides by creating lines by the edges. Example code: from tkinter import * root=Tk() canvas=Canvas(height='250',width ='250') canvas.create_line(251,0,251,251,width=2,fill='black') canvas.create_line(3,3,251,3,width=2,fill='black') canvas.create_line(3,251,252,251,width=2,fill='black') canvas.pack() root.mainloop() Which ouputs this There could be more practical ways though.
score: 0

http://stackoverflow.com/comment/80573368
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/46813015
has text: Will this answer help? https://stackoverflow.com/questions/14528958/python-youtube-api-v3-how-to-get-video-id-only

http://stackoverflow.com/q/46798173
tagged with: python
has title: Add 2d array to make 3d in python
has comment: http://stackoverflow.com/comment/80543668
has comment: http://stackoverflow.com/comment/80543271
type: AnsweredQuestion
has body: I have a requirement to read image files( 28*28) from a folder and stack them together to make a single array for analysis. I have the following code: for fname in os.listdir(dirname): im = Image.open(os.path.join(dirname, fname)) imarray = np.array(im) final = np.stack((final,imarray ), axis = 0) am getting the following error: ValueError: all input arrays must have the same shape imarray is (28,28) and i have 60K images in that folder so i want to make a array of size (60000,28,28) Thanks for the help NK
has answer: http://stackoverflow.com/a/46798350
has comment: http://stackoverflow.com/comment/80543741
type: Question
tagged with: numpy
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46798350

http://stackoverflow.com/comment/80467619
score: 0
type: Comment
has text: @user19109 didnt it sort the "PT" tag as you wish ?
comment on: http://stackoverflow.com/a/46761051
type: AnswerComment

http://stackoverflow.com/comment/80742963
comment on: http://stackoverflow.com/q/46897142
score: 0
type: Comment
type: QuestionComment
has text: Is it a bot that you're trying to make? You can try using [pyautogui](https://pyautogui.readthedocs.io/en/latest/), which is fairly simpler.

http://stackoverflow.com/q/46814724
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80578595
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/46815653
favorite count: 0
has body: My code as follows: import numpy as np import matplotlib.dates as mdates stockFile = 'HistoricalQuotes.csv' dates, close = np.loadtxt(stockFile, delimiter=',', unpack=True, usecols=(0,1), \ converters = {0: mdates.strpdate2num('%Y-%m-%d')}) print("Dates = ", dates) and the Traceback: Traceback (most recent call last): File "/Users/zdlzdlxs/Documents/workspace/pynum_practice/part3/simplestats.py", line 7, in &lt;module&gt; converters = {0: mdates.strpdate2num('%Y-%m-%d')}) File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in &lt;listcomp&gt; items = [conv(val) for (conv, val) in zip(converters, vals)] File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/matplotlib/dates.py", line 287, in __call__ return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6])) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 559, in _strptime_time tt = _strptime(data_string, format)[0] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 329, in _strptime raise TypeError(msg.format(index, type(arg))) TypeError: strptime() argument 0 must be str, not &lt;class 'bytes'&gt; I've tried to find solutions in stackoverflow but failed. Could anyone help me to convert datetime correctly? Thanks a lot.
has title: fail to use numpy loadtxt to convert date with python3.6
tagged with: datetime
has comment: http://stackoverflow.com/comment/80577500
has answer: http://stackoverflow.com/a/46815653
tagged with: python

http://stackoverflow.com/a/46822260
downvote count: 0
answers question: http://stackoverflow.com/q/46821911
has comment: http://stackoverflow.com/comment/80594899
type: Answer
has comment: http://stackoverflow.com/comment/80593049
accepted answer of: http://stackoverflow.com/q/46821911
score: 1
has body: As you correctly stated, df.applymap(f) is evaluated before df.where(). I'm fairly certain that df.where() is a quick function and is not the bottleneck here. It's more likely that df.applymap(f) is inefficient, and there's usually a faster way of doing f in a vectorized manner. Having said so, if you do believe this is impossible, and f is itself slow, you could modify f to leave the input unchanged wherever your mask is False. This is most likely going to be really slow though, and you'll definitely prefer trying to vectorize f instead. If you really must do it element-wise, you could use a NumPy array: result = df.values for (i,j) in np.where(mask): result[i,j] = f(result[i,j]) It's critical that you use a NumPy array for this, rather than .iloc or .loc in the dataframe, because indexing a pandas dataframe is slow. You could compare the speed of this with .applymap; for the same operation, I don't think .applymap is substantially faster (if at all) than simply a for loop, because all pandas does is run a for loop of its own in Python (maybe Cython? But even that only saves on the overhead, and not the function itself). This is different from 'proper' vectorization, because vector operations are implemented in C.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/80613811
has text: Appreciated!! Sorry that I have to give the answer to the other one becos he answers first. But this solution is perfect as well
score: 0
comment on: http://stackoverflow.com/a/46832938
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/124012651
type: QuestionComment
comment on: http://stackoverflow.com/q/46816894
has text: @snooze_bear Just wondering if you’ve learnt anything more about this performance difference? I’m experiencing something similar with identical versions of tensorflow giving very different performance on different computers, and any help on debugging this would be much appreciated
score: 0
type: Comment

http://stackoverflow.com/q/46800101
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/80566085
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80547134
has answer: http://stackoverflow.com/a/46835106
favorite count: 0
has body: php curl to python request Trying to make post requests to an API for ordering products. It seems that i can't figure out how to actually send a json-payload with the post-request in a way that the API receives it correctly. The service only provides a php-example: php-example: $params = array(); $params['access_token'] = '123abc'; $params['product_total'] = 2; $params['product_list'] = array( array( 'product_id' =&gt; 111 ), array( 'product_id' =&gt; 222 ), ); And this is my python code so far: import requests payload = { "access_token": "123abc", "product_total": 2, "product_list":[ { "product_id": 111, ... }, { "product_id": 222, ... }] } r = requests.post(url, data=payload, verify=False) r.text &gt; u'{"code":123,"msg":"product_id is empty"}' So something is wrong with the way i send product_list. I also tried: import json r = requests.post(url, data=json.dumps(payload), verify=False) &gt; u'{"code":456,"msg":"access_token is empty"}' r = requests.post(url, json=json.dumps(payload), verify=False) &gt; u'{"code":456,"msg":"access_token is empty"}' But than it can't read the access_token anymore. I'm using python 2.7.9 and requests 2.18.4. Update: Also failing... r = requests.post(url, json=payloal, verify=False) &gt; u'{"code":456,"msg":"access_token is empty"}' Update 2: I looked deeper in the php-example i have from the API documentation and i found this: curl_setopt($this-&gt;__ch, CURLOPT_URL, $apiUrl ); curl_setopt($this-&gt;__ch, CURLOPT_HEADER, 0); curl_setopt($this-&gt;__ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT']); curl_setopt($this-&gt;__ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($this-&gt;__ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this-&gt;__ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($this-&gt;__ch, CURLOPT_POST, 1 ); curl_setopt($this-&gt;__ch, CURLOPT_POSTFIELDS, http_build_query($this-&gt;__params)); Maybe someone can spot something in this lines that I'm missing. Update 3: I can run the php-example without issues and create a orde…
has comment: http://stackoverflow.com/comment/80597721
has comment: http://stackoverflow.com/comment/80575708
score: 1
possible better answer: http://stackoverflow.com/a/46829432
has answer: http://stackoverflow.com/a/46829432
accepted answer: http://stackoverflow.com/a/46835106
has title: post request with nested json
upvote count: 1
tagged with: python
tagged with: php
tagged with: python-requests

http://stackoverflow.com/q/46867932
has comment: http://stackoverflow.com/comment/80683409
answer count: 1
tagged with: unicode
has comment: http://stackoverflow.com/comment/80683348
has comment: http://stackoverflow.com/comment/80683318
score: 0
has comment: http://stackoverflow.com/comment/80683492
tagged with: python
has comment: http://stackoverflow.com/comment/80683265
has answer: http://stackoverflow.com/a/46868426
has comment: http://stackoverflow.com/comment/80683216
accepted answer: http://stackoverflow.com/a/46868426
has body: I am currently running a python script to detect changes in a website's json object that consists of products. When i run it manually on my ubuntu server it works fine (sends tweet) but when it is run with the crontab, it gives me this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) Here is the code. Basically I am comparing different versions of the json file to see if there's a difference. If there's a difference, send a tweet. #!/usr/bin/env python3 import twitter import requests from jsondiff import diff from classes.logger import Logger from classes.proxies import Proxy import webbrowser import time import json log = Logger().log class Cactus: proxy = Proxy() def __init__(self): self.url = 'http://api.bigcartel.com/cactusplantfleamarket/products.json' self.front = 'http://www.cactusplantfleamarket.bigcartel.com' self.api = twitter.Api(consumer_key='xxx', consumer_secret='xxx', access_token_key='xxx', access_token_secret='xxx') def scrape(self): with open('cactus.txt') as oldjson: old = json.load(oldjson); current_proxy = self.proxy.getProxy()[self.proxy.countProxy()] session = requests.session() resp = session.get(self.url, proxies=current_proxy).json() with open('cactus.txt', 'w') as outfile: json.dump(resp, outfile) if diff(resp, old) != {}: if len(resp) == 0: curr_time = time.strftime("%d %b %H:%M:%S", time.gmtime()) self.api.PostUpdate('Website Updated at ' + curr_time ) else: for item in range(len(resp)): try: self.tweet(resp[item]) except Exception as e: print(e) def tweet(self, item): print(item['name']) curr_time = time.strftime("%d %b %H:%M:%S", time.gmtime()) url = self.front + item['url'] shorturl = self.goo_shorten_url(url)['id'] self.api.PostUpdate('CPFM: ' + item['name'] + ' - ' + curr_time + ' ' + shorturl) def goo_shorten_url(self, url): API_KEY = 'xxxx' post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY) payload = {'longUrl': url} headers = {'conten…
has title: Crontab has unicode error when sending tweet
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80683439
tagged with: http://stackoverflow.com/tag/json
tagged with: twitter
type: Question

http://stackoverflow.com/comment/80705243
type: QuestionComment
comment on: http://stackoverflow.com/q/46878961
has text: Yes for example in the terminal when I write 92 it should give me: 1 LBP 50,000 2 LBP 20,000 2 LBP 1,000
score: 0
type: Comment

http://stackoverflow.com/comment/83587207
type: Comment
comment on: http://stackoverflow.com/a/46948205
score: 2
has text: How to convert org.apache.kafka.connect.data.Decimal in java ? Current value looks something like "FGk=" I want to convert this into a readable numeric value.
type: AnswerComment

http://stackoverflow.com/comment/80628050
has text: @Julia apologies, that’s my mistake -- the correct logic will work best if written into a multi-line function. Please see the changes to the answer and let me know if you have questions or problems.
comment on: http://stackoverflow.com/a/46835806
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46836864
linked to: http://stackoverflow.com/q/10458437
has title: How do I delete keys from a dictionary that are shorter than a certain length in python?
answer count: 3
downvote count: 0
tagged with: string-length
tagged with: key
accepted answer: http://stackoverflow.com/a/46836930
favorite count: 0
has comment: http://stackoverflow.com/comment/80621321
has comment: http://stackoverflow.com/comment/80621935
has comment: http://stackoverflow.com/comment/80621699
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80621542
upvote count: 3
has answer: http://stackoverflow.com/a/46836925
has body: I have a dictionary that has keys of different word lengths, for example: d={'longggg':'a', 'short':'b', 'medium':'c', 'shor':'d'} and I want to end up with a dictionary that only has keys that are greater than a certain length. For example, I want to only keep entries that are 6 letters long or more. So I want new_d={'longggg':'a', 'medium':'c'}. I tried new_d=dict(k,v) for k,v in d.items() if len[k]&gt;=6 and new_d={} for k, v in d.items(): if len[k]&gt;=6: new_d.update({k:v}) along with many other variations of that code, but the problem ends up being in taking the length of a key.
has comment: http://stackoverflow.com/comment/80621774
type: Question
has answer: http://stackoverflow.com/a/46836930
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/80621563
possible better answer: http://stackoverflow.com/a/46836925
has answer: http://stackoverflow.com/a/46837063
has comment: http://stackoverflow.com/comment/80621913

http://stackoverflow.com/a/46771174
has comment: http://stackoverflow.com/comment/80487839
has comment: http://stackoverflow.com/comment/80526379
has comment: http://stackoverflow.com/comment/80487907
has comment: http://stackoverflow.com/comment/80529107
has comment: http://stackoverflow.com/comment/80489794
has comment: http://stackoverflow.com/comment/80516009
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80526628
has comment: http://stackoverflow.com/comment/80533965
has comment: http://stackoverflow.com/comment/80534144
has comment: http://stackoverflow.com/comment/80487777
answers question: http://stackoverflow.com/q/46770709
type: Answer
accepted answer of: http://stackoverflow.com/q/46770709
has comment: http://stackoverflow.com/comment/80528621
has body: You can do it using a defaultdict from collections import defaultdict def Main(): yr_dict = defaultdict(int) template = (('ham', '0905'), ('Wind', '852'), ('Wash', '3292'), ('Chitt', '3367')) yr = sql_fin('year') yr = db_query(yr) # Yearly Data Returned Here print("YEAR: {} ".format(yr)) for a, b, c in yr: yr_dict[a + ":" + b] = c yr = tuple((a, b, yr_dict[a + ":" + b]) for a, b in template) mnth = sql_fin('month') mnth = db_query(mnth) # Monthly Data Returned Here print("MONTH: {} ".format(mnth)) wk = sql_fin('week') wk = db_query(wk) # Weekly Data Returned Here print("WEEK: {} ".format(wk)) data = {(name, n): [y, 0, 0] for name, n, y in yr} print("DATA:".format(data)) for name, n, m in mnth: data[name, n][1] = m for name, n, w in wk: data[name, n][2] = w data = tuple(tuple([*k, *v]) for k, v in data.items()) print("DATA: {}".format(data)) return data
has comment: http://stackoverflow.com/comment/80487963
has comment: http://stackoverflow.com/comment/80488019

http://stackoverflow.com/q/46795512
has comment: http://stackoverflow.com/comment/80537783
score: 2
downvote count: 0
has title: using the input file object to read a variable from a file in python
has answer: http://stackoverflow.com/a/46795581
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80537775
has comment: http://stackoverflow.com/comment/80537869
tagged with: python
has comment: http://stackoverflow.com/comment/80537924
favorite count: 0
possible better answer: http://stackoverflow.com/a/53562301
has body: So I'm thinking this is one of those problems where I can't see the forest for the tree. Here is the assignment: Using the file object input, write code that read an integer from a file called rawdata into a variable datum (make sure you assign an integer value to datum). Open the file at the beginning of your code, and close it at the end. okay so first thing: I thought the input function was for assigning data to an object such as a variable, not for reading data from an object. Wouldn't that be read.file_name ? But I gave it shot: infile = open('rawdata','r') datum = int(input.infile()) infile.close() Now first problem... MyProgrammingLab doesn't want to grade it. By that I mean I type in the code, click 'submit' and I get the "Checking" screen. And that's it. At the time of writing this, my latest attempt to submit as been 'checking' for 11 minutes. It's not giving me an error, it's just not... 'checking' I guess. Now at the moment I can't use Python to try the program because it's looking for a while and I'm on a school computer that is write locked, so even if I have the code right (I doubt it), the program will fail to run because it can neither find the file rawdata nor create it. So... what's the deal? Am I reading the instructions wrong or is it telling me to use input in some other way then I'm trying to use it? Or am I supposed to be using a different method?
has answer: http://stackoverflow.com/a/53562301
type: Question
upvote count: 2
answer count: 2
tagged with: file
tagged with: input
has comment: http://stackoverflow.com/comment/80538338
accepted answer: http://stackoverflow.com/a/46795581
has comment: http://stackoverflow.com/comment/80537900
has comment: http://stackoverflow.com/comment/80537886
has comment: http://stackoverflow.com/comment/80537982

http://stackoverflow.com/q/46751725
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/80449365
has body: I was just wandering how to print text while waiting for the users input. Like for example if we were in a chat app, we have an input() so that the user could send messages and print() when receiving messages. It needs to be simultaneous. I tried to use threads but it always stops at a thread. Example: def receive(client): threadName = client.getThreadName() while not client.isStopThread(): time.sleep(1) print('test') while (client.isThereMessage()): print('[' + threadName + ']: ' + client.getMessage()) and for the main program client.startThread(thread.uid) receiveThread = Thread(target = receive(client)) receiveThread.deamon = True receiveThread.start() while True: toSendMessage = input('[' + client.fetchThreadInfo(client.uid)[client.uid].name + ']: ') client.sendMessage(toSendMessage, thread_id=thread.uid, thread_type=thread.type)
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46752118
upvote count: 2
tagged with: multithreading
type: Question
has answer: http://stackoverflow.com/a/46752118
answer count: 1
downvote count: 0
has title: Separate input and print threads?

http://stackoverflow.com/a/46811627
type: Answer
answers question: http://stackoverflow.com/q/46811568
downvote count: 0
has body: What about: SpanVariable = driver.get_element_by_xpath('Put Xpath Here') SpanVariableValue = SpanVariable.text print SpanVariableValue # $399.98 You need to grab the text of the element you are looking at. Place the element you located in a variable, and then you can call selenium functions to it. In this case, .text grabs the text of your span element for you.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80571943

http://stackoverflow.com/comment/80611941
has text: Well no. Somewhere you have some code that takes board, promotion and player and passes them into a template context so that it can display them, no?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46773450

http://stackoverflow.com/q/46846305
favorite count: 0
has answer: http://stackoverflow.com/a/46846372
tagged with: python
score: 1
upvote count: 1
has title: Convert a list of images and labels to np array to train tensorflow
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/46846372
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44451227
answer count: 1
downvote count: 0
has body: I'm using the tutorial about convolutional neural networks. In this function, I use: # Train the model train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": X_train}, y=y_train, batch_size=100, num_epochs=None, shuffle=True) mnist_classifier.train( input_fn=train_input_fn, steps=20000, hooks=[logging_hook]) where type(X_train) list type(y_train) list y_train[0] '0' X_train[0].shape (30, 29, 3) type(X_train[0]) numpy.ndarray len(X_train) 39209 len(y_train) 39209 I get the following error: AttributeError: 'list' object has no attribute 'shape'

http://stackoverflow.com/comment/80730412
type: AnswerComment
comment on: http://stackoverflow.com/a/46891581
score: 0
type: Comment
has text: 0-65535 are port numbers, not IP addresses.

http://stackoverflow.com/a/46776287
type: AcceptedAnswer
has body: You have [(55.0, )] because you have a list of rows (containing a single row in this example), and each row is a tuple (with a single element, since you just selected price). You can do singlerow = rows[0] price, = singlerow However, fetching all rows to select just one seems weird, you should probably re-think your query.
upvote count: 3
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/46776234
answers question: http://stackoverflow.com/q/46776234
score: 2

http://stackoverflow.com/a/46796668
has body: Unfortunately - when you set the batch_size to 50 when you have only 5 examples will make your generator to return only 5 examples in each batch (despite the batch_size). So it will not extend your batch to 50.
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46789414
upvote count: 1

http://stackoverflow.com/comment/80521553
has text: Edited to include the new info given in the OP
comment on: http://stackoverflow.com/a/46773477
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46817450
tagged with: django
tagged with: unit-testing
type: Question
tagged with: testing
score: 3
upvote count: 3
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46896775
downvote count: 0
accepted answer: http://stackoverflow.com/a/46896775
has title: Django Formset Missing Management Form Data
has body: I'm attempting to write unit tests for a formset, but I'm getting the following error when trying to instantiate it. error: Traceback (most recent call last): File "/home/jwelborn/Documents/projects/Bingo/bingo/cards/tests/test_forms.py", line 218, in test_formset_accepts_valid_data self.assertTrue(formset.is_valid()) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 321, in is_valid self.errors File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 295, in errors self.full_clean() File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 343, in full_clean for i in range(0, self.total_form_count()): File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 116, in total_form_count return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 98, in management_form code='missing_management_form', django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] This error says I'm missing ManagmentForm data, but I include it in the dictionary I'm passing to my form. I've checked different spellings and varying the min and max numbers, to no avail. forms.py: class BingoSquareForm(ModelForm): class Meta: model = BingoCardSquare exclude = ('created_date',) BingoSquareFormset = inlineformset_factory( BingoCard, BingoCardSquare, form=BingoSquareForm, min_num=24, validate_min=True, max_num=24, validate_max=True ) tests.py class BingoSquareFormsetTests(TestCase): def setUp(self): self.…

http://stackoverflow.com/comment/80444973
comment on: http://stackoverflow.com/q/46749023
score: 0
has text: To be considered an importable module (in Python 2), the directory must contain an `__init__.py` file. Do the `honeywordHasher` directories contain these files?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80501555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46773019
has text: Oh thanks.I'll try that and update here.Such a stupid mistake,I didn't notice. edit:-It doesn't work.

http://stackoverflow.com/q/46795627
favorite count: 0
has comment: http://stackoverflow.com/comment/80538002
has comment: http://stackoverflow.com/comment/80537882
has title: python return from function
type: UnansweredQuestion
tagged with: cpython
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/80537964
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/46796019
has comment: http://stackoverflow.com/comment/80538087
tagged with: function
upvote count: 0
has body: Is it possible to return from a function and continue executing code from just under the function. I know that may sound vague but here is an example: def sayhi(): print("hi") continue_function() #makes this function continue below in stead of return #the code continues here with execution and will print hey print("hey") sayhi() when executing this the code should do this: it prints "hey" it calls the sayhi() function it prints "hi" it calls a function to make it continue after the function (in theory similar behavour could be achieve by using decorators) it prints "hey" again it calls sayhi() again etc i am fully aware of the fact that similar behaviour can be achieved by just using for loops but for the project i am working on this functionality is required and not achievable by using looping. some solutions i have thought of (but i have no clue how i could execute them) are: somehow clearing the stack python uses to return from one function to another changing return values changing python itself (just to make clear: it would solve the problem but it is something i do not want to do beacuse the project must be usable on non-altered versions of python using some c extension to change python's behaviour from within python itself
has comment: http://stackoverflow.com/comment/80537909
answer count: 1
has comment: http://stackoverflow.com/comment/80538026

http://stackoverflow.com/q/46896512
has answer: http://stackoverflow.com/a/46896537
has title: If elif else does not detect correct string input Python
has body: Exit=("") Exit=str(input("Do you require another service? ")) if Exit=="Yes" or "Yeah" or "Y" or "yes": print("Okay") elif Exit=="No" or "Nah" or "N" or "no": print("Terminating Program") else: print("Terminating Program") When Exit=No, the Yes path is chosen. Why?
tagged with: python
duplicate of: http://stackoverflow.com/q/20002503
linked to: http://stackoverflow.com/q/15112125
type: Question
has comment: http://stackoverflow.com/comment/80740147
duplicate of: http://stackoverflow.com/q/15112125
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/46896549
has answer: http://stackoverflow.com/a/46896555
type: UnansweredQuestion

http://stackoverflow.com/a/46815315
has body: You don't need the for-loop, because map already iterates over the splitted elements: AC = [] for x in AC_temp: if "," in x: val= x.split(",") AC.append(list(map(int, val)) else: AC.append([int(x)]) #print output# for i in AC: print(i) or in a more compact form: AC = [list(map(int, x.split(","))) for x in AC_temp] #print output# for i in AC: print(i)
upvote count: 1
has comment: http://stackoverflow.com/comment/80578019
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/80578220
score: 1
has comment: http://stackoverflow.com/comment/80578274
has comment: http://stackoverflow.com/comment/80578193
answers question: http://stackoverflow.com/q/46815290

http://stackoverflow.com/q/46904273
possible better answer: http://stackoverflow.com/a/46906443
has title: SQLAlchemy delete all items and not just the first
has answer: http://stackoverflow.com/a/46904371
accepted answer: http://stackoverflow.com/a/46904371
has comment: http://stackoverflow.com/comment/80755965
tagged with: python-2.7
upvote count: 3
has comment: http://stackoverflow.com/comment/80756525
favorite count: 0
has comment: http://stackoverflow.com/comment/80755380
has answer: http://stackoverflow.com/a/46906443
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/7892618
has body: I am trying to delete some datarecords from my db. I made cascade to also delete everything related to the datarecord. My problem is now that what if I have more than one datarecord with the same name attribute and I want to delete them all. So for example I got 3 datarecords and two have an attribute name = Max and the last one has the attribute name = Peter. How can I now delete both Max's? This is the code I got so far: def delete_anw(engine): Session = sessionmaker(bind=engine) session = Session() f = session.query(Anwendung).filter_by(name="Max").first() session.delete(f) session.commit() This code only deletes the first query that it finds. I know it's because of the first() but is there a method like all() to delete all datarecords that have the name Max?
tagged with: sqlalchemy
type: Question
answer count: 2

http://stackoverflow.com/comment/80701981
type: Comment
type: QuestionComment
has text: I don't think that will quite work; my dataframe is -much- larger than what I posted, so just grabbing one row doesn't work. There are several potential values in each column, so tons of different combinations, and the values may differ depending on the dataset I load. I'm looking for something that can flexibly take into consideration all of the different permutations.
comment on: http://stackoverflow.com/q/46877202
score: 0

http://stackoverflow.com/comment/80750100
type: AnswerComment
type: Comment
has text: If you want the element as well as the rank, use `enumerate` instead: `sorted(enumerate([102, 97, 116, 101], 1), key=lambda x: x[1], reverse=True)`
comment on: http://stackoverflow.com/a/46901637
score: 1

http://stackoverflow.com/comment/80539635
score: 0
type: AnswerComment
has text: Also, is there a way to delete this question? I'm realizing that how far I went to change things for IP reasons essentially rendered it worse than useless. I tried the "delete" button, but it won't let me, because it's been answered. Is there a way that the community can vote on its deletion because of how badly I butchered it?
type: Comment
comment on: http://stackoverflow.com/a/46796252

http://stackoverflow.com/comment/80734414
comment on: http://stackoverflow.com/a/46892275
type: AnswerComment
has text: Actually sorry I just saw you can put import statements in the __init__ file, see: http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html
type: Comment
score: 1

http://stackoverflow.com/comment/80497097
score: 0
type: Comment
type: QuestionComment
has text: I tried xlml and had a similar problem to this: import requests url = raw_input("Enter a website to extract the URL's from: ") r = requests.get("http://" +url) data = r.text soup = BeautifulSoup(data) I cannot get the r.text as in the example because to get: url = raw_input("Enter a website to extract the URL's from: ") r = requests.get("http://" +url) i need the url and i can only get to the webpage by click on a link. If reloading the webpage a 404 error occurs--file or directory not found. I need to get the data from my open webpage
comment on: http://stackoverflow.com/q/46775666

http://stackoverflow.com/comment/80529517
type: Comment
comment on: http://stackoverflow.com/q/46791254
score: 0
type: QuestionComment
has text: Retrieved the data from DB2.[Please find here](https://onedrive.live.com/?authkey=%21AFTP4sSquEb7nuI&id=FF431A41D367C7D9%21112&cid=FF431A41D367C7D9) the sample coded data

http://stackoverflow.com/comment/80608413
type: QuestionComment
has text: @ Bryan Oakley yes
comment on: http://stackoverflow.com/q/46829450
score: 0
type: Comment

http://stackoverflow.com/q/46905542
has comment: http://stackoverflow.com/comment/80757943
upvote count: 0
has body: #snakes and ladder from tkinter import * #pygame is the module that has collections of functions that is used to create a window import everything from tkinter import time class window(Frame): #Frame comes from tkinter is what you think as a window def __init__(self, master = None):#The master widget defines the settings upon initialisation Frame.__init__(self, master) #This is called the frame class that has been built in python self.master = master def __init__window(self): #creation of the init window self.master.title("Reagan Kambayi") #It changes the title of the title of our widget self.pack(fill=BOTH, expand=1)#The pack function will pack this in our frame #placing the button stop = Button(self, master, message= "Stop") #intialising the button that will start the stopwatch stop.place(x=0, y=0) screen = Tk() #It must be written with capitalised T because there will be an error and it holds the components of the tkinter module screen.geometry("700x500") app = window(screen) #The app variable is assigned to the window creation which has the tkinter module screen.mainloop()
has comment: http://stackoverflow.com/comment/80758153
answer count: 1
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/18924422
has title: Why is my tkinter button not displaying, have I installed everything in the module if not how can I install it?
downvote count: 3
has answer: http://stackoverflow.com/a/46905965
type: Question

http://stackoverflow.com/q/46901475
has comment: http://stackoverflow.com/comment/80770491
has body: Im trying to replicate a chart the was done in AmCharts but so far Im confused in the way to make the legend be outside and at the bottom of the plot right now im using this django view to render the plot def my_view(request) import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas colors = ["#FF9800", "#00E676", "#03A9F4", "#1A237E", "#AD1457", "#F44336", "#1DE9B6", "#01579B", "#CFD8DC", "#90A4AE", "#263238", "#B71C1C", "#FFEB3B"] data=('serv1','Aplicaiones','serv3','serv4','servi5','serv1','serv2','serv3','serv4','servi5',) datos=[99.3,99,23,100,99.3,99,23,100,99.3,99] figure=plt.Figure() pos=np.arange(len(datos)) ax = figure.add_subplot(111) b=ax.bar(pos, datos,color=colors) ax.legend(b,data,loc='upper center', bbox_to_anchor=(0,-.05, 1,0), ncol=5,mode="expand") ax.axis('off') # response = HttpResponse(content_type='image/png') figure.bbox_inches='tight' canvas = FigureCanvas(figure) canvas.print_png(response) return response the parameter bbox_to_anchor looks like the way to go, but chart has a limit and the label ends too close to the bars, my goal is to put the label (1 for each bar) leave space for axis description what I want https://d26dzxoao6i3hh.cloudfront.net/items/2U113d3m0O3Z0o053L3F/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.45.00.png?v=16e23ee7 right now this is what I got https://d26dzxoao6i3hh.cloudfront.net/items/0l0v2P2N3h1M15022V43/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.47.05.png?v=a36b97c9
answer count: 0
linked to: http://stackoverflow.com/q/4700614
has comment: http://stackoverflow.com/comment/80750133
duplicate of: http://stackoverflow.com/q/4700614
type: Question
has title: matplotlib legend at the bottom of the plot
tagged with: python
score: 0
tagged with: django
tagged with: matplotlib
type: UnansweredQuestion

http://stackoverflow.com/comment/80507220
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46778843
has text: Please update your answer to be consistent with the question, or if it ends up not being useful, consider deleting.
type: Comment

http://stackoverflow.com/a/46757685
answers question: http://stackoverflow.com/q/46757531
has body: When you are opening the file and reading in the values, they are of type (or class) str, so you need to convert them to either int or float to do a mathematical check. &gt;&gt;&gt; prompt = 'What...is the airspeed velocity of an unladen swallow?\n' &gt;&gt;&gt; speed = input(prompt) What...is the airspeed velocity of an unladen swallow? 17 &gt;&gt;&gt; type(speed) &lt;class str&gt; &gt;&gt;&gt; speed = int(speed) 17 &gt;&gt;&gt; int(speed) + 5 22
score: 0
type: Answer

http://stackoverflow.com/comment/80508045
comment on: http://stackoverflow.com/a/46780742
has text: thanks this is the sort of thing I'm looking for. If you have any good reference links or gists on how this works I'd appreciate it; I'm trying to get a better understanding of how metaclass works under the hood and its applicable to my current project (ex. constructing a standardized interface / protocol class with OS specific code inserted during instantiation)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80588224
comment on: http://stackoverflow.com/q/46820292
score: 0
type: Comment
type: QuestionComment
has text: I guess not prior to adding that I wasn't able to get any of the contents of my text files to print if I called them within my function. Does it not return the contents of the variable?

http://stackoverflow.com/a/46835761
has body: I think the regex r'(.)\1' should do what you're looking for, where \1 is a backreference.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46835610
downvote count: 0
type: Answer

http://stackoverflow.com/a/46750841
has comment: http://stackoverflow.com/comment/80447784
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80447736
type: Answer
answers question: http://stackoverflow.com/q/46750737
downvote count: 0
has body: Everything is doable. Here is the simplified solution on how to hack a class. Even if the module was imported, and the class was used to create object — this hack will affect all of the existing objects immediately: class KLS(object): @property def x(self): print('OLD') return 100 def new_function(self): print('NEW') return 200 obj = KLS() print(obj.x) # OLD + 100 KLS.x = property(new_function) # &lt;-- HACK! print(obj.x) # NEW + 200 The solution works both for py2 &amp; py3. However, make sure there are no setters/deleters for that property in the original class (i.e., is it settable? or just read-only?) For the setters, you will have to call property(getter_func, setter_func).

http://stackoverflow.com/a/46766599
accepted answer of: http://stackoverflow.com/q/46766530
has body: You can do this with strings (and lists) using slicing: string = "hello world!" splitat = 4 left, right = string[:splitat], string[splitat:] will result in: >>> left hell >>> right o world!
answers question: http://stackoverflow.com/q/46766530
score: 37
type: AcceptedAnswer
upvote count: 37
type: Answer
downvote count: 0

http://stackoverflow.com/a/46819092
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80585870
has body: You're executing the following two lines item = TextParser() item.get_text() When you initialize TextParser, self.storage is equal to None. When you execute the function get_text() it's still equal to None. So that's why you get that error. However, if you change it to the following. self.storage should get populated with a string rather than being none. item = TextParser() item.fetch_url() item.get_text() If you want to call the function get_text without calling fetch_url you can do it this way. def get_text(self): self.fetch_url() root = fromstring(self.storage) for post in root.cssselect('a'): print(post.text)
type: Answer
has comment: http://stackoverflow.com/comment/80598597
accepted answer of: http://stackoverflow.com/q/46818622
downvote count: 0
answers question: http://stackoverflow.com/q/46818622
has comment: http://stackoverflow.com/comment/80602243
score: 1
upvote count: 1

http://stackoverflow.com/q/46855867
tagged with: python
has comment: http://stackoverflow.com/comment/80659337
type: UnansweredQuestion
tagged with: excel
has title: Python: Read text file with column headers in rows into new CSV/Excel
type: Question
has comment: http://stackoverflow.com/comment/80659467
has comment: http://stackoverflow.com/comment/80659537
has comment: http://stackoverflow.com/comment/80660428
has comment: http://stackoverflow.com/comment/80659753
score: 0
has answer: http://stackoverflow.com/a/46856623
has comment: http://stackoverflow.com/comment/80659828
answer count: 1
has comment: http://stackoverflow.com/comment/80659662
has body: I have a text file that i want to output into a new .csv file. The column headings are in-line to the data and I cannot figure out how to process the file. I am a python newbie. The input file format is: {"column 1 name":"column 1 value", "column 2 name":"column 2 value", "column 3 name":"column 3 value", "column 4 name":"column 4 value", "column 5 name":"column 5 value"} The output file format i want is: column headers in line 1 comma separated values in lines 2 and beyond There are also times where a value may be blank so i need to account for that so the values don't shift to the wrong column header. Thanks in advance!
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/80711181
type: QuestionComment
score: 1
has text: To your question: you can create a new settings file without that app and use it as described at https://docs.djangoproject.com/en/1.11/topics/settings/
comment on: http://stackoverflow.com/q/46881726
type: Comment

http://stackoverflow.com/comment/80745113
has text: Have you run ./manage.py makemigrations and ./manage.py migrate since making your latest model changes? Do either of those commands create/apply any new migrations?
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/46898601

http://stackoverflow.com/q/46781050
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: macos-high-sierra
type: Question
has title: Unable to setup virtualenv with '--always-copy' flag due to Errno 1
has body: I am trying to run this command $ virtualenv --always-copy venv Then I got all these errors: shutil.Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Drag.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Drag.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Drag.so'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Ctl.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Ctl.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Ctl.so'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/imageop.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/imageop.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/imageop.so'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Scrap.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Scrap.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_Scrap.so'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_testcapi.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_testcapi.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/_testcapi.so'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/unicodedata.so', '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/unicodedata.so', "[Errno 1] Operation not permitted: '/Users/antkong/dev/zeetings/venv/lib/python2.7/lib-dynload/unicodedata.so'"), I checked the permission of the source file. It is all readable $ ls -l '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Drag.so' -rwxr-xr-x 1 root wheel 55936 3 Oc…
tagged with: python-2.7
answer count: 1
downvote count: 0
tagged with: macos
favorite count: 0
has answer: http://stackoverflow.com/a/46787331
accepted answer: http://stackoverflow.com/a/46787331

http://stackoverflow.com/a/46835183
answers question: http://stackoverflow.com/q/46835067
type: Answer
upvote count: 1
has body: You could define a dictionary (preferably inside your module): buttons = { "TypeA": TypeA, "TypeB": TypeB, … } and then call the entry: ButtonLib.buttons[x](**kwargs) If your button classes have a function returning their name, you could also define the dictionary like this: buttons = { button_type.name: button_type for button_type in [TypeA, TypeB, …] } More advanced: Python stores the name of a class in .__name__. Even more advanced: You could get the elements of the module with getattr(ButtonLib, name). But this might impair readability.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80633138
has comment: http://stackoverflow.com/comment/80624748

http://stackoverflow.com/q/46835531
has comment: http://stackoverflow.com/comment/80620116
type: UnansweredQuestion
has title: Folder containing subfolders, that contain multiple files (.xlsm, .pdf, .txt). How to rename .pdf files to subfolders' name?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46836377
score: 1
has comment: http://stackoverflow.com/comment/80652582
type: Question
has body: This could be done with python, but I think I am missing a way to loop for all directories. Here is the code I am using: import os def renameInDir(directory): for filename in os.listdir(directory): if filename.endswith(".pdf"): path = os.path.realpath(filename) parents = path.split('/') //make an array of all the dirs in the path. 0 will be the original basefilename newFilename=os.path.dirname(filename)+directory +parents[-1:][0] //reorganize data into format you want os.rename(filename, newFilename)//rename the file
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/46856915
tagged with: tensorflow
type: Question
score: 3
has comment: http://stackoverflow.com/comment/80676668
has comment: http://stackoverflow.com/comment/80666081
upvote count: 3
favorite count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/80676382
has body: Let's suppose that I have a matrix like this: Where p, z are some variables to be optimized. This matrix is supposed to to take part in some heavy algebraic shenanigans and in the end I want only p and z to get their new values. That's it, all other elements in the matrix/tensor should remain constant. Ideally I would like to do something like this: p = tf.get_variable('p', ()) z = tf.get_variable('z', ()) m = tf.constant(matrix) m[0,1] = p m[1,1] = 2 * p m[1,2] = z m[2,1] = z - p Unfortunately, such a point-wise operation seems to be impossible in a Tensorflow. Is there a workaround for this?
has title: Optimizing only certain elements of a tensor in Tensorflow
tagged with: python
linked to: http://stackoverflow.com/q/35298326
has comment: http://stackoverflow.com/comment/80676403
has comment: http://stackoverflow.com/comment/80676607
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80676569

http://stackoverflow.com/a/46801930
has comment: http://stackoverflow.com/comment/101596744
score: 0
has body: Sure, Python can do this: just raise NotImplementedError in the method definition in the intermediate class. class BaseClass : def method(...) : ... actually do something ... #end method #end BaseClass class Subclass(BaseClass) : def method(...) : raise NotImplementedError #end method ... #end Subclass class SubSubclass(Subclass) : def method(...) : ... actually do something else ... #end method #end SubSubclass Does that sound like what you’re looking for?
type: Answer
answers question: http://stackoverflow.com/q/46801226

http://stackoverflow.com/comment/106790085
has text: Do all the regressors have "Regress" in the name?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46852251

http://stackoverflow.com/comment/80499641
has text: list comprehension is almost always faster than an explicit for loop.
comment on: http://stackoverflow.com/a/46777043
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46839927
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/67363026
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/46840003
type: Question
has answer: http://stackoverflow.com/a/46840506
has answer: http://stackoverflow.com/a/46840011
has comment: http://stackoverflow.com/comment/80627689
tagged with: sum
has comment: http://stackoverflow.com/comment/80627724
score: 0
has body: I'm being asked to add the first 100 terms f the sequence (1 + 1/2 + 1/4 + 1/8 ...etc) what i ve been trying is something Iike for x in range(101): n = ((1)/(2**x)) sum(n) gives me an error, guess you cant put ranges to a power print(n) will give me a list of all the values, but i need them summed together anyone able to give me a hand? using qtconsole if that's of any relevance, i'm quite new to this if you haven't already guessed
has comment: http://stackoverflow.com/comment/80627764
has comment: http://stackoverflow.com/comment/80627783
has title: Finding the sum of a geometric progression
tagged with: sequence

http://stackoverflow.com/comment/80490422
has text: `df1 = df1.drop_duplicates('Month')` with previous solution does not work?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46772401

http://stackoverflow.com/comment/80461993
comment on: http://stackoverflow.com/q/46758066
has text: Please, paste the response of the `/getEmployees` call. I mean, one example of the code you receive when you make that call. On the other hand, it doesn't look like you set a dropdown for employees, it says `type="text"` (looks like a regular text input).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46767186
accepted answer: http://stackoverflow.com/a/46768095
tagged with: openpyxl
tagged with: django
has title: Convert datetime to local time from Django Query to Openpyxl
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/46768095
tagged with: datetime
tagged with: python
has body: Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl. Right now, I simply assign the attribute of the query to the cell. query = SomeModel.objects.latest() date_recorded = query.date_recorded In templates, date_recorded is already converted to local time. No problem there. ws.cell(row=rows, column=cols).value = date_recorded The above code results to UTC. Please help me convert it to local time. Thank you.
tagged with: timezone
score: 0

http://stackoverflow.com/comment/80733014
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46887903
has text: Thanks for including 2 working versions. I'll look into why it's not working for me.
score: 0

http://stackoverflow.com/q/46784184
tagged with: pattern-recognition
type: UnansweredQuestion
tagged with: machine-learning
downvote count: 1
type: Question
tagged with: time-series
score: 3
has answer: http://stackoverflow.com/a/46784242
tagged with: recurrent-neural-network
upvote count: 4
linked to: http://stackoverflow.com/q/11752727
answer count: 1
has title: Pattern recognition in time series using LSTM(python)
favorite count: 0
tagged with: python
has body: My application scenario is similar to the previous one Pattern recognition in time series By processing a time series dataset, I Would like to detect patterns that look similar to this: Using a sample time series as an example, I would like to be able to detect the patterns as marked here: But I want to do it with python and LSTM. I have read some resouces about the RNN time series and word classification.I know how RNN predicts results in time series, but I'm puzzled how to find a pattern in time series. I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. Since I am not a native English speaker, if there is anything I didn't describe clearly, please ask.Thank you!

http://stackoverflow.com/a/46770814
answers question: http://stackoverflow.com/q/46755012
has body: Updated I suspect that you have also installed python3-memcached (now deprecated, see README) in which case that might have overwritten your python-memcached installation (which now supports Python 2 &amp; 3). If so, you need to remove both python3-memcached andpython-memcached then reinstall the latter, version >= 1.58. You need to upgrade python-memcache to the latest version, currently 1.58. This package interacts with your memcached server to extract the stats collected by it. Earlier versions of the package did not decode the incoming stats data (in particular the keys) into Python 3 str type (i.e. unicode), and just passed on a bytes string to the memcached_status prettyname filter - which assumes a str object.
accepted answer of: http://stackoverflow.com/q/46755012
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80506290
has comment: http://stackoverflow.com/comment/80519456
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/80504912
has comment: http://stackoverflow.com/comment/80592546
downvote count: 0

http://stackoverflow.com/comment/80656950
type: Comment
comment on: http://stackoverflow.com/a/46854602
has text: Sure. why not ;)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80558867
score: 0
has text: @Apolo Radomer I'm sorry for the inconvenience. Since ``TypeError: unhashable type: 'dict'`` disappeared, one error was removed. For the next error, I confirmed some patterns. I updated my answer. Please confirm it.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46800273

http://stackoverflow.com/a/46856365
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/46856221
upvote count: 2
answers question: http://stackoverflow.com/q/46856221
has body: I can't really think of a great way off the top of my head. There might be a better way using one of Numpy's various indexing tricks. The simplest I can think of is to manually make slice() objects. The start:end syntax actually translates directly to slice(start, end) objects. So you could write: arr[slice(*z_range), slice(*y_range), slice(*x_range)] so that's a least a little nicer but I don't think you really gain much in terms of clarity.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80805171
type: Comment
comment on: http://stackoverflow.com/a/46887082
has text: It does the same thing. I prefer subclassing Thread - but it does not make any difference in your case. At least the problem is solved now.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80757195
score: 0
has text: @dsgdfg Secure != Encrypted access to the console
comment on: http://stackoverflow.com/q/46905201
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80595064
comment on: http://stackoverflow.com/q/46822068
has text: No, they both are just supposed to get updated based on what I input into `SearchForm`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80555501
type: Comment
type: QuestionComment
has text: You can use `setattr()` as the mirror to `getattr()` to set attributes dynamically.
score: 0
comment on: http://stackoverflow.com/q/46804275

http://stackoverflow.com/q/46792993
tagged with: python
has title: Best practice: local variables in a function (explicit vs implicit)
accepted answer: http://stackoverflow.com/a/46793163
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80533348
has comment: http://stackoverflow.com/comment/80547397
score: 1
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/80533314
tagged with: pep8
has comment: http://stackoverflow.com/comment/80534264
has answer: http://stackoverflow.com/a/46793134
has answer: http://stackoverflow.com/a/46793180
has body: Is there a recommended style when it comes to the use local variables inside a function? Should we use more explicit local variables as in style 1 or not as in style 2? Two possible styles: Style 1: import re def doc_to_lower(url_raw): url_lower = [word.lower() for word in url_raw] return url_lower def process_data(url_raw): url_split = re.split('//|/|-', url_raw) url_lower = doc_to_lower(url_split) return url_lower url = 'http://www.bbc.com/sport/football/41653935' tokens = process_data(url) for token in tokens: print(token) Style 2: import re def doc_to_lower(url_raw): return [word.lower() for word in url_raw] def process_data(url_raw): return doc_to_lower(re.split('//|/|-', url_raw)) url = 'http://www.bbc.com/sport/football/41653935' tokens = process_data(url) for token in tokens: print(token)
has answer: http://stackoverflow.com/a/46793163
answer count: 3
has comment: http://stackoverflow.com/comment/80535384
possible better answer: http://stackoverflow.com/a/46793134
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80546096
downvote count: 2

http://stackoverflow.com/comment/80471024
score: 0
has text: Awesome! Thanks so much for your help. I've got it working now.
comment on: http://stackoverflow.com/q/46762791
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46890184
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80727688
type: Question
has comment: http://stackoverflow.com/comment/80728610
has body: Suppose I have two classes. The simple Square class: class Square: def __init__(self, side): self.side = side And the slightly more complex MyClass class: class MyClass: def __init__(self, square=None): if square is None: self.square = Square() else: self.square = square self.rounded_side = round(self.square.side) I instantiate a MyClass object like so: myObj = MyClass() In this situation, how can one achieve the following behavior? Changing myObj.rounded_side to X, automatically changes myObj.square.side also to X. Changing myObj.square.side to X, automatically changes myObj.rounded_side to round(X). If possible, in a way that doesn't require any modifications to the Square class (this is a simplified version of the problem I'm currently facing; in the original version, I don't have access to the code for Square). What I tried so far: My first attempt was to transform rounded_side into a property. That makes it possible to obtain behavior 1. However, I fail to see how I can transform square also into a property, in a way that makes it possible to obtain behavior 2. I also thought about making MyClass inherit from Square, so that both attributes are in the same depth, but then I'd lose some the desired structure of my class (I rather have the user access myObj.square.side, than myObj.side) If someone is interested, the actual problem I'm facing: I'm writing a game in pygame, and my Player class has an attribute for its position, which is an array with two floats (2D position). This is used for determining where the player is, and for deciding how to update it's position in the next update step of the game's physics. However, I also want to have a Rect attribute in the Player class (which holds the information about a rectangle around the player's image), to be used when displaying the player in the screen, and when inferring collisions. The Rect class uses integers to store the position of the rectangle (pixel coordinates). So as to be able to store the position inf…
score: 0
has comment: http://stackoverflow.com/comment/80727647
answer count: 1
favorite count: 0
has title: Getter/setter but for nested attributes?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80728514
has comment: http://stackoverflow.com/comment/80728148
tagged with: python
tagged with: properties
has answer: http://stackoverflow.com/a/46890330

http://stackoverflow.com/a/67363026
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/46839927
has body: Hmm, there is actually a formula for sum of geometric series: In your question, a is 1, r is 0.5 and n is 100 So we can do like a = 1 r = 0.5 n = 100 print(a * (1 - r ** n) / (1 - r))
score: 3
downvote count: 0

http://stackoverflow.com/q/46895878
has answer: http://stackoverflow.com/a/46916676
accepted answer: http://stackoverflow.com/a/46916676
has body: I am new to snmp. I am using pysnmp to program a snmp agent, I compiled the MIB with mibdump.py and got it running using this examples: http://www.nealc.com/blog/blog/2013/02/23/writing-an-snmp-agent-with-a-custom-mib-using-pysnmp/ http://www.cloud-rocket.com/2013/08/writing-custom-mib-for-pysnmp-agent/ and also some of the documentation from de pysnmp webpage. I can do a get, a set and a walk on my agent, with variables that do not belong to a table. I cant do a walk on the table, I can do a get on half the objects, and I cant do a set on any of them. This is what I get when I try a get or a set on some of the objects. I thought it was something related to the way I was querying the table, but there is no consistency between one object and another, even if they seem the exact same. pysnmp$ snmpset -v2c -c private localhost 1.3.6.1.4.1.1206.4.2.3.3.2.1.3.0 i 1 Error in packet. Reason: notWritable (That object does not support modification) Failed object: iso.3.6.1.4.1.1206.4.2.3.3.2.1.3.0 This is an object defind by mibdump.py like fontName = MibTableColumn((1, 3, 6, 1, 4, 1, 1206, 4, 2, 3, 3, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: fontName.setStatus('mandatory') Now this is a get on another column pysnmp$ snmpget -v2c -c public localhost 1.3.6.1.4.1.1206.4.2.3.3.2.1.5.0 iso.3.6.1.4.1.1206.4.2.3.3.2.1.5.0 = No Such Instance currently exists at this OID defined like this fontCharSpacing = MibTableColumn((1, 3, 6, 1, 4, 1, 1206, 4, 2, 3, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: fontCharSpacing.setStatus('mandatory') This is the debugger feedback for a set on the same object to an i 4 which should be in range ValueConstraintError: ConstraintsIntersection(ValueRangeConstraint(-2147483648, 2147483647), ValueRangeConstraint(1, 255)) failed at: ValueConstraintError('ValueRangeConstraint(1, 255) failed a…
tagged with: python
type: AnsweredQuestion
type: Question
answer count: 1
has title: pysnmp agent table implementation
tagged with: pysnmp
score: 0
tagged with: snmp

http://stackoverflow.com/comment/80560180
score: 0
has text: Hatching is applied on a canvas level. Depending on where your axes starts within the canvas, hatches are at a different position. I'm very uncertain about what you are trying to achieve, but I would guess that hatching is not a solution for it.
comment on: http://stackoverflow.com/q/46803626
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80732510
has text: Your description mixes up dictionaries, lists and arrays. Are the values in `source` arrays or lists?
comment on: http://stackoverflow.com/q/46891530
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/46829352
tagged with: mysql
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/46829440
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: How to ordering by specific rules django
has body: I want to order my objects in django by this rule: All characters with is_sold == True must be in the end of query result. I am use two query, to get both sold and not sold characters: characters = list(Character.objects.all().filter(is_sold=False).order_by('server__ranking')) characters += list(Character.objects.filter(is_sold=True).order_by('server__ranking')) Can i do this using only one query using order_by
upvote count: 1
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46829440
score: 1

http://stackoverflow.com/comment/80694792
type: QuestionComment
comment on: http://stackoverflow.com/q/46873846
score: 0
has text: and then `test = test.rename(columns={'r2':'avg_r2', 'contact_id':'tickets', 'acknowledge_issues':'er_ai'})` ?
type: Comment

http://stackoverflow.com/a/46797504
has body: You can do this using the split method. From the docs, it will: Return a list of the words in the string, using sep as the delimiter string. So if you can take your string: prue = "VA=-0.850,0.800;CA=-0.863,0.800;SP=-0.860,0.810;MO=-0.860,0.810;SUN=MO -0.850,CA 0.810" you can do : prue.split(",") which will return a list of the strings split by the commas: ['VA=-0.850', '0.800;CA=-0.863', '0.800;SP=-0.860', '0.810;MO=-0.860', '0.810;SUN=MO -0.850', 'CA 0.810'] So if you just want the last item ('CA 0.8101') into a variable named test, you can just take the last element from the list by indexing with -1: test = prue.split(",")[-1] test is now: 'CA 0.810' Hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/46797221
score: 0

http://stackoverflow.com/a/46861163
has body: When you do not mention the key function of max, it will just take default ordering of the itearbles; in this case, the lexical order. You need to mention that you need to order by len. You need to do this: &gt;&gt;&gt; sen = "Argument goes here" &gt;&gt;&gt; max(sen.split(), key=len) 'Argument'
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46861134
downvote count: 0
type: Answer

http://stackoverflow.com/a/46760234
answers question: http://stackoverflow.com/q/46759620
type: AcceptedAnswer
has body: I think your compute_value function almost there. I complete your code. Regarding the error, that's because you call the function from ExampleBase. class ExampleBase: def __init__(self, company_name="N/A", stock_dict={}): """ class constructor """ self.company_name = company_name self.stock_dict = stock_dict print(self.stock_dict) return class Useful(ExampleBase): """ Inherits from ExampleBase class """ def __init__(self, company_name, stock_dict): super().__init__(company_name) return def compute_value(self, stock_dict): """ Computes value of stk """ val = sum(v1*v2 for v1,v2 in stock_dict.values()) return val ## ## Program starts running from here ## if __name__ == "__main__": a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)} b = Useful("Bern", a) value = b.compute_value(a) print(value) Also, if your intention for compute_value is to compute stock_dict that given when you create Useful instance, your class better goes like this: class Useful(ExampleBase): """ Inherits from ExampleBase class """ def __init__(self, company_name, stock_dict): super().__init__(company_name, stock_dict) return def compute_value(self): """ Computes value of stk """ val = sum(v1*v2 for v1,v2 in self.stock_dict.values()) return val with your main: if __name__ == "__main__": a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)} b = Useful("Bern", a) value = b.compute_value() print(value)
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46759620

gensim
tags question: http://stackoverflow.com/q/46888984
tags question: http://stackoverflow.com/q/46807010
tags question: http://stackoverflow.com/q/46786311
tag name: gensim
tags question: http://stackoverflow.com/q/46860197
tags question: http://stackoverflow.com/q/46889727
tags question: http://stackoverflow.com/q/46754881
tags question: http://stackoverflow.com/q/46769705
type: Tag

http://stackoverflow.com/comment/83974914
has text: Thats reasonable
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48477049

http://stackoverflow.com/comment/80509264
comment on: http://stackoverflow.com/q/46781420
type: Comment
type: QuestionComment
has text: Have you tried creating sample data and writing down the algorithm on paper?
score: 2

http://stackoverflow.com/comment/80569274
has text: @sascha, No, I'm looking forward to expending the array dimension.
comment on: http://stackoverflow.com/q/46810539
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80663586
has text: Sounds like an infinite recursion.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46856502
score: 0

http://stackoverflow.com/a/46791030
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46790892
type: Answer
has body: Try below code, it may help to your question a=[9,2,3] b=[4,5,6] c=[1,1,1] l = list(map(lambda x,y,z:[x,y,z],a,b,c)) You will get output like below [[9, 4, 1], [2, 5, 1], [3, 6, 1]]
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46790892
type: AcceptedAnswer

http://stackoverflow.com/a/46870106
has body: I'm thinking that you can see the data that you want to download in another web page, for example, by clicking on "My Systems (v4)". If you can do that, then you can use urllib.request.urlretrieve to download that page. And then you can use html.parser.HTMLParser to parse the data and do with as you wish.
score: 0
answers question: http://stackoverflow.com/q/46868630
type: Answer

http://stackoverflow.com/comment/80718005
type: Comment
comment on: http://stackoverflow.com/q/46884759
score: 0
type: QuestionComment
has text: How can i achieve the desired result...

http://stackoverflow.com/q/46796566
has comment: http://stackoverflow.com/comment/80539863
tagged with: tensorflow
has body: I have finished training the stack of 3 LSTMs and now I want to investigate how sensitive is each LSTM layer to small perturbations of its weights. I would like to load the model from checkpoints, add a small value to weights of a certain layer and record performance losses/gains. I wonder what is the simplest way to do this?
type: Question
has answer: http://stackoverflow.com/a/46803868
has title: TensorFlow: Adding a small noise to pre-trained weights
score: 0
has comment: http://stackoverflow.com/comment/129240185
linked to: http://stackoverflow.com/q/64542231
answer count: 1
accepted answer: http://stackoverflow.com/a/46803868
favorite count: 0
upvote count: 2
downvote count: 2
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/80546850
type: AnsweredQuestion

http://stackoverflow.com/q/46779264
has comment: http://stackoverflow.com/comment/80504430
answer count: 2
has title: Python nested loop, break if conditions not satisfied
has comment: http://stackoverflow.com/comment/80516098
tagged with: pandas
has answer: http://stackoverflow.com/a/46807033
tagged with: break
has comment: http://stackoverflow.com/comment/80515905
has body: I have been trying to use a nested loop to iterate through the rows of a pandas DataFrame, the outer loop, and for each row check if the conditions of a rule, a list of tuples:[(Attribute,Value),(Att,Val)], match those Att,Val pairs in the row of the DataFrame, the inner loop. If all conditions in the rule are satisfied I wish to record the index of the row, if 1 or more conditions fail I wish to break out of the inner loop without recording the row index and continue to the next row. I have tried placing the break statement in the inner loop, the outer loop etc but I cannot get it to work as I wish. Many thanks for any attempts at helping me. def rule_coverage(self, rule): for index,row in self.data.iterrows(): for selector in rule: if row[selector[0]] != selector[1]: break coverage.append(index) return self.data.iloc[coverage]
has comment: http://stackoverflow.com/comment/80515055
type: UnansweredQuestion
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/46779693
tagged with: loops
has comment: http://stackoverflow.com/comment/80516434
has comment: http://stackoverflow.com/comment/80514961
type: Question

http://stackoverflow.com/q/46867259
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48528382
has comment: http://stackoverflow.com/comment/80684011
tagged with: meep
type: Question
tagged with: vector
has title: Vector3 in Meep in Python
answer count: 2
has body: I'm getting 'module' object has no attribute 'Vector3' error in my simple python code. This is rightAngle.py file import meep as mp import math cell = mp.Vector3(16, 8, 0) geometry = [mp.Bloack(mp.Vector3(1e20, 1, 1e20), center = mp.Vector3(0, 0), material = mp.Medium(epsilon = 12))] sources = [mp.Source(mp.ContinuousSource(frequency = 0.15), component = mp.Ez, center = mp.Vector3(-7, 0))] pml_layers = [mp.PML(1.0)] resolution = 10 Compling using: python rightAngle.py &gt;&amp; rightAngle.out And getting this output: Traceback (most recent call last): File "rightAngle.py", line 4, in &lt;module&gt; cell = mp.Vector3(16, 8, 0) AttributeError: 'module' object has no attribute 'Vector3' All I'm doing is copy and pasting given code from this fairly reliable source but getting error in Vector3 object. Python version: Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 I don't know what I'm missing? Meep Documentation: https://meep.readthedocs.io/en/latest/Python_Tutorials/Basics/
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/69413241
tagged with: python
has comment: http://stackoverflow.com/comment/80688120
has comment: http://stackoverflow.com/comment/80682460
downvote count: 0
has comment: http://stackoverflow.com/comment/80683809

http://stackoverflow.com/q/46762767
favorite count: 0
has title: Python: trouble importing class definition from one .py into another
has comment: http://stackoverflow.com/comment/80470818
downvote count: 0
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4142151
score: 1
has comment: http://stackoverflow.com/comment/80470943
answer count: 2
has answer: http://stackoverflow.com/a/46762837
upvote count: 1
accepted answer: http://stackoverflow.com/a/46762837
has comment: http://stackoverflow.com/comment/80470824
has body: Problem: I'm having issues calling classes in a program. I created a program named example.py which has the following code: class ExampleBase: """ This is the ExampleBase class """ def __init__(self, company_name="N/A", stock_dict={}): """ class constructor """ self.company_name = company_name self.stock_dict = stock_dict return def __str__(self): """ Prints the company name string """ str = "The Company name is: %s" %\ (self.company_name ) return str def add_purchase(self, addtlSTK): """ Adds item to stock_dict """ self.stock_dict.update(addtlSTK) return I'm attempting to call ExampleBase in another program whose code is: import example if __name__ == "__main__": a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)} b = example.ExampleBase("Bern", a)
possible better answer: http://stackoverflow.com/a/46762992
has comment: http://stackoverflow.com/comment/80470860
tagged with: python
has answer: http://stackoverflow.com/a/46762992

http://stackoverflow.com/comment/80692288
score: 0
type: Comment
type: QuestionComment
has text: I've been getting errors with that
comment on: http://stackoverflow.com/q/46872550

http://stackoverflow.com/a/46805596
score: -1
answers question: http://stackoverflow.com/q/46805462
has comment: http://stackoverflow.com/comment/80558964
has comment: http://stackoverflow.com/comment/80558321
type: Answer
has comment: http://stackoverflow.com/comment/80558342
downvote count: 2
has comment: http://stackoverflow.com/comment/80558406
upvote count: 1
has comment: http://stackoverflow.com/comment/80558395
has body: Windows and Linux/macOS use different path separators - UNIX uses forward slashes (/) while Windows use back slashes (\). You should never type your own separators, always use os.path.join or os.sep, which handle this for you based on the platform you're running on. Example: import os folder_location = os.path.join('C:\\', 'Users', 'username', 'Dropbox', 'Inv') # or folder_location = os.sep.join(['C:\\', 'Users', 'username', 'Dropbox', 'Inv']); Also, you will need to manually escape the drive letter's trailing slash manually, as specified on the Python docs: Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo. Hard-coding a full path like this is usually useless, as C: will only work on Windows anyway. You will most likely want to use this later on using relative paths or paths that were fetched elsewhere and need to have segments added to them.

http://stackoverflow.com/comment/80605580
has text: Yes, this will include the entire dataset. You can repartition safely. Or you can call from_pandas with a different number of partitions. Everything should work fine here either way.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46821613
type: Comment

http://stackoverflow.com/comment/80489743
comment on: http://stackoverflow.com/a/46771947
score: 0
type: AnswerComment
has text: Thanks, I tried adding a dense layer after the convolutional layer, but without to flatten it. Now it works!
type: Comment

http://stackoverflow.com/q/46820223
answer count: 1
downvote count: 0
favorite count: 0
has body: Is this a valid way of loading subsets of a dask dataframe to memory: while i &lt; len_df: j = i + batch_size if j &gt; len_df: j = len_df subset = df.loc[i:j,'source_country_codes'].compute() I read somewhere that this may not be correct because of how dask assigns index numbers because of it dividing the bigger dataframe into smaller pandas dfs. Also I don't think dask dataframes has an iloc attribute. I am using version 0.15.2 In terms of use cases, this would be a way of loading batches of data to deep learning (say keras).
tagged with: dask
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46821613
type: Question
accepted answer: http://stackoverflow.com/a/46821613
has title: Subsetting Dask DataFrames
score: 4
upvote count: 4

http://stackoverflow.com/comment/80692855
has text: I was about to suggest to use another format like .png (also because bmp files are rather large), but forgot to post that. Good that you've figured it out yourself.
comment on: http://stackoverflow.com/a/46872289
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80749331
has text: No problem. Please remember to accept a correct answer and upvote using the controls at the left side of each answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46901004
type: Comment

http://stackoverflow.com/q/46898334
accepted answer: http://stackoverflow.com/a/47560892
type: Question
possible better answer: http://stackoverflow.com/a/46898460
has answer: http://stackoverflow.com/a/46898460
answer count: 6
has body: I am trying to build an equity curve in Python using Pandas. For those not in the know, an equity curve is a cumulative tally of investing profits/losses day by day. The code below works but it is incredibly slow. I've tried to build an alternate using Pandas .iloc and such but nothing is working. I'm not sure if it is possible to do this outside of a loop given how I have to reference the prior row(s). for today in range(len(f1)): #initiate a loop that runs the length of the "f1" dataframe if today == 0: #if the index value is zero (aka first row in the dataframe) then... f1.loc[today,'StartAUM'] = StartAUM #Set intial assets f1.loc[today,'Shares'] = 0 #dummy placeholder for shares; no trading on day 1 f1.loc[today,'PnL'] = 0 #dummy placeholder for P&amp;L; no trading day 1 f1.loc[today,'EndAUM'] = StartAUM #set ending AUM; should be beginning AUM since no trades continue #and on to the second row in the dataframe yesterday = today - 1 #used to reference the rows (see below) f1.loc[today,'StartAUM'] = f1.loc[yesterday,'EndAUM'] #todays starting aseets are yesterday's ending assets f1.loc[today,'Shares'] = f1.loc[yesterday,'EndAUM']//f1.loc[yesterday,'Shareprice'] #today's shares to trade = yesterday's assets/yesterday's share price f1.loc[today,'PnL'] = f1.loc[today,'Shares']*f1.loc[today,'Outcome1'] #Our P&amp;L should be the shares traded (see prior line) multiplied by the outcome for 1 share #Note Outcome1 came from the dataframe before this loop &gt;&gt; for the purposes here it's value is irrelevant f1.loc[today,'EndAUM'] = f1.loc[today,'StartAUM']+f1.loc[today,'PnL'] #ending assets are starting assets + today's P&amp;L
has answer: http://stackoverflow.com/a/47538220
has title: How do I avoid a loop with Python/Pandas to build an equity curve?
tagged with: pandas
has answer: http://stackoverflow.com/a/46900875
has answer: http://stackoverflow.com/a/63699552
has answer: http://stackoverflow.com/a/47560892
has answer: http://stackoverflow.com/a/46898558
has comment: http://stackoverflow.com/comment/80745112
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80785538
has comment: http://stackoverflow.com/comment/80746451
linked to: http://stackoverflow.com/q/20109391
score: 0

http://stackoverflow.com/a/46916676
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46895878
has comment: http://stackoverflow.com/comment/80892419
has body: To implement a dynamic SNMP table (where you can create/delete rows via SNMP SET) you should set up a hierarchy of MibTable, MibTableRow and MibTableColumn objects: (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance' ) And register them with pysnmp under the OIDs that reflect objects hierarchy e.g.: RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus') mibBuilder.exportSymbols( '__EXAMPLE-MIB', # table object exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess('readcreate'), # table row object, also carries references to table indices exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)).setMaxAccess('readcreate').setIndexNames((0, '__EXAMPLE-MIB', 'exampleTableColumn1')), # table column: string index exampleTableColumn1=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.OctetString()).setMaxAccess('readcreate'), # table column: string value exampleTableColumn2=MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()).setMaxAccess('readcreate'), # table column: integer value with default exampleTableColumn3=MibTableColumn((1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)).setMaxAccess('readcreate'), # table column: row status exampleTableStatus=MibTableColumn((1, 3, 6, 6, 1, 5, 4), RowStatus('notExists')).setMaxAccess('readcreate') ) Make sure to state how table index should look like e.g. the trailing part of the OID that goes past MibTableColumn OID. You do that by configuring one or more columns to the .setIndexNames(). If you want to be able to create/drop the whole row in one shot, you need to have a dedicated status column in your table with the value of type RowStatus. You can read the details on how RowStatus works in RFC2579 (search for RowStatus). By this point you should be able to create new rows: $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.2.97.98.99 s “my value” $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 4 (the 97.98.99 part of the …
accepted answer of: http://stackoverflow.com/q/46895878
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80787805

http://stackoverflow.com/q/46799667
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18689235
type: Question
upvote count: 5
tagged with: neural-network
has answer: http://stackoverflow.com/a/46812661
has title: How to resolve ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
score: 3
answer count: 1
favorite count: 0
has body: So I have this code: ####----Data----#### quest=pd.read_csv("inputFile.csv", names=["A1","A2",..."A200","Sim"]) print(quest.head()) ####----Set up Data and Label----#### X=quest.drop('Sim',axis=1) y=quest['Sim'] ####----Train Test Split----#### X_train, X_test, y_train, y_test = train_test_split(X, y) np.isfinite(X_train).any(), np.isfinite(y_train).any(),np.isfinite(X_test).any() np.isnan(X_train).any(), np.isnan(y_train).any(), np.isnan(X_test).any() ####----Data Pre-Processing----#### scaler=StandardScaler() # Fit only to the training data X_scaled=scaler.fit(X_train) # Now apply the transformations to the data: X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) ####----Training the Model----#### mlp=MLPClassifier(hidden_layer_sizes=(13,13,13), max_iter=500) mlp.fit(X_train,y_train) print(mlp) ####----Predictions and Evaluation----#### predictions=mlp.predict(X_test) print(confusion_matrix(y_test,predictions)) print(classification_report(y_test,predictions)) but I got this error: Traceback (most recent call last): File "E:\thesis\sk-ANN.py", line 67, in X_scaled=scaler.fit(X_train)... ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). My data set has values in exponential form, like this: 2.15E-06 -0.000556462 0.000197385 -0.000919 -0.000578077.... the same error occur at mlp.fit(X_train,y_train) and predictions=mlp.predict(X_test) Someone please help me how to resolve this problem
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/46812661

http://stackoverflow.com/a/46862582
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46862450
has body: &gt;&gt;&gt; x = [[1,2],[2,6],[1,5],[5,6],[5,6], [10,11], [11,12], [3,4],[4,8],[8,7],[3,7]] &gt;&gt;&gt; y = {'first':[[1,2],[2,6],[1,5],[5,6]], 'second':[[2,3], [3,7],[7,6],[2,6]]} &gt;&gt;&gt; for k,v in y.items(): y[k] = [a for a in v if a not in x] &gt;&gt;&gt; y {'second': [[2, 3], [7, 6]], 'first': []}

http://stackoverflow.com/comment/80668348
has text: Using slices: `713 ns ± 5.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)`. Using lookups: `640 ns ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)`
comment on: http://stackoverflow.com/a/46860218
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80687251
type: Comment
comment on: http://stackoverflow.com/q/46869883
score: 0
type: QuestionComment
has text: Thank you very much, it worked perfectly

http://stackoverflow.com/q/46897305
has comment: http://stackoverflow.com/comment/80741855
has answer: http://stackoverflow.com/a/46897363
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80742632
has body: My goal is to iterate over a list of names and return True only if they can be arranged so the last letter of a name is the same as the first letter of the next name. class Team(object): def __init__(self, names): self.names = names def __iter__(self): from collections import Counter first = Counter(map(lambda n: n[0].lower(), self.names)) last = Counter(map(lambda n: n[-1].lower(), self.names)) diff = last - first return any(diff.values()) &lt;= 1 def isCoolTeam(team): return bool(Team(team)) print(isCoolTeam(["Rob", "Bobby", "Billy"])) It should return False, but for some reason every input returns true.
downvote count: 0
has comment: http://stackoverflow.com/comment/80741917
accepted answer: http://stackoverflow.com/a/46897363
has answer: http://stackoverflow.com/a/46897610
has comment: http://stackoverflow.com/comment/80741820
has comment: http://stackoverflow.com/comment/80741938
has comment: http://stackoverflow.com/comment/80741886
has answer: http://stackoverflow.com/a/46897825
answer count: 3
possible better answer: http://stackoverflow.com/a/46897610
score: 3
tagged with: python
favorite count: 0
has title: Matching first and last of items in list
upvote count: 3

http://stackoverflow.com/q/46769942
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80485117
has answer: http://stackoverflow.com/a/46770193
accepted answer: http://stackoverflow.com/a/46770193
score: 1
type: Question
has answer: http://stackoverflow.com/a/46770019
upvote count: 2
tagged with: python-2.7
has title: How to change datetime format?
answer count: 2
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/80485098
favorite count: 0
has body: I have timestamps given in the following format in my pandas DataFrame df: 2015-03-09 11:09:05.0. How can I transform them into this format 2015-03-09T11:09:05.0 (i.e. separated by T)? df["dt"] = df["dt"].apply(lambda x: ???)
possible better answer: http://stackoverflow.com/a/46770019

http://stackoverflow.com/comment/80479006
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46766828
has text: you will find your answer here https://stackoverflow.com/questions/46001809/debugging-allauth-social-account-not-logging-user-in-despite-connecting-success/46049491#46049491
score: 0

http://stackoverflow.com/comment/80551443
comment on: http://stackoverflow.com/q/46801833
has text: Just giving feedback, I don't know what `parsed_stats` is. I'd expect you to provide this so we can experiment. I can't parse your dataframe.... this equates to me having to try to hard to help you.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80509308
type: Comment
type: QuestionComment
has text: Firstly, use Python3, then try `data['text'] = data['text'].astype(str)`
comment on: http://stackoverflow.com/q/46775092
score: 0

http://stackoverflow.com/a/46802455
accepted answer of: http://stackoverflow.com/q/46792780
upvote count: 2
has body: I think you are looking for rasterio.windows.transform. tile_window = rasterio.windows.Window(0, 0, 256, 256) tile_affine = rasterio.windows.transform(tile_window, smaller_image_affine) tile_image = smaller_image[(slice(None),) + tile_window.toslices()] Then with tile_image and tile_affine you have all the pieces you need to write this to a new file.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46792780
type: Answer
has comment: http://stackoverflow.com/comment/80560650
score: 2

http://stackoverflow.com/q/46800372
type: Question
score: 4
upvote count: 4
tagged with: sql
answer count: 1
downvote count: 0
has body: I was reading this SO question: psycopg2: insert multiple rows with one query and I found there was an excellent answer included that used cursor.mogrify to speed up a series of sql insertions. It got me wondering, does cursor.mogrify successfully escape all sql injection vulnerabilities? The code for the answer posted by Alex Riley was as follows: args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup) cur.execute("INSERT INTO table VALUES " + args_str) Does anyone know of any vulnerabilities to this method of using psychopg2's cursor.mogrify method and then following it up with a string interpolation in the cursor.execute function like this?
linked to: http://stackoverflow.com/q/8134602
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
has title: psychopg2: does cursor.mogrify prevent sql injection?
tagged with: python
has answer: http://stackoverflow.com/a/46800973

http://stackoverflow.com/a/46891387
answers question: http://stackoverflow.com/q/46891316
upvote count: 10
has body: You can use Python3's unpacking: a = range(0,10) b = 'a' c = 3 t = (*a,b,c) Output: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3) For Python2: import itertools t = tuple(itertools.chain.from_iterable([[i] if not isinstance(i, list) else i for i in (a, b, c)])) Output: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)
type: AcceptedAnswer
score: 10
accepted answer of: http://stackoverflow.com/q/46891316
downvote count: 0
type: Answer

http://stackoverflow.com/q/46789946
tagged with: kubernetes
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/37559704
has answer: http://stackoverflow.com/a/69754077
upvote count: 2
type: UnansweredQuestion
has body: I'm using python kubernetes 3.0.0 library and kubernetes 1.6.6 on AWS. I have pods that can disappear quickly. Sometimes when I try to exec to them I get ApiException Handshake status 500 error status. This is happening with in cluster configuration as well as kube config. When pod/container doesn't exist I get 404 error which is reasonable but 500 is Internal Server Error. I don't get any 500 errors in kube-apiserver.log where I do find 404 ones. What does it mean and can someone point me in the right direction.
tagged with: python
score: 2
has title: kubectl exec returning `Handshake status 500`
has answer: http://stackoverflow.com/a/70119831
type: Question
has answer: http://stackoverflow.com/a/51217256
answer count: 3

http://stackoverflow.com/q/46856979
has comment: http://stackoverflow.com/comment/80661621
tagged with: python
linked to: http://stackoverflow.com/q/3800086
has answer: http://stackoverflow.com/a/46900832
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80662267
type: Question
has title: How does one efficiently replace strings in a massive CSV-based array, using dictionaries?
tagged with: arrays
possible better answer: http://stackoverflow.com/a/46858351
tagged with: replace
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/6116978
has answer: http://stackoverflow.com/a/46858351
has comment: http://stackoverflow.com/comment/80661645
has body: I have a very large array with many rows and many columns (called "self.csvFileArray") that is composed of rows that I've read from a CSV file, using the following code in a class that deals with CSV files... with open(self.nounDef["Noun Source File Name"], 'rU') as csvFile: for idx, row in enumerate(csv.reader(csvFile, delimiter=',')): if idx == 0: self.csvHeader = row self.csvFileArray.append(row) I have a very long dictionary of replacement mappings that I'd like to use for replacements... replacements = {"str1a":"str1b", "str2a":"str2b", "str3a":"str3b", etc.} I'd like to do this in a class method that looks as follows... def m_globalSearchAndReplace(self, replacements): # apply replacements dictionary to self.csvFileArray... MY QUESTION: What is the most efficient way to replace strings throughout the array "self.csvFileArray", using the "replacements" dictionary? NOTES FOR CLARIFICATION: I took a look at this post but can't seem to get it to work for this case. Also, I want to replace strings within words that match, not just entire words. So, working with a replacement mapping of "SomeCompanyName":"xyz", I may have a sentence like "The company SomeCompanyName has a patent for product called abcSomeCompanyNamedef." You'll notice that the string has to be replaced, twice, in the sentence... once as a whole word and once as an embedded string.
accepted answer: http://stackoverflow.com/a/46900832
has comment: http://stackoverflow.com/comment/80661859

http://stackoverflow.com/q/46828279
type: UnansweredQuestion
has body: I want to calculate the ratio of the following case. any optimal code for doing the below scenario in Python. I am not able figure out in Python but able do the same in R. Input Ord_ID Flag 48221742 Y 48221742 Y 48221742 Y 48221742 Y 48221742 N 48221742 N 48221742 Y 48221742 N 48221742 N 48221742 N 291000002 N 291000002 Y 291000002 Y 291000002 Y 291000002 N 291000002 N 291000002 N 291000002 N Output Ord_ID Flag Y_Flag_Ratio 48221742 Y 0.5 48221742 Y 0.5 48221742 Y 0.5 48221742 Y 0.5 48221742 N 0.5 48221742 N 0.5 48221742 Y 0.5 48221742 N 0.5 48221742 N 0.5 48221742 N 0.5 291000002 N 0.375 291000002 Y 0.375 291000002 Y 0.375 291000002 Y 0.375 291000002 N 0.375 291000002 N 0.375 291000002 N 0.375 291000002 N 0.375 I tried the same in R, I was able to do the same in a single line code. Data$Y_flag_ratio = ave(Data$Flag == "Y", Data$Ord_ID)
tagged with: python
has comment: http://stackoverflow.com/comment/80604641
has title: Finding ratio of group by factors in Python?
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80604385
has answer: http://stackoverflow.com/a/46890359
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/46829850
upvote count: 2
answer count: 2
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/46827674
answer count: 2
tagged with: function
downvote count: 0
has body: I want to run 2 functions inside a method of a class at the same time in Python. I tried to use threading module but it doesn't work. My example codes are as below: import os, sys import threading from threading import Thread class Example(): def __init__(self): self.method_1() def method_1(self): def run(self): threading.Thread(target = function_a(self)).start() threading.Thread(target = function_b(self)).start() def function_a(self): for i in range(10): print (1) def function_b(self): for i in range(10): print (2) run(self) Example() If above codes get executed, it will just print all 1s first and then all 2s. However, what I want is to print 1 and 2 at the same time. Thus, the desired output should be them mixed up. Is threading module capable to do that? If not, what module can do that? If anyone knows how to solve it, please let me know. Appreciated!!
tagged with: class
has title: Threading two functions inside a method of a class Python
possible better answer: http://stackoverflow.com/a/46828230
tagged with: multiprocess
favorite count: 0
has answer: http://stackoverflow.com/a/46828230
tagged with: multithreading
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/46828035
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46828035
has comment: http://stackoverflow.com/comment/98817217
type: Question

find
tags question: http://stackoverflow.com/q/46766530
tags question: http://stackoverflow.com/q/46801683
type: Tag
tag name: find
tags question: http://stackoverflow.com/q/46779471

http://stackoverflow.com/comment/80557870
has text: Thanks, I had no idea. So it's actually a bug / feature / limitation of the REPL rather than python syntax.
type: Comment
comment on: http://stackoverflow.com/q/46805254
score: 0
type: QuestionComment

http://stackoverflow.com/a/46764265
has comment: http://stackoverflow.com/comment/80473763
has comment: http://stackoverflow.com/comment/80473828
type: Answer
upvote count: 6
has body: Use dropna if empty values are NaNs: cols = ['B','C','D'] df = df.dropna(subset=cols, thresh=2) #same as #df = df[df[cols].isnull().sum(1) &lt; 2] print (df) A B C D 0 NaN 1.0 NaN 1.0 2 3.0 3.0 3.0 3.0 Or if empty values are empty strings compare numpy arrays created by values and filter by boolean indexing: df = df[(df[cols].values == '').sum(axis=1) &lt; 2]
score: 6
answers question: http://stackoverflow.com/q/46764230
downvote count: 0

http://stackoverflow.com/comment/80581930
comment on: http://stackoverflow.com/q/46817107
type: QuestionComment
score: 0
has text: I've created the issue in the repo: https://github.com/syrusakbary/validate_email/issues/69, let's see if it's answered. Thanks!
type: Comment

http://stackoverflow.com/comment/80703680
type: Comment
has text: Hi Vaishali. When I try this, with `year` as an integer value, I get `TypeError: invalid type comparison`. What should the type of `year` be?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46878184

http://stackoverflow.com/comment/80496065
has text: @mkrieger1 they told is verbally in class.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46774696

http://stackoverflow.com/comment/80605600
comment on: http://stackoverflow.com/q/46829152
type: Comment
has text: You caused another exception while handling the first, as the error says. This has nothing to do with the if. Post the full error.
score: 5
type: QuestionComment

http://stackoverflow.com/comment/80736596
has text: Because they all take parameters which imply different assumptions about your data! LinearRegression is pretty robust, kernel-SVMs are not. No offense: but without knowing the difference between an rbf-kernel and a linear-kernel (check out the docs; rbf=default) you should be careful with your experiments!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46894490

http://stackoverflow.com/comment/80733068
comment on: http://stackoverflow.com/q/46891494
has text: do you have multiple clients installed perhaps? (maybe an older 9i or 10g Oracle home?) what does ORACLE_HOME point to?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/80586734
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46819590
has text: `delete_objects` *should* let you delete objects regardless of the version. I'm not 100% sure

http://stackoverflow.com/comment/80687075
comment on: http://stackoverflow.com/a/46869897
score: 0
type: AnswerComment
type: Comment
has text: No errors in the code, but all my ratios are 0 for some reason.

http://stackoverflow.com/a/46782683
type: Answer
upvote count: 4
downvote count: 0
has body: There are 2 types of buffer here: The buffer mentioned in recv() is in the user space which is in the running process's memory. The kernel also maintains a buffer in kernel space. When you call recv(), the data will be copied from kernel space to user space.
answers question: http://stackoverflow.com/q/46782505
score: 4

http://stackoverflow.com/a/46819839
has body: Hope it helps pd.concat([df1[1].reset_index(drop=True).add_suffix(i+1) for i,df1 in enumerate(df[df.duplicated('Name',keep=False)].groupby('Name',as_index=False))],axis=1) Out[218]: City1 Name1 Phone1 City2 Name2 Phone2 0 c Christian 700 a Sam 900 1 e Christian 500 d Sam 600 EDIT: This seems like what you want df1=df[df.duplicated('Name',keep=False)] df1['G']=df1.groupby('Name').cumcount().add(1) pd.concat([df1.reset_index(drop=True).drop('G',1).add_suffix(i) for i,df1 in df1.groupby('G')],axis=1) Out[308]: City1 Name1 Phone1 City2 Name2 Phone2 0 a Sam 900 d Sam 600 1 c Christian 700 e Christian 500
upvote count: 3
answers question: http://stackoverflow.com/q/46819490
accepted answer of: http://stackoverflow.com/q/46819490
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/q/46777793
has body: I'm new to generative networks and I decided to first try it on my own before seeing up a code. These are the steps I used to train my GAN. [lib: tensorflow] 1) Train a discriminator on the dataset. (I used a dataset of 2 features with labels of either 'mediatating' or 'not meditating', dataset: https://drive.google.com/open?id=0B5DaSp-aTU-KSmZtVmFoc0hRa3c ) 2) Once the the discriminator is trained, save it. 3) Make another file with for another feed forward network (or any other depending on your dataset). This feed forward network is the generator. 4) Once the generator is constructed, restore the discriminator and define a loss function for generator such that it learns to fool the discriminator. (this didn't work in tensorflow because sess.run() doesn't return a tf tensor and the path between G and D breaks but should work when done from scratch) d_output = sess.run(graph.get_tensor_by_name('ol:0'), feed_dict={graph.get_tensor_by_name('features_placeholder:0'): g_output}) print(d_output) optimize_for = tf.constant([[0.0]*10]) #not meditating g_loss = -tf.reduce_mean((d_output - optimize_for)**2) train = tf.train.GradientDescentOptimizer(learning_rate).minimize(g_loss) Why don't we train a generator like this? This seems so much simpler. It's true I couldn't manage to run this on tensorflow but this should be possible if I do from scratch. Full code: Discriminator: import pandas as pd import tensorflow as tf from sklearn.utils import shuffle data = pd.read_csv("E:/workspace_py/datasets/simdata/linear_data_train.csv") learning_rate = 0.001 batch_size = 1 n_epochs = 1000 n_examples = 999 # This is highly unsatisfying &gt;:3 n_iteration = int(n_examples/batch_size) features = tf.placeholder('float', [None, 2], name='features_placeholder') labels = tf.placeholder('float', [None, 1], name = 'labels_placeholder') weights = { 'ol': tf.Variable(tf.random_normal([2, 1]), name = 'w_ol') } biases = { 'ol': tf.Variable(tf.random_normal([1]), name = 'b_ol') } ol = tf.nn.sigmo…
accepted answer: http://stackoverflow.com/a/46777936
tagged with: neural-network
tagged with: deep-learning
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/46777936
tagged with: python
answer count: 1
upvote count: 3
has title: Why not train GANs like this?
tagged with: tensorflow

http://stackoverflow.com/q/46849574
upvote count: 11
tagged with: psutil
has answer: http://stackoverflow.com/a/46884863
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46976221
tagged with: python
score: 11
answer count: 4
has body: I am looking for a way to start multiple process efficiently with low priority in Windows. I tried : def run(command): # command['Program.exe args1 args2','output_file'] try : p = subprocess.Popen(command[0] , stdout = command[1]) psutil.Process(p.pid).nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) p.wait() except Exception as e: print(e) raise SystemExit The problem is : the low priority is not set immediately. I get some freeze at the beginning. When I look closer in the process window I can see the priority of the application starting at high_priority and switch to low_priority. I would like to start immediately at low priority or find another way to block the CPU usage (100% right now). Then I use the run command inside a multiprocessing pool (few second for each run). def safe_run(args): """Call run(), catch exceptions.""" try: run(args) except Exception as e: print(args[0]) print(e) def parallel(commands,nb_proc): # populate files # start processes if len(commands) &lt; 10: nb_proc = 1 print('Use of {} cpus\n'.format(nb_proc)) pool = mp.Pool(nb_proc) pool.map(safe_run, commands, chunksize=1) UPDATE Test.exe is a fortran code : integer function NumArguments() integer :: IARGC NumArguments = IARGC() end function subroutine GetArgument(Idx,Argument) integer, intent(in) :: Idx character(LEN=*), intent(out) :: Argument call GETARG(Idx,Argument) end subroutine program Console implicit none integer, parameter :: INTEG = SELECTED_INT_KIND(9) integer(INTEG), parameter :: MAX_STRING_LEN = 1024_INTEG character(LEN=MAX_STRING_LEN) :: FileName integer(INTEG) :: i call GetArgument(1,FileName) ! Body of Console !print *, 'Hello World' !print *, FileName call sleep(5) open(unit=1, file=FileName,status='new') Do i=1,1000,1 write(1,*) i Enddo close(unit=1) end program Console Full code : # -*- coding: utf-8 -*- """ """ ############################################################################### ############################################################################### # # IMP…
has answer: http://stackoverflow.com/a/59148933
downvote count: 0
has answer: http://stackoverflow.com/a/56884806
type: Question
tagged with: python-multiprocessing
has title: Start process with low priority Popen

http://stackoverflow.com/comment/80548966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46801078
has text: `snmpSessionBaseClass ` is probably not a module, but an abstract base class defined in as part of a module. What is the name of the module you are missing?
score: 0

http://stackoverflow.com/comment/80546872
comment on: http://stackoverflow.com/q/46799456
score: 0
type: Comment
type: QuestionComment
has text: Have you considered providing a minimal working example?

http://stackoverflow.com/q/46760886
has answer: http://stackoverflow.com/a/46761099
downvote count: 1
type: Question
score: 0
upvote count: 1
answer count: 1
has body: I have been trying my hand at a NASCAR project, where I would have to use a class to create 20 unique vehicles and then have them race ( or to see who would reach 500 miles first, through the means of repeatedly choosing a different speed between 1 and 120 and adding it to an increasing odometer). I made what you see below and ran it, and it boots well into the Python IDLE. However, it will always tell me that NameError: name 'Driver_sponsor' is not defined. See, I have been facing this error for a while now, and I have tried placing the Driver_sponsor list into a class, placing it into the Main def and placing the keyword self. before it. No matter what I did, I faced this error. I am going to go back into my class book to see what I can do, but I am hoping that someone here can tell me what I am missing within my code, since, really, I am extremely lost. from random import randint import time class Car: def __init__(self,Driver_Name,Sponsor): self.__Total_Odometer_Miles = 0 self.__Speed_Miles_Per_Hour = 0 self.__Driver_Name = Driver_Name self.__Sponsor = Sponsor self.__Driver = ('Drivers name Missing') self.__Sponsor = ('Sponsor Missing') self.__Driver_sponsor = {'A.J.Allmendinger:3M','Aric Almirola:Allegiant ','Trevpr Bayne:AMR ','Ryan Blaney:Camping World ','Clint Bowyer:Chevrolet ', 'Chris Buesher:Coca-Cola','Kurt Busch:Coca-light ','Kyle Busch:Credit One ','Landon Cassill:Ford','Matt DiBenedetto:FDP', 'Austin Dillon:','Ty Dillon:','Dale Earnhardt:Jacob Companies ','Chase Elliott: M &amp; M ','Denny Hamlin: Microsoft ', 'Kevin Harvick:GoodYear ','Jimmie Johnson:Nationwide','Erik Jones:SUNOCO','Kasey Kahne:Toyota','Matt Kenseth:Visa ' } def Name(self,Driver_Name): self.__Driver_Name = Driver_Name def Retrieve_Name(self): return self.__Driver_Name def __mutualize__(self): self.__Total_Odometer_Miles = 0 self.__Speed_Miles_Per_Hour = 0 def sponsors(self): self.__Driver_sponsor = {'A.J.Allmendinger:3M','Aric Almirola:Allegiant ','Trevpr Bayne:AMR ','Ryan Blaney:Cam…
favorite count: 0
has comment: http://stackoverflow.com/comment/80467117
type: UnansweredQuestion
tagged with: python
has title: Why is it so that I keep getting the error that Driver sponsor is not defined, even though I placed it within a class?

http://stackoverflow.com/q/46783078
has title: URI encoding in Python Requests package
tagged with: python
has answer: http://stackoverflow.com/a/76093005
type: AnsweredQuestion
tagged with: urlencode
has comment: http://stackoverflow.com/comment/80513182
has answer: http://stackoverflow.com/a/46783596
possible better answer: http://stackoverflow.com/a/76093005
tagged with: python-requests
downvote count: 1
upvote count: 44
type: Question
score: 43
answer count: 2
accepted answer: http://stackoverflow.com/a/46783596
favorite count: 0
has body: I am using python requests package to get results from a API and the URL contains + sign in it. but when I use requests.get, the request is failing as the API is not able to understand + sign. how ever if I replace + sign with %2B (URI Encoding) the request is successful. Is there way to encode these characters, so that I encode the URL while passing it to the requests package Error: test user@gmail.com does not exist API : https://example.com/test+user@gmail.com

http://stackoverflow.com/q/46791359
tagged with: pathos
accepted answer: http://stackoverflow.com/a/46842031
tagged with: python
has answer: http://stackoverflow.com/a/46839474
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/46839474
has comment: http://stackoverflow.com/comment/80617759
has body: I have the following problem: I would like to use a amap from pathos.multiprocessing. import pathos as pt class Foo: def __init__(self): pass def f(self, a, b, c): return a + b + c def g(self): pool = pt.multiprocessing.ProcessPool() def _h(a, b, c): k = self.f(a, b, c) return k/2 result = [pool.amap(_h, (i, j, k)) for i in range(3) for j in range(5) for k in range(7)] return result a = Foo() b = a.g() b[0].get() It is necessary to have these two function f and g although I could do everything within f. If I run this code I get that g expects 3 arguments but one was given. TypeError: _h() takes exactly 3 arguments (1 given) How can I fix this?
type: Question
has comment: http://stackoverflow.com/comment/80618534
answer count: 2
has title: how to handover *args to pathos' amap
has answer: http://stackoverflow.com/a/46842031
has comment: http://stackoverflow.com/comment/80617828

datetime
tags question: http://stackoverflow.com/q/46861647
tags question: http://stackoverflow.com/q/46836330
tags question: http://stackoverflow.com/q/46878156
tags question: http://stackoverflow.com/q/46769942
tags question: http://stackoverflow.com/q/46759888
tags question: http://stackoverflow.com/q/46858626
tags question: http://stackoverflow.com/q/46784482
tags question: http://stackoverflow.com/q/46837568
tags question: http://stackoverflow.com/q/46814724
tags question: http://stackoverflow.com/q/46864957
tags question: http://stackoverflow.com/q/46772093
tags question: http://stackoverflow.com/q/46873827
tags question: http://stackoverflow.com/q/46862946
tags question: http://stackoverflow.com/q/46751078
tags question: http://stackoverflow.com/q/46858090
tags question: http://stackoverflow.com/q/46905576
tags question: http://stackoverflow.com/q/46881413
tag name: datetime
tags question: http://stackoverflow.com/q/46762920
tags question: http://stackoverflow.com/q/46834732
tags question: http://stackoverflow.com/q/46842508
tags question: http://stackoverflow.com/q/46753628
tags question: http://stackoverflow.com/q/46870557
tags question: http://stackoverflow.com/q/46767186
tags question: http://stackoverflow.com/q/46880810
type: Tag
tags question: http://stackoverflow.com/q/46761906
tags question: http://stackoverflow.com/q/46851868
tags question: http://stackoverflow.com/q/46882803
tags question: http://stackoverflow.com/q/46842793
tags question: http://stackoverflow.com/q/46834202
tags question: http://stackoverflow.com/q/46839032
tags question: http://stackoverflow.com/q/46798252
tags question: http://stackoverflow.com/q/46755489
tags question: http://stackoverflow.com/q/46896024
tags question: http://stackoverflow.com/q/46832468
tags question: http://stackoverflow.com/q/46860375
tags question: http://stackoverflow.com/q/46897691

http://stackoverflow.com/a/46758660
type: Answer
answers question: http://stackoverflow.com/q/46758445
has body: When your file has only 2 lines, the 2nd line will be what you expected, so your program works. When you have more than 2 lines, the 2nd line ends with a new line character \n. Just make sure to get rid of the last character before you compare. if lines[1].rstrip("\n") == name: will do. Thanks to @Rawing
score: 0

http://stackoverflow.com/comment/80583222
has text: Actually really easy: it should be within `self` in `get_queryset`. So in the method you find it: `self.request`.
type: Comment
comment on: http://stackoverflow.com/a/46817424
type: AnswerComment
score: 1

http://stackoverflow.com/q/46881302
has title: Calculating a Streak from a column in Python
tagged with: python
type: AnsweredQuestion
has body: I have a df that has a Basket column of hits H and misses H. I am calculating a streak from this column. My df looks like this, vs game quarter Basket 0 ORL 1 1 H 1 ORL 1 1 M 2 ORL 1 1 M 3 ORL 1 1 H 4 ORL 1 1 H 5 ORL 1 1 M 6 ORL 1 1 M 7 ORL 1 1 M 8 ORL 1 1 M 9 ORL 1 2 H 10 ORL 1 2 H 11 ORL 1 2 H 12 ORL 1 2 M This is how, I have my function, count = 0 def count_hit(x): global count if x == 'H': count += 1 else: count = 0 return count After this, I created a variable Streak with above function as function does I get the Streak = df['Basket'].apply(count_hit) print(Streak) &gt;&gt; 1 0 0 1 2 0 0 0 0 1 2 3 However, I need my Streak like this, 1 0 2 0 0 0 3 Here, for example, first Streak 1 is a H followed by miss M (Indexed 1 through 1 and there is a 0 after because of miss in 2nd index). Second Streak is 2 that goes from index 3 through 5. How should I tweak my function here to calculate like that. I want to go to the next M miss as soon as H hit ends to calculate a streak. Any help would be appreciated.
accepted answer: http://stackoverflow.com/a/46881439
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/80709960
score: 0
tagged with: pandas
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/46881439

http://stackoverflow.com/a/46869499
answers question: http://stackoverflow.com/q/46869468
type: Answer
score: 0
has body: The problem is that the method count() expects a string object. Right now, with this line (password.count(uppercase)), you are effectively passing an Array object to your function. See zeraien's answer for a good solution.

http://stackoverflow.com/comment/80894138
type: AnswerComment
has text: Interesting! Maybe you could make a PR against the main Chipmunk repo (https://github.com/slembcke/Chipmunk2D) in case this constraint would be useful for more people.
type: Comment
comment on: http://stackoverflow.com/a/46961977
score: 0

http://stackoverflow.com/q/46853377
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80658606
has comment: http://stackoverflow.com/comment/80658722
tagged with: python
has comment: http://stackoverflow.com/comment/80657422
has comment: http://stackoverflow.com/comment/80658172
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/80658665
score: 1
has comment: http://stackoverflow.com/comment/80654686
has body: I'm using Python and Selenium. My problem is that I can't switch on the modal that pops out and I can't click the buttons in it. This is the elements of the modal: This is my code: minus the url of course browser = webdriver.Chrome(executable_path="D:\\sasdsa\\automate\\chromedriver_win32\\chromedriver.exe") user_name = browser.find_element_by_xpath("//input[@id='username']") user_name.send_keys("test.employee") ##Password pass_word = browser.find_element_by_xpath("//input[@id='password']") pass_word.send_keys("123") ##log_in = browser.find_element_by_css_selector(".btn") log_in = browser.find_element_by_xpath("//button[@class='btn btn-sm btn-primary btn-block']") log_in.click() ##punch #driver.find_element_by_id("//@id='product_view') #To open the modal punch_in = browser.find_element_by_xpath("//button[@class='btn btn-success btn-sm pull-right']") punch_in.click() #cant switch to the modal to access the button browser.switch_to_frame("product_view") punch_in2 = browser.find_element_by_xpath("//button[@id='save_me']") punch_in2.click()
has comment: http://stackoverflow.com/comment/80659766
tagged with: switch-statement
type: Question
has comment: http://stackoverflow.com/comment/80657278
has answer: http://stackoverflow.com/a/46857084
has answer: http://stackoverflow.com/a/51429453
has answer: http://stackoverflow.com/a/72734757
has title: How to switch to a modal in Python using Selenium
upvote count: 2
has comment: http://stackoverflow.com/comment/80658245
answer count: 3
has comment: http://stackoverflow.com/comment/80657877
downvote count: 1
has comment: http://stackoverflow.com/comment/80658155

http://stackoverflow.com/q/46837771
has answer: http://stackoverflow.com/a/46838753
has answer: http://stackoverflow.com/a/46838082
tagged with: pip
tagged with: python
score: 10
type: AnsweredQuestion
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/80623496
accepted answer: http://stackoverflow.com/a/46838082
answer count: 2
has title: How to pip list with package urls
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/46838753
has body: I want to get a list of installed PIP packages with the URLs to those packages. I know that there is pip list command that lists all the packages installed, but it doesn't show the URL to package home page. There is also pip show command that shows info about a package including its URL, but it only works for one package. Is there a way to combine both commands to get a full list of packages with their respective home page URLs?

debugging
tags question: http://stackoverflow.com/q/46788035
tags question: http://stackoverflow.com/q/46798489
tag name: debugging
tags question: http://stackoverflow.com/q/46875867
tags question: http://stackoverflow.com/q/46799575
type: Tag
tags question: http://stackoverflow.com/q/46875156
tags question: http://stackoverflow.com/q/46849898
tags question: http://stackoverflow.com/q/46856327

http://stackoverflow.com/a/66107034
score: 0
has comment: http://stackoverflow.com/comment/116885255
type: Answer
answers question: http://stackoverflow.com/q/46752268
has body: This code works for performing basic calculations using Python print("Welcome to the Python Calculator") def addition(n,m): print(f"Addition of {n} and {m} is {n+m}") def subtraction(n,m): print(f"Subtraction of {n} and {m} is {n-m}") def multiplication(n,m): print(f"Multiplication of {n} and {m} is {n*m}") def division(n,m): print(f"Division of {n} and {m} is {n/m}") should_continue=False while not should_continue: n=int(input("Enter the number:")) user_input=input("Enter the operation you want to perform\n +\n -\n *\n / \n") m=int(input("Enter the number:")) if user_input=='+': addition(n,m) elif user_input=='-': subtraction(n,m) elif user_input=='*': multiplication(n,m) elif user_input=='/': division(n,m) user=input("want to continue type yes if not type no").lower() if user=="no": should_continue=True print("Bye Bye") Output: Welcome to the Python Calculator Enter the number:1 Enter the operation you want to perform + - * / selected operation is + Enter the number:2 Addition of 1 and 2 is 3 You can also perform the same above operations by using the below code. Here I used dictionary to call the Function name. def add(n,m): return n+m def subtraction(n,m): return n-m def multiplication(n,m): return n*m def division(n,m): return n/m operators={ '+':add,'-':subtraction,'*':multiplication,'/':division } should_continue=False while not should_continue: num1=int(input("Enter the number1:")) for i in operators: print(i) print("Enter the any one of the above operator you want to perform") user_input=input("") num2=int(input("Enter the number2:")) function=operators[user_input] print(f"{num1} {user_input} {num2} =",function(num1,num2)) user=input("want to continue type yes if not type no").lower() if user=="no": should_continue=True print("Bye Bye")
has comment: http://stackoverflow.com/comment/116889840

http://stackoverflow.com/a/53872419
answers question: http://stackoverflow.com/q/46819590
downvote count: 1
has comment: http://stackoverflow.com/comment/108635268
has comment: http://stackoverflow.com/comment/108679005
score: 10
has comment: http://stackoverflow.com/comment/116208979
has comment: http://stackoverflow.com/comment/108594427
has comment: http://stackoverflow.com/comment/122467645
upvote count: 11
has comment: http://stackoverflow.com/comment/108678390
has body: I had trouble using the other solutions to this question so here's mine. import boto3 bucket = "bucket name goes here" filename = "filename goes here" client = boto3.client('s3') paginator = client.get_paginator('list_object_versions') response_iterator = paginator.paginate(Bucket=bucket) for response in response_iterator: versions = response.get('Versions', []) versions.extend(response.get('DeleteMarkers', [])) for version_id in [x['VersionId'] for x in versions if x['Key'] == filename and x['VersionId'] != 'null']: print('Deleting {} version {}'.format(filename, version_id)) client.delete_object(Bucket=bucket, Key=filename, VersionId=version_id) This code deals with the cases where object versioning isn't actually turned on there are DeleteMarkers there are no DeleteMarkers there are more versions of a given file than fit in a single API response Mahesh Mogal's answer doesn't delete DeleteMarkers. Mangohero1's answer fails if the object is missing a DeleteMarker. Hari's answer repeats 10 times (to workaround missing pagination logic).
type: Answer

http://stackoverflow.com/comment/80558281
type: QuestionComment
has text: DB's are slow and I want classes that I can use as part of running some algorithm.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46805555

http://stackoverflow.com/comment/80606769
type: Comment
comment on: http://stackoverflow.com/q/46829489
type: QuestionComment
has text: i tried to fix the indetantion on your script but wasn't able to determine it 100%. Please check it and use 4 spaces as padding and not tabs. Specially important the `writer.writerow(combined_row)`. By the way, should the previous line be `combined_row.extend(['']*3)` instead of `combined.extend(['']*3)`?
score: 0

http://stackoverflow.com/comment/80693922
has text: added @BennyBoe
type: Comment
comment on: http://stackoverflow.com/a/46870164
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80748722
score: 0
has text: @kindall that is not quite right, as we have nested functions here, not a class.
type: QuestionComment
comment on: http://stackoverflow.com/q/46900824
type: Comment

http://stackoverflow.com/comment/80583746
comment on: http://stackoverflow.com/q/46818102
score: 0
has text: Why can't you? indentation is critical with python. We can only go by what we see.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46789062
has comment: http://stackoverflow.com/comment/80549388
has title: How to install pysaxon using pip3?
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/80539905
type: Question
has body: I try to install library into my project using next way: pip3 install -r requirements.txt My requirements.txt contains: six Cython git+https://github.com/ajelenak/pysaxon.git But installations fails: Collecting git+https://github.com/ajelenak/pysaxon.git (from -r /var/www/gost/gost/requirements.txt (line 20)) Cloning https://github.com/ajelenak/pysaxon.git to /tmp/pip-zkz6pq1u-build Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-zkz6pq1u-build/setup.py", line 8, in &lt;module&gt; from Cython.Build import cythonize ImportError: No module named 'Cython' What is wrong?
tagged with: saxon
tagged with: xslt-2.0
has comment: http://stackoverflow.com/comment/80552974
has comment: http://stackoverflow.com/comment/80541819
score: 0

http://stackoverflow.com/comment/80747115
type: AnswerComment
has text: or, in your case, `freq=CDay(calendar=cal)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46899909

http://stackoverflow.com/comment/80739311
comment on: http://stackoverflow.com/q/46896065
score: 1
has text: `Letters` is a `list` not a `dict` in your code (see first line). `d` is a dictionary, but you're not using it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80658538
has text: Your `set_from_set` isn't actually building the union you want; it just constructs a bunch of intermediate sets and throws them away, then returns the empty set you constructed on the first line.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/46855519

http://stackoverflow.com/q/46856379
tagged with: python
has body: I want to able to check if a record exists in the DB with a specific 'ID' and create one if it does not have one( i.e, Doesnt exist) Like so... I would also like to fetch "Num" For a specific record after it has been updated. import sqlite3 as lite db = lite.connect("test.db") id_to_be_added = "123456789101112" db.execute("CREATE TABLE USERS (ID TEXT, NUM INT)") Query = "{ SOMETHING IN SQL }" # This returns either True or False if Query: db.execute("UPDATE USERS SET NUM = NUM + 1 WHERE ID = {};".format(id_to_be_added)) else: db.execute("INSERT INTO USERS ({}, 0)".format(id_to_be_added)) num_to_be_printed = db.execute("SELECT NUM FROM USERS WHERE ID = {}".format(id_to_be_added)) print("{0} has {1}").format(id_to_be_added, num_to_be_printed)
has comment: http://stackoverflow.com/comment/80662599
upvote count: 1
has comment: http://stackoverflow.com/comment/80694025
downvote count: 1
has title: How to check if Record exists
type: Question
has comment: http://stackoverflow.com/comment/80660411
score: 0
answer count: 2
tagged with: sql
tagged with: sqlite
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46861667
has answer: http://stackoverflow.com/a/46856487
type: UnansweredQuestion

http://stackoverflow.com/comment/80511890
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46782764
type: AnswerComment
has text: It's [not just xoring (there is multiplication and some weird addition on each loop based on length to dodge the flaws in naive xoring)](https://github.com/python/cpython/blob/3.6/Objects/tupleobject.c#L348), but yeah, that's the general idea.

http://stackoverflow.com/q/46813114
tagged with: set
has answer: http://stackoverflow.com/a/46813234
type: Question
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/80573369
has body: In python, when creating a frozenset out of a list, for example: a=[1,2,3] b=frozenset(a) iterating over the items in 'a' iterates over 3 items, as expected, yet iterating over the items in 'b' also iterates over the same 3 items. I expected 'b' to contain only 1 item, the list 'a'. Why does this happen?
tagged with: python
upvote count: 4
has title: Why does creating a frozenset out of a list in python convert the list?
accepted answer: http://stackoverflow.com/a/46813234
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/46845131
has body: import warnings # import pdb def format_Warning(message, category, filename, lineno, line=''): return str(filename) + ':' + str(lineno) + ': ' + category.__name__ + ': ' +str(message) + '\n' warnings.formatwarning = format_Warning def tt(): warnings.warn("123") return 10 x = tt() print(x) Hope it helps!
upvote count: 1
answers question: http://stackoverflow.com/q/46844809
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/46801156
type: Question
has title: Class Factory do not work with isinstance
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/80585677
tagged with: python
has comment: http://stackoverflow.com/comment/80549133
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80549123
has body: I am trying to write a version of python's namedtuple that takes the types of the fields, and double checks that the fields are the correct types at creation. In order to do this, I created a factory function that returns a custom class. However, it's impossible to use instances of these classes with isinstance. Is there an easy way to fix this? Edit: To make the question more clear, neither of the if statements at the end of my code print anything, because the conditions evaluate to false. I'd like a simple way to determine which objects are instances of the class. Code below. from collections import namedtuple # TYPED VERSION OF A NAMEDTUPLE def typedtuple(name, fields, types): if len(fields) != len(types): raise TypeError("typedtuple must have the same number of fields and types") Base = namedtuple(name, fields) class TypedTuple(Base): def __new__(cls, *args): if len(fields) &lt; len(args): raise TypeError("Too many arguments to typedtuple" "{}; got {} and expected {}".format( name, len(args), len(fields) )) if len(fields) &gt; len(args): raise TypeError("Not enough arguments to typedtuple" "{}; got {} and expected {}".format( name, len(args), len(fields) )) i = 0 for a, t in zip(args, types): if not isinstance(a, t): raise TypeError("Wrong type of argument to typedtuple" "{}; {} at position {} is not of type {}".format( name, a, i, t )) i += 1 return Base(*args) TypedTuple.__name__ = name return TypedTuple GaussianInteger = typedtuple("GaussianInteger", ["real", "imag"], [int, int]) point = GaussianInteger(1,2) print point print type(point) print GaussianInteger if isinstance(point, GaussianInteger): print "it is an instance" if type(point) == GaussianInteger: print "it is the type of"

http://stackoverflow.com/q/46870784
tagged with: mongoengine
tagged with: mongodb
possible better answer: http://stackoverflow.com/a/55304531
score: 2
has answer: http://stackoverflow.com/a/55304531
downvote count: 0
has comment: http://stackoverflow.com/comment/80689838
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/80688967
has title: How can I update specific object in embedded list using mongoengine?
has answer: http://stackoverflow.com/a/46871271
tagged with: python
upvote count: 2
has body: This is my schema model class Address(Document): street = StringField() city = StringField() country = StringField() class Users(Document): user_name = StringField() address = ListField(EmbeddedDocumentField('Address')) This is what my object look like: { user_name: "John", address: [ { "street": "broadway", "city": "new york", "country": "US" }, { "street": "weymounth", "city": "london", "country": "England" } ] } This is my code to update the second item/object in address list: new_address = Address(street="bourke", city="melbourne", country="Australia") User.objects(id="1", address__country="England").update_one(set__address__S=new_address) But this update change the first object in embedded list instead of the second one: { user_name: "John", address: [ { "street": "bourke", "city": "melbourne", "country": "Australia" }, { "street": "weymounth", "city": "london", "country": "England" } ] }
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46871271
has answer: http://stackoverflow.com/a/65208175

http://stackoverflow.com/comment/80549336
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/46801280
has text: `np.outer(a, b)`?

http://stackoverflow.com/a/46891584
has comment: http://stackoverflow.com/comment/80730427
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46891535
has body: You didn't call your function that you wrote. def squareIt(n): return 2 ** n print("n", '\t', "2**n") #table column headings print("---", '\t', "-----") for x in range(13): #generate values for columns print(x, '\t', squareIt(x))
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46891535
score: 1

http://stackoverflow.com/comment/80606436
comment on: http://stackoverflow.com/a/46827237
score: 0
type: AnswerComment
has text: Thanks, I feel a bit silly now. It is actually a very simple solution, thank you nonetheless, it works!
type: Comment

http://stackoverflow.com/q/46750094
tagged with: python
has comment: http://stackoverflow.com/comment/80449612
tagged with: http://stackoverflow.com/tag/mp4
tagged with: video
answer count: 0
has body: I am partially downloading a video by specifying the Ranges header. I am doing this in python. So, suppose there is video whose duration is 4:43 min and has size 2.56 mb and I am only downloading 1 mb of it, so the actual duration of the video is somewhere around the 2 min mark. Now when I play this video, it plays till it has downloaded but shows 4:43 still as its total duration and abruptly ends like a corrupted video file does. Is there a way I can edit the bytes I receive on downloading the file, so that the video player recognises the exact position after which it should end? More importantly, I want to know if in videos, the start and end is determined by some set of bytes? Like, if I download a video from the 3000th byte to 6000th byte, it won't play as if its a corrupt video, so I want to know if its possible to add some bytes to the beginning of the file to let the player know that this is the beginning. How does a video player determine the end duration of a video from just the bytes?
type: Question
has comment: http://stackoverflow.com/comment/80446707
has title: How to fix duration for an incompletely downloaded video?
score: 0
tagged with: ffmpeg
type: UnansweredQuestion

http://stackoverflow.com/comment/80759275
score: 1
has text: @user2357112 the fun values should be functions in terms of a,b,c,d
comment on: http://stackoverflow.com/q/46897974
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46767101
score: 0
has comment: http://stackoverflow.com/comment/80480756
answer count: 1
tagged with: gunicorn
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80479686
has title: Not able to access server when invoking gunicorn via .bash file
type: Question
tagged with: server
has body: I am not able to access server when starting gunicorn via a .bash file I made. It works when I do it manually with this command $ gunicorn project.wsgi:application --bind 192.168.1.130:8000 Created a gunicorn.bash file from tutorials. I looks like this and runs without fault. #!/bin/bash NAME="project" # Name of the application DJANGODIR=/home/username/projects/project # Django project directory SOCKFILE=/home/username/.venvs/project/run/gunicorn.sock # We will communicate using this unix socket USER=username # the user to run as GROUP=username # the group to run as NUM_WORKERS=1 # how many worker processes shoul Gunicorn spawn DJANGO_SETTINGS_MODULE=project.settings.production # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/username/.venvs/project/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exsist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start yout Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- I don't know how to troubleshoot this? Maybe some command to see what differs in running settings from manually starting gunicorn and from the .bash file?
has answer: http://stackoverflow.com/a/46768437

http://stackoverflow.com/comment/80543283
has text: @Aadit. Import the dialog class, and then create a subclass of it in the same way as `PyMain`. Then in a slot connected to the button, do `self.dialog = DialogSubClass(); self.dialog.show()`.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46792269
type: Comment

http://stackoverflow.com/q/46871958
linked to: http://stackoverflow.com/q/46593021
linked to: http://stackoverflow.com/q/44746576
score: 0
has comment: http://stackoverflow.com/comment/80691080
tagged with: python
has answer: http://stackoverflow.com/a/46872055
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80692237
has title: Whats the difference between np.vectorize() and regular notation
has body: I am new at python and numpy. Consider that I have a function called addTwo that just returns the given value + 2. My question is what's the difference between np.vectorize(addTwo )(matrix) and addTwo (matrix). both give me the same output. Basically my question is: if I have following code: import numpy as np def addTwo(a): return a + 2 matr = np.array([[1, 2], [2, 3], [3, 4]]) I wonder difference between these two: addTwo(matr) np.vectorize(addTwo)(matr)
type: Question
tagged with: linear-algebra
accepted answer: http://stackoverflow.com/a/46872055
tagged with: numpy
has comment: http://stackoverflow.com/comment/80692477
answer count: 1

http://stackoverflow.com/q/46901356
has comment: http://stackoverflow.com/comment/80749681
has title: looping files and extracting segments in Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80749703
has answer: http://stackoverflow.com/a/46901453
type: Question
has body: I am trying to create a loop and extrat some segments of files located in a folder. I could easily do it in R but in Python I am having trouble. I have already tried with os and with glob. The code in R looks like this: ## loop over all files for (i in 1:length(file)) { ## extract file name file.name &lt;- strsplit(file[i],"\\.")[[1]][1] ## extract file header file.head &lt;- readLines(file[i], n = length(grep("#", readLines(file[i])))) .... and the code in Python that I made looks like this (path is the directoy): for file in os.listdir(path): ## extract file name filename = os.fsdecode(file) ## extract file header tempfile = os.open(file, os.O_RDWR) Altough I am new in Python, I didnt believe such simple thing would be so time consuming. I appreciate the help, as I have already scoutted the web for an answer.
has comment: http://stackoverflow.com/comment/80749716
accepted answer: http://stackoverflow.com/a/46901453
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 1
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/80547243
type: QuestionComment
comment on: http://stackoverflow.com/q/46758830
score: 1
type: Comment
has text: It is causing an error with a website I am trying to scrape. They error out if the connection is aborted too early (i.e "Connection: close")

http://stackoverflow.com/comment/80740067
type: Comment
has text: Thanks for the effort. I am still running it on my actual data and its a bit slow. The month 5 should be Churns 2 and New_visits 0. Is it a type or there some issue with the code?
comment on: http://stackoverflow.com/a/46895733
type: AnswerComment
score: 0

http://stackoverflow.com/q/46873827
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/80694642
has body: I am subtracting two dates in python 2.7 and getting wrong result in seconds. Apparently difference between these dates is more than 24h which is 86400s. But I am getting 44705s, why is that and how to fix it ? &gt;&gt;&gt; date1 datetime.datetime(2017, 10, 22, 11, 41, 28) &gt;&gt;&gt; date2 datetime.datetime(2017, 10, 20, 23, 16, 23) &gt;&gt;&gt; (date1-date2).seconds 44705
answer count: 2
upvote count: 1
tagged with: datetime
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/46873858
accepted answer: http://stackoverflow.com/a/46873858
downvote count: 0
possible better answer: http://stackoverflow.com/a/46873857
has answer: http://stackoverflow.com/a/46873857
has title: getting wrong time delta in python
type: Question

http://stackoverflow.com/q/46785041
has comment: http://stackoverflow.com/comment/80516587
has comment: http://stackoverflow.com/comment/80516965
has comment: http://stackoverflow.com/comment/80516781
tagged with: numpy
has comment: http://stackoverflow.com/comment/80516878
answer count: 1
has comment: http://stackoverflow.com/comment/80516465
favorite count: 0
has body: Tensorflow overrides multiple operators for the Tensor class, including __lt__, __ge__, etc. However, the implementation for __eq__ seems to be conspicuously absent: ops.Tensor._override_operator("__lt__", gen_math_ops.less) ops.Tensor._override_operator("__le__", gen_math_ops.less_equal) ops.Tensor._override_operator("__gt__", gen_math_ops.greater) ops.Tensor._override_operator("__ge__", gen_math_ops.greater_equal) Why does == for tensorflow's tensors not behave the same way as for numpy arrays? Code example: a = tf.constant([1,2]) b = tf.constant([3,4]) a == b &gt;&gt;&gt; False a &lt; b &gt;&gt;&gt; &lt;tf.Tensor 'Less:0' shape=(2,) dtype=bool&gt; With numpy, on the other hand: a = np.asarray([1,2]) b = np.asarray([3, 4]) a == b &gt;&gt;&gt; array([False, False], dtype=bool)
has answer: http://stackoverflow.com/a/46785346
accepted answer: http://stackoverflow.com/a/46785346
tagged with: python
score: 2
type: AnsweredQuestion
has title: Why does Tensorflow not override __eq__ for Tensors?
downvote count: 3
has comment: http://stackoverflow.com/comment/80516736
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/35094899
upvote count: 5

fits
tags question: http://stackoverflow.com/q/46831915
tag name: fits
type: Tag

http://stackoverflow.com/comment/80585501
type: QuestionComment
has text: @0TTT0 I add it now, thanks
comment on: http://stackoverflow.com/q/46818700
score: 0
type: Comment

http://stackoverflow.com/a/46899493
type: Answer
has body: You could build a dataframe by passing a dict to it. i = ['CIK','Period','Text'] j = [CIK, period, data] df = pd.DataFrame(dict(zip(i, j)) This is cheap as it doesn't result in creating copies of your data. The dict simply generates key-value pairs around the references (there's no need to create any data copies, only references are being moved around). Unfortunately, with your column_stack call, the arrays must be stacked into a freshly allocated array and a new result returned, which is wasteful.
has comment: http://stackoverflow.com/comment/80746629
upvote count: 2
answers question: http://stackoverflow.com/q/46899399
accepted answer of: http://stackoverflow.com/q/46899399
score: 2
has comment: http://stackoverflow.com/comment/80746587
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80746560

http://stackoverflow.com/a/46831036
upvote count: 0
has body: Using bash and awk you get this: for i in {0..999} do cp 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B `echo "$i 0x4f0DAA112142FFC4BA1B9f3B76bcd238A094D65B" | awk '{printf("%s_%03d\n",$2,$1)}'` done
score: -1
answers question: http://stackoverflow.com/q/46830574
downvote count: 1
type: Answer

http://stackoverflow.com/comment/80595431
comment on: http://stackoverflow.com/q/46812001
has text: Thanks for you comments, @MarkTolonen. I've found something interesting. I've been using Visual Studio Python Development Tools for creating the script and debugging and the output from here is wrong. Now I've tried running the script in IDLE (included with ArcGIS) and the script runs correct.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46758830
answer count: 0
tagged with: scrapy
type: Question
score: 5
has body: In my scrapy crawler I have the following custome_settings: custom_settings = { 'DEFAULT_REQUEST_HEADERS': { 'Connection' : 'Keep-Alive' } } I have even tried setting the headers in the scrapy.Reqest() as followed: headers = {} headers['Connection'] : 'Keep-Alive' headers['User-Agent'] : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' for url in urls: yield scrapy.Request(url, headers=headers, callback = self.parse) However the request is not overriding the value. Instead it is just appending another "Connection" into the request header. Request Packet: GET http://example.com HTTP/1.1 Connection: close Connection: Keep-Alive User-Agent: Scrapy/1.4.0 (+http://scrapy.org) Accept-Encoding: gzip,deflate But the request the "Connection : Keep-Alive" is appended to the request headers instead of overriding it. How do I actually override the "Connection" in the header of the request in scrapy?
upvote count: 5
tagged with: http-headers
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80547243
tagged with: python
has title: How to override "Connection : close" in header Scrapy?
has comment: http://stackoverflow.com/comment/80474533

http://stackoverflow.com/q/46869131
accepted answer: http://stackoverflow.com/a/46869467
type: Question
has comment: http://stackoverflow.com/comment/80686036
answer count: 1
has title: How to generate a list by specified rules?
score: 0
has comment: http://stackoverflow.com/comment/80685958
has body: How to efficiently generate a list by the specified rules? Rules: num 20 occurs with step 2 in the list num 40 occurs with step 4 in the list num 60 occurs with step 8 in the list num 80 occurs with step 16 in the list The end result of a list of length 15 should look like this: [20,40,20,60,20,40,20,80,20,40,20,60,20,40,20] The "step" rules are always a power of something. In this example is power of 2. So, let's say we have it written as: rules_power = 2 n1 = 20 n1_step = 2 n2 = 40 n2_step = 4 n3 = 60 n3_step = 8 n4 = 80 n4_step = 16 How do we efficiently generate such a list?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80685899
tagged with: python
has comment: http://stackoverflow.com/comment/80685731
has comment: http://stackoverflow.com/comment/80685791
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80685848
has answer: http://stackoverflow.com/a/46869467

http://stackoverflow.com/comment/80682923
type: Comment
type: QuestionComment
has text: @JonClements A number, at the lowest depth of the list.
score: 0
comment on: http://stackoverflow.com/q/46867704

http://stackoverflow.com/comment/123711613
has text: If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/30351042)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/69982926
type: AnswerComment

http://stackoverflow.com/comment/80598795
type: Comment
type: QuestionComment
has text: I'm asking on how to get an output of 1 1/4 instead of 1, 1, 4
comment on: http://stackoverflow.com/q/46825594
score: 0

image-scanner
tag name: image-scanner
type: Tag
tags question: http://stackoverflow.com/q/46783784

http://stackoverflow.com/a/46789278
downvote count: 0
answers question: http://stackoverflow.com/q/46789055
has comment: http://stackoverflow.com/comment/80525105
has comment: http://stackoverflow.com/comment/80525270
accepted answer of: http://stackoverflow.com/q/46789055
has comment: http://stackoverflow.com/comment/80525600
has comment: http://stackoverflow.com/comment/80525470
type: Answer
upvote count: 1
has body: Need sort_values + drop_duplicates with select columns for check dupes and keep only last value: df = (df.sort_values(by=['wikidataType', 'itemId', 'revisionId']) .drop_duplicates(['itemId','wikidataType'], keep='last')) print (df) revisionId itemId wikidataType 1 307190482 23 Q5 6 305019084 80 Q5 8 303692414 181 Q5 9 306600439 192 Q5 11 294597048 206 Q5
score: 1
has comment: http://stackoverflow.com/comment/80525478
type: AcceptedAnswer

http://stackoverflow.com/comment/80628805
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46840384
score: 0
has text: Even easier if you want to use HTTP: https://docs.python.org/2/library/simplehttpserver.html

http://stackoverflow.com/comment/80690198
has text: I meant `pygame.sprite.Sprite` not `pygame.Sprite`.
score: 0
comment on: http://stackoverflow.com/q/46862739
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46780538
has body: Let's start in the middle. Presumably, a character of any race has the same attributes, just different values for those attributes. class Race: def __init__(self): self.life = 100 # 100% healthy class Humanoid(Race): def __init__(self): super().__init__() self.legs = 2 class Insectoid(Race): def __init__(self): super().__init__() self.legs = 8 class Human(Humanoid): def __init__(self): super().__init__() self.brawn = 2 self.agility = 2 self.intellect = 2 self.cunning = 2, self.willpower = 2 self.presence = 2 class Elf(Humanoid): def __init__(self): super.__init__() self.brawn = 1 self.agility = 3 self.intellect = 3 self.cunning = 2 self.willpower = 3 self.presence = 1 Now, any particular character would be instantiated as the correct class: some_elf_1 = Elf() some_human_1 = Human() some_human_2 = Human() for character in [some_elf_1, some_human_1, some_human_2]: print("Brawn: ", character.brawn) In the preceding, it doesn't matter what the actual type of each character is; as long as you know that it is some subclass of Race (or an instance of Race itself), it will have a brawn attribute that you can access. You data class doesn't really seem necessary without more detail.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46780461
has comment: http://stackoverflow.com/comment/80507241
accepted answer of: http://stackoverflow.com/q/46780461
type: Answer
has comment: http://stackoverflow.com/comment/80508296

c#
tags question: http://stackoverflow.com/q/46890592
tag name: c#
tags question: http://stackoverflow.com/q/46874324
tags question: http://stackoverflow.com/q/46827150
tags question: http://stackoverflow.com/q/46773858
tags question: http://stackoverflow.com/q/46772395
tags question: http://stackoverflow.com/q/46829793
tags question: http://stackoverflow.com/q/46784976
tags question: http://stackoverflow.com/q/46872431
type: Tag
tags question: http://stackoverflow.com/q/46821018
tags question: http://stackoverflow.com/q/46886903

http://stackoverflow.com/comment/80750645
type: Comment
comment on: http://stackoverflow.com/q/46901926
score: 1
has text: `open(...)` supposed to return a file-handler. what's the meaning of `file_handler % cusername` ?
type: QuestionComment

http://stackoverflow.com/a/46785306
has comment: http://stackoverflow.com/comment/80517015
accepted answer of: http://stackoverflow.com/q/46784727
answers question: http://stackoverflow.com/q/46784727
has comment: http://stackoverflow.com/comment/80524826
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Base R solution: do.call(rbind, lapply(split(df, df$Id), function(x) x[seq(from = 1, to = nrow(x), by = unique(x$Nth)), ])) Id TagNo Nth a.1 a A-A-3 3 a.4 a A-A-2 3 b b B-B-5 4
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/80516943
has comment: http://stackoverflow.com/comment/80520007

http://stackoverflow.com/q/46871133
type: AnsweredQuestion
score: 4
accepted answer: http://stackoverflow.com/a/46871206
type: Question
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46871206
has body: in the older version we could get the list of spiders(spider names ) with following code, but in the current version (1.4) I faced with [py.warnings] WARNING: run-all-spiders.py:17: ScrapyDeprecationWarning: CrawlerRunner.spiders attribute is renamed to CrawlerRunner.spider_loader. for spider_name in process.spiders.list(): # list all the available spiders in my project Use crawler.spiders.list(): &gt;&gt;&gt; for spider_name in crawler.spiders.list(): ... print(spider_name) How Can I get spiders list (and equivalent class names) in Scrapy?
tagged with: python
upvote count: 4
downvote count: 0
has title: Get All Spiders Class name in Scrapy
tagged with: web-scraping
tagged with: scrapy

http://stackoverflow.com/comment/80547412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46800178
score: 0
has text: as long as we can see what you DID import, we can help

http://stackoverflow.com/comment/80521397
comment on: http://stackoverflow.com/q/46787429
type: Comment
has text: I don't believe that you don't get an error. `listOfCompanies` is a `list` which does not exist inside the function `populatebox()` so when calling it inside that function it returns an error `NameError: name 'listOfCompanies' is not defined`. So you are guaranteed to return an error with the code you provided us.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80493583
has text: @Pi See `9A` vs `99` and `14` vs `15` in the results. (You have to scroll to the right to see it).
score: 0
comment on: http://stackoverflow.com/q/46773858
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46854568
has answer: http://stackoverflow.com/a/46854658
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/47596733
has comment: http://stackoverflow.com/comment/80656667
has title: Quotes without backslash in subprocess command line in python
favorite count: 0
tagged with: python
tagged with: subprocess
downvote count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46854651
type: Question
score: 1
has body: I'm trying to use ffmpeg from python. The command I need to execute is: ffmpeg -i test_file-1kB.mp4 -i test_file.mp4 -filter_complex psnr="stats_file=test_file.mp4-1kB.psnr" -f null - However, my output that is getting passed to subprocess looks like it is escaping the double quotes with backslashes like so: In[1]: print(subprocess.list2cmdline(psnr_args)) ffmpeg -i test_file-1kB.mp4 -i test_file.mp4 -filter_complex psnr=\"stats_file=test_file.mp4-1kB.psnr\" -f null - To use subprocess, I build my command line arguments one at a time into a list and then pass the list to subprocess. psnr_args = [] psnr_args.append("ffmpeg") #add first input, the encoded video psnr_args.append("-i") psnr_args.append(full_output_file_name) #add second input, the original video psnr_args.append("-i") psnr_args.append(video_file) #Setup the psnr log file psnr_args.append("-filter_complex") psnr_args.append('psnr="stats_file=%s.psnr"' % vstats_abs_filename ) #Output the video to null psnr_args.append("-f") psnr_args.append("null") psnr_args.append("-") print(subprocess.list2cmdline(psnr_args)) run_info_psnr = subprocess.run(psnr_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

django-templates
tags question: http://stackoverflow.com/q/46809355
tags question: http://stackoverflow.com/q/46797973
tags question: http://stackoverflow.com/q/46773450
tags question: http://stackoverflow.com/q/46843694
tags question: http://stackoverflow.com/q/46880926
tags question: http://stackoverflow.com/q/46775664
tags question: http://stackoverflow.com/q/46824832
tag name: django-templates
tags question: http://stackoverflow.com/q/46786239
tags question: http://stackoverflow.com/q/46820315
type: Tag
tags question: http://stackoverflow.com/q/46870835
tags question: http://stackoverflow.com/q/46750948
tags question: http://stackoverflow.com/q/46792118
tags question: http://stackoverflow.com/q/46884619

http://stackoverflow.com/q/46878117
has comment: http://stackoverflow.com/comment/80703281
has answer: http://stackoverflow.com/a/46878309
downvote count: 1
type: Question
has body: I am trying very hard to write a function that will duplicate the first string in a list into 6 places and duplicate the ones that occur at even indices into two places,if it occurs at an index that is a multiple of three, duplicate three times. However, if it occurs at both an even index and at an index that is a multiple of three, it should duplicate it into six places. Here is the code i have written but it seems not to be solving it dynamically as soon as i change input and target more cases i get this error : IndexError: list index out of range def multiply_strings(test): test[0] *= 6 test[2] *= 2 test[3] *= 3 test[4] *= 2 test[6] *= 6 test[8] *= 8 return test test_list = ["A", "B", "C", "D", "E", "F", "G"] print(multiply_strings(test_list)) this prints IndexError: list index out of range This is not the desired output. am expecting it to print ['AAAAAA', 'B', 'CC', 'DDD', 'EE', 'F', 'GGGGGG'] But am expected to take care of other cases like ["A", "B", "C", "D", "E", "F", "G", "H", "I"] this will print. ['AAAAAA', 'B', 'CC', 'DDD', 'EE', 'F', 'GGGGGG', 'H', 'II'] There are also other edge cases similar to this one i already posted.
has answer: http://stackoverflow.com/a/46878533
has answer: http://stackoverflow.com/a/46878192
has comment: http://stackoverflow.com/comment/80703884
answer count: 3
has comment: http://stackoverflow.com/comment/80703624
upvote count: 0
favorite count: 0
has title: How to multiply string that occur at different indices python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80705494
score: -1
tagged with: list

http://stackoverflow.com/comment/80728038
has text: check your model may probelm
comment on: http://stackoverflow.com/q/46890365
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46851600
score: 12
has comment: http://stackoverflow.com/comment/80651138
answer count: 2
has body: I am trying to read a h5 file in Python. The file can be found in this link and it is called 'vstoxx_data_31032014.h5'. The code I am trying to run is from the book Python for Finance, by Yves Hilpisch and goes like this: import pandas as pd h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r') futures_data = h5['futures_data'] # VSTOXX futures data options_data = h5['options_data'] # VSTOXX call option data h5.close() I am getting the following error: h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r') Traceback (most recent call last): File "&lt;ipython-input-692-dc4e79ec8f8b&gt;", line 1, in &lt;module&gt; h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r') File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 466, in __init__ self.open(mode=mode, **kwargs) File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 637, in open raise IOError(str(e)) OSError: HDF5 error back trace File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5F.c", line 604, in H5Fopen unable to open file File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fint.c", line 1085, in H5F_open unable to read superblock File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fsuper.c", line 277, in H5F_super_read file signature not found End of HDF5 error back trace Unable to open/create file 'path.../vstoxx_data_31032014.h5' where I have substituted my working directory for 'path.../' for the purpose of this question. Does anyone know where this error might be coming from?
upvote count: 12
has comment: http://stackoverflow.com/comment/80650926
downvote count: 0
possible better answer: http://stackoverflow.com/a/72415391
favorite count: 0
has answer: http://stackoverflow.com/a/72415391
tagged with: h5py
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46851877
tagged with: python
has comment: http://stackoverflow.com/comment/80651168
has title: Open .h5 file in Python
has comment: http://stackoverflow.com/comment/80651113
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46851877

http://stackoverflow.com/comment/80533405
type: QuestionComment
comment on: http://stackoverflow.com/q/46793033
type: Comment
score: 0
has text: In my code I am using dictionaries which might be totally empty and other dictionaries which might have a nested dictionary also empty, nothing else, no other kind of dictionaries, I am trying to avoid double checking, I thought using all() or bool() as I wrote in my question but it just works for one of them, never for both at the same time

http://stackoverflow.com/a/46855138
has comment: http://stackoverflow.com/comment/80673560
accepted answer of: http://stackoverflow.com/q/46854054
has comment: http://stackoverflow.com/comment/80674585
answers question: http://stackoverflow.com/q/46854054
has body: I would need more details to be sure, but I believe that some sort of fft algorithm would be required. Perhaps try something from numpy.fft or from scipy fft implementations. Both of those would need some love to convert amplitude to dB, but it seems possible.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/53861261
accepted answer of: http://stackoverflow.com/q/46822423
has comment: http://stackoverflow.com/comment/94592763
answers question: http://stackoverflow.com/q/46822423
has comment: http://stackoverflow.com/comment/94574943
downvote count: 2
has comment: http://stackoverflow.com/comment/94574902
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116704107
upvote count: 9
has comment: http://stackoverflow.com/comment/94573953
has comment: http://stackoverflow.com/comment/94596445
type: Answer
has comment: http://stackoverflow.com/comment/122172315
has body: Keep things simple, and use a function: def query_with_all(data_frame, query_string): if query_string == "all": return data_frame return data_frame.query(query_string) Whenever you need to use this type of query, just call the function with the data frame and the query string. There's no need to use any extra if statements or subclass pd.Dataframe. If you're restricted to using df.query, you can use a global variable ALL = slice(None) df.query('@ALL', engine='python') If you're not allowed to use global variables, and if your DataFrame isn't MultiIndexed, you can use df.query('tuple()') All of these will property handle NaN values.
score: 7
has comment: http://stackoverflow.com/comment/94596385

http://stackoverflow.com/q/46774120
has comment: http://stackoverflow.com/comment/80494224
score: 2
tagged with: file-rename
has answer: http://stackoverflow.com/a/46774232
type: Question
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/46774306
has answer: http://stackoverflow.com/a/46774732
answer count: 3
linked to: http://stackoverflow.com/q/19416456
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/80494117
has comment: http://stackoverflow.com/comment/80494174
has body: I have a problem with my code The purpose of this code is to download a csv file (which called history.csv) and rename this file to the original name which I use selenium to fetch it out of the web page. the first issue here is selenium slowness while loading the web page. the second issue is the code stopped after downloading and renaming the first 2 or 3 links of the links list. here is the event list https://drive.google.com/file/d/0B5bJvxM9TZkhYXZOSnRDVnhTbFk/view?usp=sharing from selenium import webdriver import os events = open('events.txt', 'r') for event in events: driver = webdriver.Chrome() driver.get(event) download = driver.find_element_by_xpath('//*[@id="fxec_historytable"]/a').click() lname = driver.find_element_by_xpath('//*[@id="fxit-h1title"]') lname = lname.text lname = lname.replace('\n', '') name = str(lname) print(name) path = "C:\\Users\\Sayed\\Downloads" os.chdir(path) print(os.getcwd()) for file in os.listdir(path): fileName, fileExt = os.path.splitext(file) nname = '{}{}'.format(name, fileExt) os.rename(file, nname) an the error is C:\Users\Sayed\Anaconda3\python.exe C:/Users/Sayed/PycharmProjects/Tutorial/us.py Services Sentiment -European Monetary Union C:\Users\Sayed\Downloads ZEW Survey - Economic Sentiment -European Monetary Union C:\Users\Sayed\Downloads Traceback (most recent call last): File "C:/Users/Sayed/PycharmProjects/Tutorial/us.py", line 21, in os.rename(file,nname) FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'Services Sentiment -European Monetary Union.csv' -> 'ZEW Survey - Economic Sentiment -European Monetary Union.csv'
has comment: http://stackoverflow.com/comment/80494230
upvote count: 2
type: UnansweredQuestion
tagged with: selenium
has title: python download & rename

http://stackoverflow.com/a/46904516
type: AcceptedAnswer
has body: Strings in python are immutable. All these repeated string addition operations are wasteful, because new memory and objects must be allocated and created, and data copied - at each iteration. I'd suggest putting everything inside a list and calling str.join at the end. xml_artefacts = [] for row in data: xml_artefacts.append("&lt;Row&gt;\n") for item in headers: xml_artefacts.append(getCellString(row[item])) xml_artefacts.append("&lt;/Row&gt;\n") xml_artefacts.append('''&lt;/Table&gt; ... &lt;/Workbook&gt;''') Now, perform concatenation with the xml string. xml += ''.join(xml_artefacts)
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/46904406
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46904406

http://stackoverflow.com/comment/80534144
type: AnswerComment
comment on: http://stackoverflow.com/a/46771174
score: 0
type: Comment
has text: You mean not having the `0`s in the template? I purpousely deleted them from there. The default dict with `int` as the default function already initiates them to 0. In your actual case using `[0, 0, 0].copy` as the default copy does the same but with the 3 arguments you are using now.

infrastructure
tags question: http://stackoverflow.com/q/46827233
type: Tag
tag name: infrastructure

http://stackoverflow.com/q/46869343
tagged with: linux
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80687352
score: 2
has comment: http://stackoverflow.com/comment/86011491
answer count: 0
type: Question
has body: I am running Raspbian Linux on a Raspberry Pi, and I have both python, python3, and pip installed. When I run sudo pip install pillow, I get a very large output of code. The first error is Failed building wheel for pillow, after which is says that it failed to build pillow and will install pillow. At the very end of the code, I have this error in red: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-Yhx8TM/pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.rea d().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-yjhZ83-record/install-record.txt --single-version-externally-m anaged --compile" failed with error code 1 in /tmp/pip-build-Yhx8TM/pillow/ I have been following the installation instructions from https://pillow.readthedocs.io/en/latest/installation.html and have not found a solution there. I haven't found any similar errors online yet. UPDATE: I have tried installing cython, updating gcc and g++. I have also tried running python -m pip install pillow. I have tried installing django through pip, and I get this as an error: Exception: Traceback (most recent call last): File "/home/pi/.local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/pi/.local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/pi/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/pi/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/pi/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/pi/.local/lib/python2.7/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/pi/.local/lib/python2.7/site-packa…
has comment: http://stackoverflow.com/comment/80687156
has comment: http://stackoverflow.com/comment/80686868
has comment: http://stackoverflow.com/comment/80685924
has title: Error installing pip on linux
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80685891

http://stackoverflow.com/q/46787474
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80521239
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46787995
score: -1
has answer: http://stackoverflow.com/a/46787733
possible better answer: http://stackoverflow.com/a/46787995
answer count: 2
upvote count: 0
has title: Read data from XML using python
has body: I have data received from web like this: OK 2017-10-17 03:25:57:000 AA 102 48.86 Any Help how to read it. for example get 'OK' ,... Also 'AA' Thanks in advance. I have tried: import xml.etree.ElementTree as ET data1 = ET.fromstring(data) ok = data1.get('status')
favorite count: 0
has comment: http://stackoverflow.com/comment/80521808
accepted answer: http://stackoverflow.com/a/46787733
has comment: http://stackoverflow.com/comment/80521172
tagged with: python

http://stackoverflow.com/a/46862264
score: 0
has body: you can change file association which controls what to do when invoking filename in command line. For instance, when you just type text filename in cmd, notepadd will be opened, for word docs Word or other document editor. Have a look into following link from google or you can fiddle by yourself starting from Control Panel > Control Panel Home > Default Programs > Set Associations. Select a file type in the list and click Change Program. Alternatively,you can use any of Python IDE (PyCharm,PyDev etc.) so you will be able to run directly scripts from editor.
answers question: http://stackoverflow.com/q/46862147
type: Answer

http://stackoverflow.com/a/46869944
type: Answer
has comment: http://stackoverflow.com/comment/80688096
has comment: http://stackoverflow.com/comment/80688306
has comment: http://stackoverflow.com/comment/80688113
has comment: http://stackoverflow.com/comment/80687927
has comment: http://stackoverflow.com/comment/80688186
has comment: http://stackoverflow.com/comment/80687724
has comment: http://stackoverflow.com/comment/80687967
has comment: http://stackoverflow.com/comment/80688079
has comment: http://stackoverflow.com/comment/80688249
has comment: http://stackoverflow.com/comment/80688029
has comment: http://stackoverflow.com/comment/80687766
has comment: http://stackoverflow.com/comment/80688146
has comment: http://stackoverflow.com/comment/80688273
score: 0
has comment: http://stackoverflow.com/comment/80687755
has comment: http://stackoverflow.com/comment/80687944
has comment: http://stackoverflow.com/comment/80687911
has comment: http://stackoverflow.com/comment/80687845
answers question: http://stackoverflow.com/q/46869776
has body: Success url of Identity_unique_Update does not contain pk: success_url = reverse_lazy('Identity_nest_list') Change it to: def get_success_url(self): return reverse('nesting:Identity_nest_list', kwargs={'pk': self.object.pk})

http://stackoverflow.com/q/46853104
tagged with: python
has title: Can This Solution to the Google Foobar "Re-ID" be more efficient?
score: 2
has comment: http://stackoverflow.com/comment/117814332
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/59502184
favorite count: 0
has body: I'm looking for guidance on a better way to solve Google's Re-ID problem. Instead of typing out the "Re-ID" description here, I will simply list the pertinent parts: There are 10,000 "Minions" each of which are assigned an integer randomly between 0 and 10000 inclusive. The Minion will look up his integer as an index in a string of concatenated prime numbers - i.e. 2357111317192329... His new "ID" is generated by finding the index value in the string according to the Minion's integer assignment and concatenating the next 4 numbers with it - i.e. if the Minion's integer assignment is 3 his new ID would be 71113 (7 is the value at index 3 of the string, then we add the next 4 digits/characters) To solve this I: Utilized (thanks again, SO) a function to identify if a number is prime or not: is_prime() Generated a string of all prime numbers concatenated together which facilitates a Minion with assignment "10000" plus the next 4 characters. Created a function to generate the new ID based on the Minion's assignment and the string of concatenated values: answer() import math def is_prime(n): if n % 2 == 0 and n &gt; 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) primes = '' for i in range(2,21000,1): if len(primes) &lt; 10005: if is_prime(i): primes = primes + str(i) else: break def answer(n): re_id = primes[n:n+5:1] return(re_id) Areas of possible improvement The 21000 in my for loop is completely arbitrary. By trial and error I found 21,000 facilitates a Minion integer assignment of 10000 plus the 5 additional digits/characters. Is it necessary to create this long string of concatenated prime numbers before hand? Could it not be done dynamically based on the Minion ID? Thanks for your insights. Happy Friday.
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/46884402
tagged with: regex
has body: Input : ['TotalAmt', 'ProgramServicesAmt', 'Desc'] Expected Output : ['Total Amt', 'Program Services Amt', 'Desc'] I am using : &gt;&gt;&gt; import re &gt;&gt;&gt; data = ['TotalAmt', 'ProgramServicesAmt', 'Desc'] &gt;&gt;&gt; re.findall('[A-Z][^A-Z]*', data) Edit : Error : expected string or buffer Request Method: GET Request URL: http://localhost:8002/data?ein=132618801 Django Version: 1.11.5 Exception Type: TypeError Exception Value: expected string or buffer Edit 2: Use this also, but same error exist re.sub( r"([A-Z])", r" \1", ['TotalAmt', 'ProgramServicesAmt', 'Desc']).split()
answer count: 4
accepted answer: http://stackoverflow.com/a/46884576
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80716035
score: 1
has comment: http://stackoverflow.com/comment/80716033
linked to: http://stackoverflow.com/q/2277352
has answer: http://stackoverflow.com/a/46884698
type: Question
has answer: http://stackoverflow.com/a/46884576
possible better answer: http://stackoverflow.com/a/46884490
downvote count: 2
has title: Python - How to split array of strings at uppercase letters?
has answer: http://stackoverflow.com/a/46884490
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/80716231
upvote count: 3
has comment: http://stackoverflow.com/comment/80716106
has answer: http://stackoverflow.com/a/46884882
has comment: http://stackoverflow.com/comment/80716004
has comment: http://stackoverflow.com/comment/135938243
tagged with: python

http://stackoverflow.com/comment/80541170
comment on: http://stackoverflow.com/a/46797005
type: AnswerComment
score: 0
type: Comment
has text: I think this is close to what I want but the order of the columns is not exaclty what I want. I need to have it be ordered A_x A_y B_x B_y... and so on. Is there any way to sort the columns that way? maybe a sort function on top of this?

http://stackoverflow.com/a/46885272
has comment: http://stackoverflow.com/comment/80718280
has comment: http://stackoverflow.com/comment/80719188
downvote count: 0
answers question: http://stackoverflow.com/q/46885157
type: Answer
has body: You don't have an else suite for your if statement. Your if statement does nothing (it uses pass when the test is true, skipped otherwise). You do have an else suite for the for loop: for entry in wordlist_1: # ... else: matches.append(found_difference) A for loop can have an else suite as well; it is executed when a loop completes without a break statement. So when your for loop completes, the current value for found_difference is appended; so whatever was assigned last to that name. Fix your indentation if the else suite was meant to be part of the if test: for entry in wordlist_1: found_difference = binary_search(sorted_list=wordlist_2, element=entry) if entry == found_difference: pass else: matches.append(found_difference) However, you shouldn't use a pass statement there, just invert the test: matches = [] for entry in wordlist_1: found_difference = binary_search(sorted_list=wordlist_2, element=entry) if entry != found_difference: matches.append(found_difference) Note that the variable name matches feels off here; you are appending words that are missing in the other list, not words that match. Perhaps missing is a better variable name here. Note that your binary_search() function always returns element, the word you searched on. That'll always be equal to the element you passed in, so you can't use that to detect if a word differed! You need to unindent that last return line and return False instead: def binary_search(sorted_list, element): """Search for element in list using binary search. Assumes sorted list""" matches = [] index_start = 0 index_end = len(sorted_list) while (index_end - index_start) &gt; 0: index_current = (index_end - index_start) // 2 + index_start if element == sorted_list[index_current]: return True elif element &lt; sorted_list[index_current]: index_end = index_current elif element &gt; sorted_list[index_current]: index_start = index_current + 1 return False Now you can use a list comprehension in your wordfile_differences_binarysearch(…
has comment: http://stackoverflow.com/comment/80718469
has comment: http://stackoverflow.com/comment/80718979
has comment: http://stackoverflow.com/comment/80718352
has comment: http://stackoverflow.com/comment/80718315
has comment: http://stackoverflow.com/comment/80718972
has comment: http://stackoverflow.com/comment/80718225
has comment: http://stackoverflow.com/comment/80718409
has comment: http://stackoverflow.com/comment/80720425
has comment: http://stackoverflow.com/comment/80718802
has comment: http://stackoverflow.com/comment/80718531
has comment: http://stackoverflow.com/comment/80719459
has comment: http://stackoverflow.com/comment/80718168
has comment: http://stackoverflow.com/comment/80719069
has comment: http://stackoverflow.com/comment/80719334
score: 4
has comment: http://stackoverflow.com/comment/80719011
upvote count: 4
has comment: http://stackoverflow.com/comment/80718544

http://stackoverflow.com/comment/80743737
type: QuestionComment
comment on: http://stackoverflow.com/q/46897468
has text: Expected result is for a word to return a certain score - like scrabble. I was working on something like: `def scrabble_score(word): result = 0 print(word) for c in word: for value in score: if c == value: result += sum(score.values()) return result ` #iterate through all chars in the word, then iterate through the keys in score, if the key matched the char it would add the value of that key to result ^ my code does not work but it seems(to me) like reasonably sound logic?
score: 0
type: Comment

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/46777919
tags question: http://stackoverflow.com/q/46853511
type: Tag

http://stackoverflow.com/q/46876770
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46876958
has comment: http://stackoverflow.com/comment/80700779
has answer: http://stackoverflow.com/a/53172593
downvote count: 1
has comment: http://stackoverflow.com/comment/80700836
has body: Suppose I have a string of the of the format host:port, where :port is optional. How can I reliably extract the two components? The host can be any of: A hostname (localhost, www.google.com) An IPv4 literal (1.2.3.4) An IPv6 literal ([aaaa:bbbb::cccc]). In other words, this is the standard format used across the internet (such as in URIs: complete grammar at https://www.rfc-editor.org/rfc/rfc3986#section-3.2, excluding the "User Information" component). So, some possible inputs, and desired outputs: 'localhost' -> ('localhost', None) 'my-example.com:1234' -> ('my-example.com', 1234) '1.2.3.4' -> ('1.2.3.4', None) '[0abc:1def::1234]' -> ('[0abc:1def::1234]', None)
has answer: http://stackoverflow.com/a/70294442
type: Question
has comment: http://stackoverflow.com/comment/80701086
accepted answer: http://stackoverflow.com/a/46880067
possible better answer: http://stackoverflow.com/a/53172593
score: 12
has answer: http://stackoverflow.com/a/46877297
answer count: 7
has title: How can I parse a host:port pair in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/80700817
has answer: http://stackoverflow.com/a/46877092
has answer: http://stackoverflow.com/a/46877220
has comment: http://stackoverflow.com/comment/80700553
tagged with: python
has answer: http://stackoverflow.com/a/46880067
has comment: http://stackoverflow.com/comment/80700748
upvote count: 13

http://stackoverflow.com/comment/80686391
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46869454
has text: Do you mean to have different tuples/lists for each interval between the 'start' and 'end' signal words? I can edit it to reflect this change.
type: AnswerComment

http://stackoverflow.com/comment/80603712
comment on: http://stackoverflow.com/q/46828093
score: 0
has text: Or, if you are on python 3: `super().count`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46869566
answers question: http://stackoverflow.com/q/46869405
has comment: http://stackoverflow.com/comment/80686390
has comment: http://stackoverflow.com/comment/80686757
has comment: http://stackoverflow.com/comment/80686455
score: 0
type: AcceptedAnswer
has body: Change inside authenticate(request): redirect_uri = request.build_absolute_uri(reverse('shopify_app:shopify_app_finalize'))
has comment: http://stackoverflow.com/comment/80686404
has comment: http://stackoverflow.com/comment/80686344
has comment: http://stackoverflow.com/comment/80686353
type: Answer
has comment: http://stackoverflow.com/comment/80686503
accepted answer of: http://stackoverflow.com/q/46869405
has comment: http://stackoverflow.com/comment/80686938

http://stackoverflow.com/q/46841488
answer count: 2
tagged with: sympy
score: 3
downvote count: 0
has title: Sympy and Wolframalpha give different result
has answer: http://stackoverflow.com/a/46841911
tagged with: wolframalpha
favorite count: 0
type: UnansweredQuestion
tagged with: integral
tagged with: python
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/46859767
has body: Sympy and wolframalpha have produced different result. Have done anything obviously wrong here? import sympy as smp smp.init_printing() In [2]: a,R,t = smp.symbols('a,R,t',real=True) In [3]: f = t**2/(1+t**2/a**2);f Out[3]: In [4]: I=smp.Integral(f,t); I Out[4]: In [5]: I.doit() Out[5]: a2t Wolframalpha gives however
has comment: http://stackoverflow.com/comment/80630912

http://stackoverflow.com/comment/122152049
comment on: http://stackoverflow.com/a/64588611
type: Comment
has text: I had to deal with a dataset of roughly 100k rows. If you want to compare they all each other, you know that the number of possible partners of N rows are N*(N-1)/2, it means, 5*(10**9) possible combinations. So, I recommend you group by son features that you think are quite representative for isolate small groups of rows, and apply this thecnique to those groups.
type: AnswerComment
score: 0

http://stackoverflow.com/a/46893146
has body: If you say the three parts exist all the time we can use np.diff() with argmax() by converting the True &amp; False values to int i.e def gfi_third(x): return (np.diff(x.astype(int)) &gt; 0).argmax() + 1 Sample runs : three_parts_list = np.array([True, False, False, False, False, False,True, True]) three_parts_list2 = np.array([True, False, False, False, True, True,True, True]) gfi_third(three_parts_list) 6 gfi_third(three_parts_list2) 4
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46891502
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46891502

http://stackoverflow.com/q/46834412
tagged with: django
has title: Insert data to sqlite3 - python - django
type: Question
accepted answer: http://stackoverflow.com/a/46834750
tagged with: database
score: 0
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/46834750
tagged with: python
type: AnsweredQuestion
has body: I'm new to django framework. I parsed data from WebAPI server to dict: key is product buys and value is list that contains info about product. Code: def get_best_products(self): dict_of_items = {} for x in range (0, self.max_range): itemId = self.fresh_data.item[x].itemId itemTitle = self.fresh_data.item[x].itemTitle photoUrl = self._get_main_item_photo(x) itemPrice = self._get_item_price(x) dict_of_items[self.fresh_data.item[x].bidsCount] = [itemId, itemTitle, itemPrice, photoUrl] return self._sort_parsed_item_data(dict_of_items) def _sort_parsed_item_data(self, data): return OrderedDict(sorted(data.items(), reverse=True, key=lambda t: t[0])) So i have dict of sorted items by product buys with info as value. What is best way to put this data to database? Should i build a model? And if yes how to do it? any tips? On internet i can find examples of models that allows to edit data... or "how to build mail registration". I want to make a model that shows all the data in a table from all the auctions but i dont want to add more. I want to have only 100 records and they will be updated when a buys change. (and maybe later when i build table that table i will try to do... lets say you click on "itemID" it will take you to edit manager, where you can change what you want about that specyfic record). Is it possible to do with django? or if i want to update just 100 records without change i should just use SQL commands, becouse it seems to be easier? All the examples i saw allows to edit data and add data.... i want to prevent it for now. But.... Am I allowed to "play" with database without django models when i'm using this framework? That's the main question

http://stackoverflow.com/a/46902479
score: 3
has comment: http://stackoverflow.com/comment/80765319
downvote count: 0
has body: You can save time.clock in a variable first_instance = time.clock() if (time.clock &gt; first_instance + 10):
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/46902433

http://stackoverflow.com/q/46902226
type: Question
has comment: http://stackoverflow.com/comment/80751344
has comment: http://stackoverflow.com/comment/80751223
has title: List comprehension to Modify a List
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80751271
tagged with: python
has answer: http://stackoverflow.com/a/46902279
tagged with: list
has body: I'm trying to modify values in a list of list via list comprehension. I'm stuck on how to implement this though when creating the inner list (please see modify_word(j) line below). #loop through each tweet for i in all_data: #loop through each word of each tweet for j in i: #find the values we're interested in if j not in set(all_cities) and meets_criteria(j): #here is where I want to make a list of the modified word for each iteration of i (tweet) modify_word(j) I failed miserably with this: new_data = [[modify_word(j) if (meets_criteria(j) and j not in set(all_cities)) for j in i] for i in all_data] Anyone have an idea on how I might be able to do this? Thanks as always.
has comment: http://stackoverflow.com/comment/80751299

http://stackoverflow.com/a/46843776
upvote count: 1
answers question: http://stackoverflow.com/q/46835602
score: 1
accepted answer of: http://stackoverflow.com/q/46835602
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80656105
has body: There are multiple problems in your code, and many of them could cause the network not to train properly: You are initializing the weights and biases with a zero value. It should be initialized with a small random value (uniform or normally distributed). There are no activation functions in your network, making it only able to model only linear relationships. The learning rate is fixed, this is a hyper-parameter that you have to tune. You also have to monitor the value of the loss function during training, to make sure that it is decreasing and then converging to a small value. If its not then you should not look at the outputs, as the network is not learning anything. Also, if you are not normalizing the inputs and outputs, you should also do so.
type: Answer

http://stackoverflow.com/comment/80660696
type: QuestionComment
has text: The Question I asked was answered by answers given. But this did not solve my actual problem. One of the answers gave me the right hint where to search for the underlying problem (I changed the accepted answer from there to the question which answers the actual question to minimize confusion). And I removed the answer I stated in the question. Hope you guys are fine with those explanations and decisions.
score: 0
comment on: http://stackoverflow.com/q/46852887
type: Comment

http://stackoverflow.com/q/46850620
tagged with: mean
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80649160
downvote count: 0
has body: I just pick up pandas. I have a dataframe as follow: DEST MONTH PRICE SOUR TYPE YEAR 0 DEST7 8 159 SOUR4 WEEKEND 2015 1 DEST2 9 391 SOUR1 WEEKEND 2010 2 DEST5 5 612 SOUR1 WEEKDAY 2013 3 DEST4 10 836 SOUR4 WEEKEND 2013 4 DEST4 4 689 SOUR3 WEEKEND 2013 5 DEST7 3 862 SOUR4 WEEKDAY 2014 6 DEST4 5 483 SOUR4 WEEKEND 2016 7 DEST2 2 489 SOUR3 WEEKEND 2017 8 DEST4 7 207 SOUR1 WEEKDAY 2012 9 DEST3 11 374 SOUR2 WEEKDAY 2015 10 DEST1 2 959 SOUR2 WEEKEND 2017 11 DEST5 10 969 SOUR3 WEEKDAY 2011 12 DEST8 3 645 SOUR4 WEEKEND 2013 13 DEST6 7 258 SOUR4 WEEKEND 2013 14 DEST8 5 955 SOUR4 WEEKDAY 2010 15 DEST1 3 568 SOUR4 WEEKEND 2013 16 DEST5 5 601 SOUR4 WEEKDAY 2016 17 DEST1 6 159 SOUR3 WEEKDAY 2011 18 DEST3 11 322 SOUR4 WEEKDAY 2013 19 DEST2 10 103 SOUR2 WEEKDAY 2012 I've put the code below, feel free to generate your own random dataframe: import pandas as pd import random import numpy as np df= pd.DataFrame({"YEAR": np.random.choice([2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017], 20, replace=True), "MONTH": np.random.choice([_ for _ in range(1, 13)], 20, replace=True), "TYPE": np.random.choice(['WEEKDAY', 'WEEKEND'], 20, replace=True), "SOUR": np.random.choice(['SOUR1', 'SOUR2', 'SOUR3', 'SOUR4'], 20, replace=True), "DEST": np.random.choice(['DEST1', 'DEST2', 'DEST3', 'DEST4','DEST5', 'DEST6', 'DEST7', 'DEST8'], 20, replace=True), "PRICE": np.random.choice([_ for _ in range(100, 999)], 20, replace=True)}) print(df) I want to generate min, max, mean, median, ...as new columns, add those columns to the dataframe. This is the aggregation code I tried: aggregation={ "PRICE": { "MIN": lambda x: x.min(skipna=True), "MAX":lambda x: x.max(skipna=True), "MEDIAN":lambda x: x.median(skipna=True), "MEAN":lambda x:x.mean(skipna=True) } } df1=df.groupby(["YEAR","MONTH","TYPE","SOUR","DEST"]).agg(aggregation).reset_index() df1 But the output doesn't calculate any min, max, median, mean at all: YEAR MONTH TYPE SOUR DEST PRICE MIN MAX MEDIAN MEAN 0 2010 5 WEEKDAY SOUR4 DEST8 955 955 955 955 1 2010…
accepted answer: http://stackoverflow.com/a/46850834
favorite count: 0
tagged with: pandas-groupby
type: Question
has answer: http://stackoverflow.com/a/66081548
has title: How can we use pandas to generate min, max, mean, median, ...as new columns for the dataframe?
score: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/66081548
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/46850834
has comment: http://stackoverflow.com/comment/80649580
tagged with: autogeneratecolumn
tagged with: min

http://stackoverflow.com/comment/80609091
comment on: http://stackoverflow.com/q/46830743
has text: You could check each string against the [regular expression](https://en.wikipedia.org/wiki/Regular_expression) `[ab]*bbb[ab]*`.
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46829329
tagged with: formatting
has answer: http://stackoverflow.com/a/46829386
type: Question
tagged with: replace
has comment: http://stackoverflow.com/comment/80606073
answer count: 2
upvote count: 1
has body: I have a DataFrame called user_logs with msno as key msno date num_25 num_50 num_75 num_985 num_100 num_unq total_secs rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34= 20150513 0 0 0 0 0 1 1 280.335 rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34= 20150709 9 1 0 0 0 1 1 280.335 yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8= 20150105 3 3 0 0 0 1 1 280.335 yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8= 20150306 1 0 0 0 0 1 1 280.335 yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8= 20150501 3 0 0 0 38 38 9649.029 The date column is in int and I would like to have it as a datetime format but I'm completely stuck. I only got as fare as to create a new variable where I actually succedded in formatting into dates: Dates = pd.DataFrame([datetime.strptime(format(d, '.0f'), '%Y%m%d') for d in user_logs.loc[: , 'date']]) But I have a feeling that using DataFrame.replace might be usefull?
favorite count: 0
accepted answer: http://stackoverflow.com/a/46829356
tagged with: python
has title: Replace int with date in DataFrame column
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46829356
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/46829386

http://stackoverflow.com/a/46852244
score: 0
has comment: http://stackoverflow.com/comment/80654801
answers question: http://stackoverflow.com/q/46851780
has comment: http://stackoverflow.com/comment/80654294
has body: As I said in the comments, executing / evaluating arbitrary strings is a security risk. But if you really want to do this, you need to pass exec an appropriate globals dict. The natural choice here is to pass it the globals() dict, so that whatever names your exec defines get put into the global namespace. def test(argstring): exec(argstring, globals()) print(main()) function_string = 'def main():\n\treturn(1)' test(function_string) print(main) typical output 1 &lt;function main at 0xb7196cd4&gt;
type: Answer
has comment: http://stackoverflow.com/comment/80654208

http://stackoverflow.com/q/46796451
has body: I can create a simple columnar diagram in a matplotlib according to the 'simple' dictionary: import matplotlib.pyplot as plt D = {u'Label1':26, u'Label2': 17, u'Label3':30} plt.bar(range(len(D)), D.values(), align='center') plt.xticks(range(len(D)), D.keys()) plt.show() But, how do I create curved line on the text and numeric data of this dictionarie, I do not know? Т_OLD = {'10': 'need1', '11': 'need2', '12': 'need1', '13': 'need2', '14': 'need1'} Like the picture below
has answer: http://stackoverflow.com/a/46797009
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46796884
has answer: http://stackoverflow.com/a/46797395
tagged with: python-3.x
type: Question
tagged with: python
tagged with: dictionary
tagged with: plot
score: 0
tagged with: matplotlib
answer count: 3
has title: Draw a plot in which the Y-axis text data (not numeric), and X-axis numeric data

http://stackoverflow.com/comment/91324276
type: Comment
has text: For python 2.7 I had to add to modify the HMAC def to return hmac.new(str(key), str(message), hashlib.sha256)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46800349

http://stackoverflow.com/a/46777632
has comment: http://stackoverflow.com/comment/80501569
answers question: http://stackoverflow.com/q/46777600
has comment: http://stackoverflow.com/comment/80501729
has comment: http://stackoverflow.com/comment/80501576
has comment: http://stackoverflow.com/comment/80501349
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/46777600
has body: You can't just read from a file twice. sum(1 for row in data) already read all the data, so data = list(data) is an empty list, because the file pointer is at the end of the file and won't return more data unless you rewind the file to the start. You don't even need to use the sum() call, remove it. You can get the same count with len(data) after you used list() on it: with open('C:\Users\Administrator\Desktop\python test\update_test\datalog.csv','rb') as csvfile: data= csv.reader(csvfile) data = list(data) text = data[0][0] print(text) print len(data)

tcp
type: Tag
tags question: http://stackoverflow.com/q/46894768
tags question: http://stackoverflow.com/q/46833561
tags question: http://stackoverflow.com/q/46785946
tags question: http://stackoverflow.com/q/46902071
tags question: http://stackoverflow.com/q/46787160
tags question: http://stackoverflow.com/q/46751804
tags question: http://stackoverflow.com/q/46790250
tags question: http://stackoverflow.com/q/46855865
tags question: http://stackoverflow.com/q/46860663
tag name: tcp
tags question: http://stackoverflow.com/q/46782505
tags question: http://stackoverflow.com/q/46840479

http://stackoverflow.com/a/46834750
has body: The better way to use Django is using the models, basically Django works on base in something called ORM, Object-Relational mapping, that allows to you work with databases using Classes (models). For more information about how to use it read the docs that Django provide in this tutorial https://docs.djangoproject.com/en/1.11/intro/tutorial01/
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80622111
type: Answer
has comment: http://stackoverflow.com/comment/80621586
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46834412
score: 1
answers question: http://stackoverflow.com/q/46834412

http://stackoverflow.com/q/46763675
score: -4
has comment: http://stackoverflow.com/comment/80478321
favorite count: 0
has answer: http://stackoverflow.com/a/46763851
type: Question
has comment: http://stackoverflow.com/comment/80472715
tagged with: python
possible better answer: http://stackoverflow.com/a/46763845
has answer: http://stackoverflow.com/a/46763845
has comment: http://stackoverflow.com/comment/80472526
answer count: 2
has body: from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver class LoginPage(): def __init__(self, driver): self.driver = driver def get_username_textbox(self): try: return self.driver.find_element_by_id('email') except: return None def get_password_textbox(self): try: return self.driver.find_element_by_id('pass') except: return None def get_login_button(self): try: return self.driver.find_element_by_id("loginbutton") except: return None def wait_for_login_page(self): wait = WebDriverWait(self.driver, 30) element = self.driver.title("Facebook – log in or sign up") wait.until(EC.title_is(element))
tagged with: selenium
accepted answer: http://stackoverflow.com/a/46763851
downvote count: 4
has title: Getting TypeError: 'str' object is not callable
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/46856483
type: Answer
downvote count: 0
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46853383
has body: When you use QtGui.QCursor.pos() is getting the coordinates of the cursor with respect to the screen, but when you want to paint a widget you must be in the coordinates of the widget, for it the widget has the mapToGlobal() method: self.mapFromGlobal(QtGui.QCursor.pos()) But in this case there is another solution, you must use the event that returns mouseReleaseEvent that has the information in the pos() method: cursor_event.pos() Another problem is that the label you created is above the widget so you do not see the points, the easiest thing is to draw the QPixmap directly with the drawPixmap() method. Complete code: from PyQt5 import QtWidgets, QtGui, QtCore class ImageScroller(QtWidgets.QWidget): def __init__(self): self.chosen_points = [] QtWidgets.QWidget.__init__(self) self._image = QtGui.QPixmap("image.png") def paintEvent(self, paint_event): painter = QtGui.QPainter(self) painter.drawPixmap(self.rect(), self._image) pen = QtGui.QPen() pen.setWidth(20) painter.setPen(pen) painter.setRenderHint(QtGui.QPainter.Antialiasing, True) painter.drawPoint(300, 300) painter.drawLine(100, 100, 400, 400) for pos in self.chosen_points: painter.drawPoint(pos) def mouseReleaseEvent(self, cursor_event): self.chosen_points.append(cursor_event.pos()) # self.chosen_points.append(self.mapFromGlobal(QtGui.QCursor.pos())) self.update() if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = ImageScroller() w.resize(640, 480) w.show() sys.exit(app.exec_())
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46853383

http://stackoverflow.com/comment/80512432
score: 0
has text: Yes. Thats because, inside a pipeline (most probably due to gridSearchCV), the type of X is changed from Dataframe to numpy array which dont have any index or columns with it. Hence doing this will give errors>
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46781448

http://stackoverflow.com/comment/80569539
comment on: http://stackoverflow.com/q/46810824
has text: tried but gives clipboard error: https://github.com/lucasmazza/copy-as-rtf/blob/master/lib/winclipcopy.py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80544631
has text: Which user had the second answer?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46798828

http://stackoverflow.com/q/46782232
has title: How can I serve Html pages in twisted/python?
type: Question
tagged with: twisted
answer count: 1
has body: My twisted/python webservice runs on port 8080. I have client.html page for to be visible for initial GET request fro port 8080. (ie: localhost:8080) From that html I have linked other html pages. How can I register a folder and provide that link in my client html page to open those linked html pages? my twisted app is; class Root(resource.Resource): isLeaf = False responseContent = "Lob Cache" def getChild(self, name, request): return self def render_GET(self, request): return self.returnResponse(request) def render_POST(self, request): return self.returnResponse(request) def returnResponse(self, request): f = open('clients.html', 'r') request.setHeader(b"content-type", b"text/html") return f.read() .... site = Root() site.putChild('cache', NetworkCacheManager()) endpoints.serverFromString(reactor, "tcp:port=8080:interface=0.0.0.0").listen(server.Site(site)) reactor.run() Currently my html pages and python script is in same folder location. I want to link other pages like; &lt;a href="http://localhost:8080/clientSiteinfo.html I can put other html pages in my webserver( apache webserver, but im getting cross domain issues)
has answer: http://stackoverflow.com/a/46782426
tagged with: python
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/81254185
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46829000
type: Comment
has text: Hey, thank you. My issue is resolved. I had not given root access to it.

http://stackoverflow.com/q/46787124
favorite count: 0
tagged with: face-detection
type: UnansweredQuestion
has body: How can I check for the location of an eye for example. Its in this function? eyes = eye_cascade.detectMultiScale(gray, 1.4, 7) How to read the input of this? i would like to calculate in a face detection program if on the picture for example a nose or an eye is the place as should be, in a human.
has answer: http://stackoverflow.com/a/46787484
tagged with: python
upvote count: 0
has title: Python OpenCV face detection
type: Question
tagged with: opencv
score: -1
downvote count: 1
answer count: 1
tagged with: computation

http://stackoverflow.com/comment/80471033
has text: You have nothing to apologize for. This is a stupid task and being assigned it is not your fault.
comment on: http://stackoverflow.com/q/46762884
score: 7
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80755779
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46904369
score: 0
has text: Just give us the whole url you want.

http://stackoverflow.com/a/46813360
type: Answer
has body: Do you mean like this? stars = "*" * (die_rolls.count(1) // 10) print("1: " + stars + " [" + str(die_rolls.count(1)) + " |", "{:.1f}".format(percent_one) + "%]") The // operator performs integer division, so 19//10 = 1, 20//10 = 2, 21//10 = 2, etc. Writing "*" * 2 makes Python repeat the string "*" twice.
accepted answer of: http://stackoverflow.com/q/46813252
answers question: http://stackoverflow.com/q/46813252
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80576431
score: 0

http://stackoverflow.com/comment/80736928
type: Comment
has text: Ok, but I cannot find such an example :-(
type: AnswerComment
comment on: http://stackoverflow.com/a/46893471
score: 0

http://stackoverflow.com/q/46885572
type: Question
has body: I built my own chatbot with Chatterbot library, but for local work. Now I want to build it for Telegram but when I try to install packages of Django with pip install django chatterbot, the Terminal shows me this: Requirement already satisfied: django in /Library/Python/2.7/site-packages Requirement already satisfied: chatterbot in /Library/Python/2.7/site-packages Requirement already satisfied: pytz in /Library/Python/2.7/site-packages (from django) Collecting python-dateutil&lt;2.7,&gt;=2.6 (from chatterbot) Using cached python_dateutil-2.6.1-py2.py3-none-any.whl Requirement already satisfied: nltk&lt;4.0,&gt;=3.2 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: python-twitter&lt;4.0,&gt;=3.0 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: pymongo&lt;4.0,&gt;=3.3 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: jsondatabase&lt;1.0.0,&gt;=0.1.7 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: chatterbot-corpus&lt;1.1,&gt;=1.0 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: sqlalchemy&lt;1.2,&gt;=1.1 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: six&gt;=1.5 in /Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg (from python-dateutil&lt;2.7,&gt;=2.6-&gt;chatterbot) Requirement already satisfied: requests-oauthlib in /Library/Python/2.7/site-packages (from python-twitter&lt;4.0,&gt;=3.0-&gt;chatterbot) Requirement already satisfied: future in /Library/Python/2.7/site-packages (from python-twitter&lt;4.0,&gt;=3.0-&gt;chatterbot) Requirement already satisfied: requests in /Library/Python/2.7/site-packages (from python-twitter&lt;4.0,&gt;=3.0-&gt;chatterbot) Requirement already satisfied: ruamel.yaml&lt;=0.15 in /Library/Python/2.7/site-packages (from chatterbot-corpus&lt;1.1,&gt;=1.0-&gt;chatterbot) Requirement already satisfied: oauthlib&gt;=0.…
answer count: 1
accepted answer: http://stackoverflow.com/a/46900508
score: 0
has comment: http://stackoverflow.com/comment/80719081
tagged with: python
has title: Django Chatterbot: installation
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46900508
tagged with: chatterbot

http://stackoverflow.com/a/46885971
answers question: http://stackoverflow.com/q/46885157
has comment: http://stackoverflow.com/comment/80719510
score: 1
upvote count: 1
has body: With sets Binary search is used to improve efficiency of an algorithm, and decrease complexity from O(n) to O(log n). Since the naive approach would be to check every word in wordlist1 for every word in wordlist2, the complexity would be O(n**2). Using binary search would help to get O(n * log n), which is already much better. Using sets, you could get O(n): american = """Amazon Americana Americanization Civilization""" british = """Amazon Americana Americanisation Civilisation""" american = {line.strip() for line in american.split("\n")} british = {line.strip() for line in british.split("\n")} You could get the american words not present in the british dictionary: print(american - british) # {'Civilization', 'Americanization'} You could get the british words not present in the american dictionary: print(british - american) # {'Civilisation', 'Americanisation'} You could get the union of the two last sets. I.e. words that are present in exactly one dictionary: print(american ^ british) # {'Americanisation', 'Civilisation', 'Americanization', 'Civilization'} This approach is faster and more concise than any binary search implementation. But if you really want to use it, as usual, you cannot go wrong with @MartijnPieters' answer. With two iterators Since you know the two lists are sorted, you could simply iterate in parallel over the two sorted lists and look for any difference: american = """Amazon Americana Americanism Americanization Civilization""" british = """Amazon Americana Americanisation Americanism Civilisation""" american = [line.strip() for line in american.split("\n")] british = [line.strip() for line in british.split("\n")] n1, n2 = len(american), len(british) i, j = 0, 0 while True: try: w1 = american[i] w2 = british[j] if w1 == w2: i += 1 j += 1 elif w1 &lt; w2: print('%s is in american dict only' % w1) i += 1 else: print('%s is in british dict only' % w2) j += 1 except IndexError: break for w1 in american[i:]: print('%s is in american dict only' % w1…
type: Answer
downvote count: 0

http://stackoverflow.com/q/46804799
tagged with: python
has answer: http://stackoverflow.com/a/46804977
downvote count: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80556768
has title: How to delete on square from json file in python?
has body: I have an extra last square } in a big json file, I need to remove it by using python : { "layers": { "frame": { "frame.interface_id": "0", "frame.encap_type": "127", "frame.time": "Oct 10, 2017 18:05:51.620568000 Central European Daylight Time", "frame.offset_shift": "0.000000000", "frame.time_epoch": "1507651551.620568000", "frame.time_delta": "0.324011000", "frame.time_delta_displayed": "0.324011000", "frame.time_relative": "29.248970000", "frame.number": "38", "frame.len": "64", "frame.cap_len": "64", "frame.marked": "0", "frame.ignored": "0", "frame.protocols": "wpan:6lowpan:ipv6:ipv6.hopopts:udp:data", "frame.coloring_rule.name": "UDP", "frame.coloring_rule.string": "udp" }, "wpan": { "wpan.frame_length": "66", "wpan.fcf": "0x0000dc41", "wpan.fcf_tree": { "wpan.frame_type": "0x00000001", "wpan.security": "0", "wpan.pending": "0", "wpan.ack_request": "0", "wpan.pan_id_compression": "1", "wpan.seqno_suppression": "0", "wpan.ie_present": "0", "wpan.dst_addr_mode": "0x00000003", "wpan.version": "1", "wpan.src_addr_mode": "0x00000003" }, "wpan.seq_no": "8", "wpan.dst_pan": "0x0000abcd", "wpan.dst64": "00:21:2f:3c:c6:b5:00:01", "wpan.src64": "00:21:2f:3c:c6:b5:00:7e", "wpan.fcs_ok": "1" }, "6lowpan": { "IPHC Header": { "6lowpan.pattern": "0x00000003", "6lowpan.iphc.tf": "0x00000003", "6lowpan.iphc.nh": "0", "6lowpan.iphc.hlim": "0x00000002", "6lowpan.iphc.cid": "1", "6lowpan.iphc.sac": "1", "6lowpan.iphc.sam": "0x00000003", "6lowpan.iphc.m": "0", "6lowpan.iphc.dac": "1", "6lowpan.iphc.dam": "0x00000003", "6lowpan.iphc.sci": "0x00000000", "6lowpan.iphc.dci": "0x00000000" }, "6lowpan.next": "0x00000000", "6lowpan.src": "::221:2f3c:c6b5:7e", "6lowpan.dst": "::221:2f3c:c6b5:1" }, "ipv6": { "ipv6.version": "6", "ip.version": "6", "ipv6.tclass": "0x00000000", "ipv6.tclass_tree": { "ipv6.tclass.dscp": "0", "ipv6.tclass.ecn": "0" }, "ipv6.flow": "0x00000000", "ipv6.plen": "39", "ipv6.nxt": "0", "ipv6.hlim": "64", "ipv6.src": "::221:2f3c:c6b5:7e", "ipv6.addr": "::221:2f3c:c6…
linked to: http://stackoverflow.com/q/33811688
upvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80556643
answer count: 1
score: -1

http://stackoverflow.com/comment/80713239
type: AnswerComment
comment on: http://stackoverflow.com/a/46882872
score: 0
type: Comment
has text: Actually, I do not think so. You cannot have the same error so please post you error.

http://stackoverflow.com/q/46899727
tagged with: python
has title: How can I use ModelChoiceField with Filter in Django 1.11?
has comment: http://stackoverflow.com/comment/80750719
answer count: 0
type: UnansweredQuestion
tagged with: django
has body: I have two models related, I wanna show them with a multiplechoicefield from django.forms but also I wanna that one model had assigned depends on the multiplechoicefield of the related model. class Model(models.Model): name = models....() .... class OtherModel(models.Model): name = models....() model = models.ForeignKey() In my form I have: class ModelAdminForm(forms.ModelForm): model = forms.MultipleChoiceField(queryset = model.objects.all()) other_model = forms.MultipleChoiceField(queryset = other_model.objects.all()) But I wanna do that other_model MultipleChoiceField show me objects only related with model related, how can I do that through queryset filter, or another way to do.
type: Question
has comment: http://stackoverflow.com/comment/80746685
tagged with: django-admin
score: 0

http://stackoverflow.com/comment/80457670
comment on: http://stackoverflow.com/q/46755990
score: 0
type: Comment
type: QuestionComment
has text: @Zero yes, ip is unique

http://stackoverflow.com/q/46760856
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/46761051
type: Question
has body: Using Python 3.6 I have the data shown below in an xml.etree.ElementTree, the xml output using minidom.toprettyxml is shown below. Before outputting to XML file I want to sort the Observation nodes using the PT attribute as the key. Whilst maintaining them in their correct Setup node. This is for human reading purposes so that "Observation"s to the same "PT" are next to each other for checking, and possibly editing manually. Thanks in advance for any help. <?xml version="1.0" ?> <Observation PT="SBDSE852S" HA="336.4813486486353" VA="87.14710969026532" SD="168.8937" TH="0.0" Face="F1" Time="2016-05-21T15:47:39.03"/> <Observation PT="SBTW801S" HA="260.9403472908128" VA="88.11265463299148" SD="224.61925" TH="0.0" Face="F1" Time="2016-05-21T15:49:05.02"/> <Observation PT="SBTW802S" HA="249.90718352859065" VA="88.20019946435063" SD="221.16645" TH="0.0" Face="F1" Time="2016-05-21T15:49:56.05"/> <Observation PT="SBZZ108R" HA="213.70079790293013" VA="87.84023471948807" SD="129.7161" TH="0.0" Face="F1" Time="2016-05-21T15:52:17.04"/> <Observation PT="SBGC210R" HA="131.9100549303175" VA="86.83200793760854" SD="31.1457" TH="0.0" Face="F1" Time="2016-05-21T15:56:24.08"/> <Observation PT="SBGC201R" HA="135.24920297621932" VA="87.42093979205845" SD="35.22585" TH="0.0" Face="F1" Time="2016-05-21T15:57:19.08"/> <Observation PT="SBGC300R" HA="341.0439328237202" VA="94.9602466892515" SD="16.3769" TH="0.0" Face="F1" Time="2016-05-21T15:58:31.03"/> <Observation PT="SBGC300R" HA="341.04415608692466" VA="94.96029050152956" SD="16.37675" TH="0.0" Face="F1" Time="2016-05-21T15:59:36.06"/> <Observation PT="SBGC301R" HA="38.42640483483226" VA="62.94180376378161" SD="7.64965" TH="0.0" Face="F1" Time="2016-05-21T16:00:30.00"/> <Observation PT="SBMOSI105S" HA="219.1574438207224" VA="86.35383331578822" SD="114.80255" TH="0.0" Face="F1" Time="2016-05-21T16:23:19.02"/> <Observation PT="SBGC300R" HA="325.74302017491317" VA="92.11049818613618" SD="47.7476" TH="0.0" Face="F1" Time="2016-05-21T16:24:4…
has title: Using Python to Sort Child nodes in ElementTree
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/80467251

http://stackoverflow.com/comment/80490500
has text: The data I'm working with IS on the form described in the problem - I would not write it this way myself. And there is a lot of it. The accepted answer is adequate for my situation, and is hence a solution for this case. Thanks for all the replies. It was very helpful.
score: 0
comment on: http://stackoverflow.com/q/46767597
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80602771
type: Comment
type: QuestionComment
has text: @ArpitGoyal Thanks for your response. So even though Django REST framework uses HTTP responses to communicate, it doesn't need to abide by HTTP protocol? I respect that REST and HTTP protocol are different.
comment on: http://stackoverflow.com/q/46826501
score: 0

physics
tags question: http://stackoverflow.com/q/46874594
tag name: physics
type: Tag
tags question: http://stackoverflow.com/q/46868717

http://stackoverflow.com/comment/80466142
has text: Nice one! ~ :-)
type: Comment
comment on: http://stackoverflow.com/a/46760055
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80753388
type: QuestionComment
has text: @Chengzhi how bout run it daily at 12:45pm, provided that current datetime is 2017-10-24 12:35pm. I expect to see it scheduling at "2017-10-24 12:45pm" (which means including today for testing), "2017-10-25 12:45pm", "2017-10-25 12:45pm", ...
score: 0
comment on: http://stackoverflow.com/q/46888213
type: Comment

http://stackoverflow.com/comment/80509193
score: 0
type: Comment
type: QuestionComment
has text: Yes, but I think it is just the first non encoded UTF-8 character that encounters in the file, therefore I assume that once I correct for that one I will run into another one and another one and so on. As I specified in the question, the text file I want to read is rather huge
comment on: http://stackoverflow.com/q/46781371

http://stackoverflow.com/q/46801171
score: 4
upvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/80549159
downvote count: 0
favorite count: 0
has title: What is the space complexity of my python function?
has answer: http://stackoverflow.com/a/46801951
tagged with: python
type: AnsweredQuestion
has body: Can someone tell me what the space complexity for this python function is? I believe it is O(1) but my friends are telling me that this is O(N). Reason why they are saying O(N): You are creating a new 'a' in every iteration of the for loop. Reason why I am saying O(1):You make a new 'a' every time you iterate and dump out the old 'a'. def hello(n): for i in range(n): a = 10 Would the space complexity be the same if this is pseudo code?
tagged with: space-complexity
type: Question
accepted answer: http://stackoverflow.com/a/46801951

http://stackoverflow.com/q/46851283
possible better answer: http://stackoverflow.com/a/46851358
has answer: http://stackoverflow.com/a/46851358
accepted answer: http://stackoverflow.com/a/46851557
has comment: http://stackoverflow.com/comment/80650905
favorite count: 0
type: Question
tagged with: python
has title: Can't use variable in function
answer count: 2
upvote count: 1
has body: I want to make a guessing game where if someone guesses the right number they get coins. When I create a function called guess_home (to act as a home screen) I cannot access variables in the main file. I am using two files, one for the main code, and one for all the functions to save space. when I made a variable in my main code, I cannot access it in my functions code. I was wondering if there was a way to allow me to use a variable in both files? Main Code: from guessing_functions import guess_game, guess_home coins = 0 q1 = input("Wanna play a game? ") if q1 == "ya": guess_game() coins += 5 guess_home() Functions: def guess_home(): main_q = input("Type 'coins' to see you coin balance, or 'again' to play again") if main_q == "coins": print ("Your coins balance is: " + coins) if main_q == "again": guess_game()
has answer: http://stackoverflow.com/a/46851557
score: -3
downvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/80653644
type: QuestionComment
score: 1
has text: Let's say that the contents of each QTextBrowser are different so the ideal size varies, in this case how do you want your widget to be displayed?
comment on: http://stackoverflow.com/q/46851971
type: Comment

http://stackoverflow.com/a/46753395
downvote count: 0
score: 1
has body: from python uuid doc, uuid1 is dependent on current time. You could use uuid3 to have a reproducible uuid for the same input, by reusing the same namespace: namespace = uuid.uuid4() ... print uuid.uuid3(namespace, "1")
upvote count: 1
answers question: http://stackoverflow.com/q/46753183
type: Answer

boolean
tags question: http://stackoverflow.com/q/46844812
tags question: http://stackoverflow.com/q/46903676
tags question: http://stackoverflow.com/q/46848035
tag name: boolean
tags question: http://stackoverflow.com/q/46765998
tags question: http://stackoverflow.com/q/46838614
tags question: http://stackoverflow.com/q/46851809
type: Tag

http://stackoverflow.com/q/46796770
tagged with: python
downvote count: 0
score: 1
has title: TensorFlow dropout: how to apply different values to Train vs Test?
has body: I am trying to implement dropout in TensorFlow for a simple 3-layer neural network for classification and am running into problems. More specifically, I am trying to apply different dropout parameter pkeep values when I train vs. test. I am taking the approach as follows: 1) def create_placeholders(n_x, n_y): X = tf.placeholder("float", [n_x, None]) Y = tf.placeholder("float", [n_y, None]) pkeep = tf.placeholder(tf.float32) return X,Y,pkeep 2) In the function forward_propagation(X, parameters, pkeep), I perform the following: Z1 = tf.add(tf.matmul(W1, X), b1) A1 = tf.nn.relu(Z1) A1d = tf.nn.dropout(A1, pkeep) Z2 = tf.add(tf.matmul(W2, A1d),b2) A2 = tf.nn.relu(Z2) A2d = tf.nn.dropout(A2, pkeep) Z3 = tf.add(tf.matmul(W3, A2d),b3) return Z3 3) Later when tensorflow session is called (in between code lines omitted for clarity): X, Y, pkeep = create_placeholders(n_x, n_y) Z3 = forward_propagation(X, parameters, pkeep) sess.run([optimizer,cost], feed_dict={X:minibatch_X, Y:minibatch_Y, pkeep: 0.75}) Above would run without giving any errors. However, I think that the above would set pkeep value to 0.75 for both training and testing runs. Minibatching is done only on the train data set but I am not setting the pkeep value anywhere else. I would like to set pkeep = 0.75 for training and pkeep = 1.0 for testing. 4) It does give an error when I do something like this: x_train_eval = Z3.eval(feed_dict={X: X_train, Y: Y_train, pkeep: 0.75}) x_test_eval = Z3.eval(feed_dict={X: X_test, Y: Y_test, pkeep: 1.0}) The error message I am getting is: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_2' with dtype float [[Node: Placeholder_2 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] What is the best way to pass different pkeep values for training and testing? Your advice would be much appreciated.
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/46799962
has answer: http://stackoverflow.com/a/46797219
answer count: 2
upvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/46878830
has body: You can introduce an optional argument that would trigger the '\t': def func(t=False): t = '\t' if t else '' print(t + 'this print with tab') print(t + 'and this print with tab') print('some text:') func(True)
score: 0
answers question: http://stackoverflow.com/q/46878699
type: Answer

http://stackoverflow.com/q/46792370
has comment: http://stackoverflow.com/comment/80531252
has answer: http://stackoverflow.com/a/46794787
tagged with: testing
tagged with: pytest
score: 7
has body: Using TestInfra with Ansible backend for testing purposes. Everything goes fine except using Ansible itself while running tests test.py import pytest def test_zabbix_agent_package(host): package = host.package("zabbix-agent") assert package.is_installed package_version = host.ansible("debug", "msg={{ zabbix_agent_version }}")["msg"] (...) where zabbix_agent_version is an Ansible variable from group_vars. It can be obtained by running this playbook - hosts: all become: true tasks: - name: debug debug: msg={{ zabbix_agent_version }} command executing tests pytest --connection=ansible --ansible-inventory=inventory --hosts=$hosts -v test.py ansible.cfg [defaults] timeout = 10 host_key_checking = False library=library/ retry_files_enabled = False roles_path=roles/ pipelining=true ConnectTimeout=60 remote_user=deploy private_key_file=/opt/jenkins/.ssh/deploy the output I get is self = &lt;ansible&gt;, module_name = 'debug', module_args = 'msg={{ zabbix_agent_version }}', check = True, kwargs = {} result = {'failed': True, 'msg': "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"} def __call__(self, module_name, module_args=None, check=True, **kwargs): if not self._host.backend.HAS_RUN_ANSIBLE: raise RuntimeError(( "Ansible module is only available with ansible " "connection backend")) result = self._host.backend.run_ansible( module_name, module_args, check=check, **kwargs) if result.get("failed", False) is True: &gt; raise AnsibleException(result) E AnsibleException: Unexpected error: {'failed': True, E 'msg': u"the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"} /usr/lib/python2.7/site-packages/testinfra/modules/ansible.py:70: AnsibleException Any idea why Ansible can't see this variable when running testinfra's Ansible module while it can see it while running Ansible alone?
type: Question
answer count: 2
tagged with: ansible
upvote count: 7
downvote count: 0
has title: Using Ansible variables in testinfra
favorite count: 0
has comment: http://stackoverflow.com/comment/80534400
has comment: http://stackoverflow.com/comment/80535289
tagged with: testinfra
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47576327

http://stackoverflow.com/q/46822789
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63463485
possible better answer: http://stackoverflow.com/a/55114979
tagged with: list-comprehension
has title: Python Generating random even numbers using list comprehension
has comment: http://stackoverflow.com/comment/80593909
answer count: 3
has comment: http://stackoverflow.com/comment/80593149
has answer: http://stackoverflow.com/a/46822836
accepted answer: http://stackoverflow.com/a/46822836
score: 0
has answer: http://stackoverflow.com/a/55114979
tagged with: python
has comment: http://stackoverflow.com/comment/80592971
tagged with: list
has body: A contrived example to try and understand Python list comprehensions I want to generate a list of 1000 random even numbers in the range of 1 to 100 This is what I have import random list = [random.randint(1,100) for _ in range(1,1000) if _ %2 ==0] I am not able to figure out how to check the result of the randint() in the for loop. I know this can possibly be done with random.randrange(x,y,2) or another mechanism. I want to understand if I can do it in the list comprehension way.
has comment: http://stackoverflow.com/comment/80593190
has comment: http://stackoverflow.com/comment/101404278
type: Question

http://stackoverflow.com/q/46802371
has answer: http://stackoverflow.com/a/46802466
has answer: http://stackoverflow.com/a/46802447
type: Question
has answer: http://stackoverflow.com/a/46802435
upvote count: 0
tagged with: nested-loops
score: -1
answer count: 6
has answer: http://stackoverflow.com/a/46802438
has title: Python Using nested loops to create a pattern
favorite count: 0
has answer: http://stackoverflow.com/a/46827321
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46802437
has body: Using python I am attempting to use nested loops to create this pattern: ** *-** *--*** *---**** *----***** My code so far has many issues and doesn't work as intended here it is so far for a in range(5): print("*", end="") print() for b in range(a): print("-", end="") Can you tell me what should I do?
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/80727878
has text: Yes - but I'm trying to report the two angles separately - I don't use them at the same time. (I realise this includes redundancy in the pitch and roll). I think I can put: `pitch = math.pi-(math.atan2(y, z)%(math.pi*2))` This will work for the micro bit - if it can only pitch and roll and not yaw - which will suit my purpose.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46886767
score: 0

http://stackoverflow.com/comment/80705069
has text: @ТолкачёвИван, already added :) See my answer
comment on: http://stackoverflow.com/q/46878699
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46832516
answer count: 2
has body: This works: &gt;&gt;&gt; not(True) False &gt;&gt;&gt; a = {} &gt;&gt;&gt; a["hidden"] = False &gt;&gt;&gt; a["hidden"] = not(a["hidden"]) &gt;&gt;&gt; a["hidden"] True but not this: def toggleHelp(self, event): # https://stackoverflow.com/questions/10267465/showing-and-hiding-widgets#10268076 if (self.special_frame["hidden"] == False): self.special_frame.grid_remove() else: self.special_frame.grid() self.special_frame["hidden"] == not(self.special_frame["hidden"]) error line 563 self.special_frame["hidden"] == not(self.special_frame["hidden"]) ^ SyntaxError: invalid syntax in the init: self.special_frame["hidden"] = False What I am doing wrong ?
accepted answer: http://stackoverflow.com/a/46832640
linked to: http://stackoverflow.com/q/6100305
favorite count: 0
has title: Why is using not() operator sometimes a SyntaxError?
duplicate of: http://stackoverflow.com/q/6100305
tagged with: python
linked to: http://stackoverflow.com/q/10267465
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/127366104
possible better answer: http://stackoverflow.com/a/46832605
has comment: http://stackoverflow.com/comment/80612620
has comment: http://stackoverflow.com/comment/80612552
score: 1
has answer: http://stackoverflow.com/a/46832605
has answer: http://stackoverflow.com/a/46832640
upvote count: 1
type: Question
downvote count: 0
tagged with: python-3.6

http://stackoverflow.com/comment/80697763
score: 0
type: Comment
type: QuestionComment
has text: `time.strptime()` might help
comment on: http://stackoverflow.com/q/46875300

http://stackoverflow.com/q/46847870
upvote count: 2
has comment: http://stackoverflow.com/comment/80644001
tagged with: python
has comment: http://stackoverflow.com/comment/80646861
has answer: http://stackoverflow.com/a/46848471
linked to: http://stackoverflow.com/q/25753632
tagged with: text
type: AnsweredQuestion
tagged with: tkinter
tagged with: widget
score: 1
has body: I would like to repeatedly get the contents of a Text widget, so I can analyse it and gets stats about what's been entered. These stats would need to be updated in real time as the user types, hence why I need the variable currentContent to update every loop. What I'd like to do is something like this. main = tk.Tk() # Y'know, all the typical window setup stuff. currentContent = inputBox.get(0.0,END) textBlobContent = TextBlob(currentContent) # Basically here I'd do a bunch of stuff using TextBlob. main.mainloop() However, that doesn't work. It gets the content once, as soon as the window loads, and then stops. Surely mainloop runs repeatedly, and it should keep getting the contents of the Text widget?
accepted answer: http://stackoverflow.com/a/46848471
linked to: http://stackoverflow.com/q/17120429
downvote count: 1
type: Question
has title: How to repeatedly get the contents of a Text widget every loop with tkinter?
has comment: http://stackoverflow.com/comment/80643061
has comment: http://stackoverflow.com/comment/80643224
has comment: http://stackoverflow.com/comment/80643868
has comment: http://stackoverflow.com/comment/80644507
has comment: http://stackoverflow.com/comment/80643686
answer count: 1
favorite count: 0

http://stackoverflow.com/a/46871791
accepted answer of: http://stackoverflow.com/q/46871746
score: 1
answers question: http://stackoverflow.com/q/46871746
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I suspect that your temporary directory contains a non-ASCII 7 bit character in the actual path. If you are on Windows make sure that the environment variable %TEMP% is set to a directory that only uses in it's full path the values in the ranges A-Za-z0-9 no accented characters, symbols, etc. Note On windows 10 and python 2.7.13 I have just tested and got: &gt; pip install django Collecting django Downloading Django-1.11.6-py2.py3-none-any.whl (6.9MB) 100% |################################| 7.0MB 152kB/s Requirement already satisfied: pytz in c:\python27\lib\site-packages (from django) Installing collected packages: django Successfully installed django-1.11.6 &gt; pip --version pip 9.0.1 from c:\python27\lib\site-packages (python 2.7) BUT &gt; mkdir Témp &gt; set TEMP=.\Témp &gt; pip install django Collecting django Exception: Traceback (most recent call last): File "c:\python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\python27\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "c:\python27\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "c:\python27\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\python27\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "c:\python27\lib\site-packages\pip\download.py", line 821, in unpack_url hashes=hashes File "c:\python27\lib\site-packages\pip\download.py", line 659, in unpack_http_url hashes) File "c:\python27\lib\site-packages\pip\download.py", line 880, in _download_http_url file_path = os.path.join(temp_dir, filename) File "c:\python27\lib\ntpath.py", line 85, in join result_path = result_path + p_path UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 31: ordinal not in range(128)
upvote count: 1

http://stackoverflow.com/comment/80730144
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46891129
has text: Yes, and piRSquared's was what I was looking for. But please allow me to say thank you to your quick response.

distinct
tag name: distinct
tags question: http://stackoverflow.com/q/46892392
type: Tag

http://stackoverflow.com/q/46868164
has comment: http://stackoverflow.com/comment/80683906
score: 0
has title: Python CSV & Dict Writer- Write Specific Columns: Only writing the header
has comment: http://stackoverflow.com/comment/80683792
has comment: http://stackoverflow.com/comment/80683694
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/80683993
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80683776
has body: I tinkered with some code that I found here to suit my needs where I only want to pull certain fields (columns) from a CSV and write to another file. I have a 150 line file in "cleanfile.csv" and I limited the headers-to-write to just two for simplicity of trouble shooting. I can add the rest back after I figure this out. The code does not error out but it only writes the header line to "outfile.csv". Any help would be grealy appreciated. import csv headers = ['Owner','Expiry'] with open('cleanfile.csv','r') as _in, open('outfile.csv','w') as out: reader = csv.DictReader(_in) writer = csv.DictWriter(out,headers,extrasaction='ignore') writer.writeheader() for line in reader: writer.writerow(line)
has comment: http://stackoverflow.com/comment/80683677
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93875710
has comment: http://stackoverflow.com/comment/80684007
has comment: http://stackoverflow.com/comment/80683835
type: Question

http://stackoverflow.com/comment/80709294
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46880929
has text: `if is_user_turn is True:` can become `if is_user_turn:` and you needn't do the check in `elif is_user_turn is False:`. It can only be true or false, so just `else:` will suffice.
score: 0

http://stackoverflow.com/comment/80522707
type: Comment
score: 0
has text: can you share your imports? what module id session.Session from
type: QuestionComment
comment on: http://stackoverflow.com/q/46788182

http://stackoverflow.com/comment/80703877
type: QuestionComment
has text: What are the results if you call `test.count()` and `train.count()`?
score: 0
comment on: http://stackoverflow.com/q/46863036
type: Comment

http://stackoverflow.com/q/46810126
accepted answer: http://stackoverflow.com/a/46816082
tagged with: python
type: AnsweredQuestion
has title: How to convert newlines from CRLF to LF while creating Python sdist?
tagged with: setuptools
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/46816082
has body: I'd like to use Windows as my main development platform, but at the same time generate sdist tarballs with LF newlines. Is there a way to keep CRLF-s in my working directory and turn them automatically to LF-s while doing python setup.py sdist ? Where are all sdist options documented?
score: 0
tagged with: distutils

http://stackoverflow.com/comment/80578011
has text: Don't lie. That code does not produce that error. You'd need to fix three or four syntax errors before you can even run that code at all.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46815115

http://stackoverflow.com/comment/80574771
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46802122
has text: @Clement What are the differences between your own code and the correct code? It should not take so long to find indices in such a small array. But if it works, you can start with that code and try to optimize it.

http://stackoverflow.com/comment/80541160
comment on: http://stackoverflow.com/q/46797221
type: Comment
type: QuestionComment
has text: Split with a comma and get the last item.
score: 0

http://stackoverflow.com/a/46896080
answers question: http://stackoverflow.com/q/46895991
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80739935
has body: If both are strings you can use the == operator, like follow: a == b Note that this is case-sensitive, if you want it to be case-unsensitive you can use the .lower() function of strings: a.lower() == b.lower() If they are not Strings, you can probably cast them to string.
has comment: http://stackoverflow.com/comment/80739537

http://stackoverflow.com/q/46809525
type: AnsweredQuestion
tagged with: geopy
score: 5
upvote count: 7
answer count: 1
favorite count: 0
has title: python geopy get city and country
tagged with: python
has body: I am trying to get city and country names with geopy. Normally this is how you can get city and country using geopy. from geopy.geocoders import Nominatim geolocator = Nominatim(timeout=3) geolocator.reverse('52.5094982,13.3765983') loc = location.raw loc_dict = location.raw print(loc_dict['address']) and this is the output: {'suburb': 'Tiergarten', 'country_code': 'de', 'country': 'Deutschland', 'postcode': '10117', 'attraction': 'Potsdamer Platz', 'road': 'Potsdamer Platz', 'city': 'Berlin', 'city_district': 'Mitte', 'state': 'Berlin'} My problem is that geopy returns city and country names in their country language, for example: city: Berlin, country: Deutschland city: København, country: Danmark city: București, country: România i want them like this: city: Berlin, country: Germany city: Copenhagen, country: Denmark city: Bucharest, country: Romania Is it possible to get them in english as i want? or convert them somehow? I am using all countries and cities arround the world.
has answer: http://stackoverflow.com/a/46809645
accepted answer: http://stackoverflow.com/a/46809645
downvote count: 2
type: Question

http://stackoverflow.com/comment/80825310
comment on: http://stackoverflow.com/a/46912759
score: 0
type: AnswerComment
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157508/discussion-between-eyllanesc-and-akeg).

http://stackoverflow.com/a/64282960
has comment: http://stackoverflow.com/comment/123834746
type: Answer
has comment: http://stackoverflow.com/comment/121561035
upvote count: 3
has body: In the last version ( uic 5.15) the argument -x is no longer used you just use pyside2-uic mainwindow.ui -o mainwindow.py Use your transpiled file (mainwindow.py) within your main Python script: from PySide2.QtWidgets import QMainWindow from mainwindow import Ui_MainWindow MainWindow = QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show()
score: 3
answers question: http://stackoverflow.com/q/46899540
downvote count: 0

http://stackoverflow.com/comment/80598715
comment on: http://stackoverflow.com/q/46825425
has text: What observable action do you expect to occur and why? Your script does not do anything.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80732840
has text: Maybe the `pip` launcher script is from a Python installation different from the Python 2.7 one invoked by `python`? Try `pip -V` to confirm this.
comment on: http://stackoverflow.com/q/46892830
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80576008
type: Comment
type: QuestionComment
has text: Short answer: no
comment on: http://stackoverflow.com/q/46813776
score: 0

http://stackoverflow.com/comment/80614336
comment on: http://stackoverflow.com/a/46833192
has text: Also, for the data you can just generate a range: list(range(1,25))
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46835804
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/46852282
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/46852282
answer count: 2
has answer: http://stackoverflow.com/a/46850845
tagged with: python
has comment: http://stackoverflow.com/comment/80652251
tagged with: moto
has comment: http://stackoverflow.com/comment/80652576
has title: Mocking boto3 calls actual boto3
has body: I'm writing some test for boto3 functions and using the moto library to mock boto3. The example they provide is as such: import boto3 from moto import mock_ec2 def add_servers(ami_id, count): client = boto3.client('ec2', region_name='us-west-1') client.run_instances(ImageId=ami_id, MinCount=count, MaxCount=count) @mock_ec2 def test_add_servers(): add_servers('ami-1234abcd', 2) client = boto3.client('ec2', region_name='us-west-1') instances = client.describe_instances()['Reservations'][0]['Instances'] assert len(instances) == 2 instance1 = instances[0] assert instance1['ImageId'] == 'ami-1234abcd' However when I try something similar, using a trivial example here, by doing this: def start_instance(instance_id): client = boto3.client('ec2') client.start_instances(InstanceIds=[instance_id]) @mock_ec2 def test_start_instance(): start_instance('abc123') client = boto3.client('ec2') instances = client.describe_instances() print instances test_start_instance() ClientError: An error occurred (InvalidInstanceID.NotFound) when calling the StartInstances operation: The instance ID '[u'abc123']' does not exist Why is it actually making request to AWS when I clearly have the function wrapped in the mocker?
accepted answer: http://stackoverflow.com/a/46850845
tagged with: boto3
has comment: http://stackoverflow.com/comment/80652918
has comment: http://stackoverflow.com/comment/92694710

http://stackoverflow.com/comment/80572676
comment on: http://stackoverflow.com/a/46812584
type: Comment
score: 0
has text: Check `collections.Counter.most_common()`: https://docs.python.org/3.6/library/collections.html#collections.Counter.most_common
type: AnswerComment

http://stackoverflow.com/comment/80694150
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46873344
has text: You are naming these files after "whitening" them... can you add a `w_` prefix, and then segregate based on their name? `gun1.jpg` --> `w_gun1.jpg`
score: 0

http://stackoverflow.com/q/46787429
tagged with: logic
has title: Adding items to Listbox in Python Tkinter
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/80521397
answer count: 1
tagged with: button
favorite count: 0
has answer: http://stackoverflow.com/a/46787761
has comment: http://stackoverflow.com/comment/80521626
accepted answer: http://stackoverflow.com/a/46787761
has comment: http://stackoverflow.com/comment/80521691
tagged with: python
type: AnsweredQuestion
has body: I would like my Listbox widget to be updated upon clicking of a button. However I encountered a logic error. When I click on the button, nothing happens. No errors at all. listOfCompanies: [[1, ''], [2, '-'], [3, '@ASK TRAINING PTE. LTD.'], [4, 'AAIS'], [5, 'Ademco'], [6, 'Anacle'] def populatebox(): listBox.insert("end", listOfCompanies) btn = Button(self, text="Update list", command = lambda: populatebox()) btn.pack()
tagged with: tkinter
type: Question
tagged with: listbox
score: -1

http://stackoverflow.com/comment/80731253
comment on: http://stackoverflow.com/q/46891888
has text: Do get to technical on pizzas please, it is just an example
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46755129
has comment: http://stackoverflow.com/comment/80456719
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80456617
has body: I am trying to draw a triangle in this way, but I keep messing up the part, where I have to choose my vertices. Can somebody tell me where I went wrong? from graphics import GraphicsWindow triangle1= [[150,50], [250,50],[200,130]] win = GraphicsWindow(400, 400) canvas = win.canvas() canvas.setOutline("blue") canvas.drawPolygon(triangle1, canvas) last = len(triangle1) - 1 for i in range(last): start = triangle1[i] end = triangle1[i+1] canvas.drawLine(start[0], start[1], end[0], end[1]) start =triangle1[last] end = triangle1[0] canvas.drawLine(start[0], start[1], end[0], end[1]) win.wait()
type: Question
has title: Can't define vertices
has comment: http://stackoverflow.com/comment/80457060
has answer: http://stackoverflow.com/a/46755987
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80455919
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80457106
tagged with: python
accepted answer: http://stackoverflow.com/a/46755987

http://stackoverflow.com/q/46869943
has title: How to concatenate features of different types in a single python array?
tagged with: arrays
answer count: 1
downvote count: 0
tagged with: scikit-learn
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/46869991
tagged with: pandas
tagged with: python
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/46869991
has body: I have a features array that contains values of different types: &gt;&gt;&gt; features = train_df.values &gt;&gt;&gt; [x for x in features] [True, array([2, 0, 0, ..., 0, 0, 0]), False, False, 17, 1, 10, array([0, 0, 0, ..., 0, 0, 0])] I would like to produce a single python array that contains a concatenation of the all of the above features, i.e. np.array([True, 2, 0, 0, ..., 0, 0, 0, False, False, 17, 1, 10, 0, 0, 0, ..., 0, 0, 0]) My goal is to train sklearn LogisticRegression with the above feature vector. What is the best way to do this in python?
type: Question

http://stackoverflow.com/comment/80719922
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46886226
has text: Could you tell us which version of skill_metrics and matplotlib are you using? You can check it with following code: `python import matplotlib import skill_metrics matplotlib.__version__ '2.1.0' skill_metrics.__version__ '1.1.4' `

http://stackoverflow.com/comment/80480095
type: QuestionComment
score: 0
has text: Why are you making a single string from the list returned by `os.listdir()` ?
type: Comment
comment on: http://stackoverflow.com/q/46767256

http://stackoverflow.com/comment/80743920
has text: once I have downloaded the Python-2.6.6.tgz and unzipped it, I am able to run python2.6.6 from the unzipped file, does that mean I don't actually have to do the ./configure.py and make build process to compile it to source code? I do have a virtualenv environment available, should I just configure virtualenv to use uncompiled version of the python2.6.6?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46897967

http://stackoverflow.com/comment/80701117
score: 1
comment on: http://stackoverflow.com/q/46877090
has text: Could you post the import statement as well.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46855947
answer count: 3
upvote count: 0
possible better answer: http://stackoverflow.com/a/46856144
has comment: http://stackoverflow.com/comment/80659422
has answer: http://stackoverflow.com/a/46856144
favorite count: 0
tagged with: area
has title: How do you take values from dictionaries in python for calculations?
has answer: http://stackoverflow.com/a/46856040
tagged with: python
has body: I have to answer the following question: 8. We have a dictionary containing several rectangular islands: islands = { "Banana island" : (3,5,7,6), "Mango island" : (10,3,19,4), "Pineapple island" : (8,8,9,20), "Coconut island" : (2,13,5,9) } Write code to calculate which island has the minimum area, using your land_rectangle_area function. I have created a function for the area: def land_rectangle_area(x1, y1, x2, y2): area=abs((int(x1)-int(x2))*(int(y1)-int(y2))) return(area) I am unsure how I proceed with this question from here?
tagged with: dictionary
score: -2
has comment: http://stackoverflow.com/comment/80659443
tagged with: python-3.x
downvote count: 2
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46856040
tagged with: math
has answer: http://stackoverflow.com/a/46856119

http://stackoverflow.com/a/46866174
has comment: http://stackoverflow.com/comment/80680159
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80878429
has body: class ConnectionConfig(): name: str url: str port: int user: str = "" pwd: str = "" client: Any = None def __init__(self, **kv): self.__dict__.update(kv) then you can specify everything in the constructor c=ConnectionConfig(port=22) print (c.port) # will print 22
upvote count: 2
answers question: http://stackoverflow.com/q/46865909

http://stackoverflow.com/comment/80631212
comment on: http://stackoverflow.com/q/46841618
has text: We have to use a regular expression tester given to us. Is there any way to do this purely as a regular expression?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80544705
comment on: http://stackoverflow.com/q/46797160
score: 0
has text: Sure I try to show the first paragraph of a post on index or /posts page even if contains a lot of characters. Here is an [example](http://www.erdem.tk/arduino) but it was coded with D.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80549200
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/46799902
has text: `np.median(M.A, axis=0)` for a reasonably sparse matrix is likely to be all 0s. That is, it most of the elements in a row are 0, the middle one (in a sorted list) probably will be 0.

http://stackoverflow.com/q/46797770
has comment: http://stackoverflow.com/comment/81247349
has comment: http://stackoverflow.com/comment/80928476
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81247420
linked to: http://stackoverflow.com/q/46778491
has title: Tkinter application 'freezes' while continually polling Pipe for contents (multiprocessing)
has comment: http://stackoverflow.com/comment/81247154
type: Question
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/46962228
has body: I have two scripts: Processor_child.py: Its purpose is to perform a number of data analysis and cleaning operations. This must perform the same operations when run alone (without Tkinter_parent.py) as it does when packaged into a GUI with Tkinter_parent.py. Tkinter_parent.py: Its purpose is to provide a GUI for those who can't use Processor_child directly. Within Processor_child, there are for loops that ask the user for input on each iteration. These prompts need to appear in the Tkinter app, accept the input, and send it back to Processor_child. The code below does this, raising an Entry field whenever there's data in the Pipe (added by the loop). However, it often seems to 'freeze', getting stuck loading and not progressing through the code. Sometimes, it runs perfectly as intended. (No changes in the code in these instances.) How can I resolve this / make it more stable? I've commented below where the 'freeze' is happening. Tkinter_parent.py: ### Tkinter_parent.py ### from tkinter import * from tkinter.filedialog import askopenfilename from tkinter import ttk from multiprocessing import Process, Pipe import pandas as pd import Processor_child import time class GUI: def __init__(self, master): self.master = master def gui_input(message, a_pipe = None): def input_done(event=None): entry.pack_forget() input_label.pack_forget() submit_button.pack_forget() a_pipe.send(entry.get()) next_one(a_pipe) entry = Entry(frame) input_label = ttk.Label(frame, text=message) entry.bind("&lt;Return&gt;", input_done) submit_button = ttk.Button(frame, text="Submit", command=input_done) input_label.pack() entry.pack() submit_button.pack() def file_select(): dataset_path = askopenfilename() if __name__ == '__main__': pipe1, pipe2 = Pipe() some_vars = ['a var', 'another var'] a_df = pd.read_csv(dataset_path) p_review = Process(target=Processor_child.review_with_user, args=(some_vars, a_df, pipe2)) p_review.start() gui_input(pipe1.recv(), pipe1) #time.sleep(1) def next_one(pipe1): while…
has answer: http://stackoverflow.com/a/46898149
has answer: http://stackoverflow.com/a/46991743
linked to: http://stackoverflow.com/q/21811464
score: 0
has answer: http://stackoverflow.com/a/46802154
tagged with: python
tagged with: tkinter-entry
answer count: 4

http://stackoverflow.com/q/46821113
upvote count: 3
has body: Here's my Python code right now: sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(Queue='test') msg = 'hello world' for i in range(0,1000): queue.send_message(MessageBody = msg) print("Message Sent") And here is the Node.js version: var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); var params = { MessageBody: 'hello world', QueueUrl: // Queue URL here }; for(var i = 0; i &lt; 1000; i++){ sqs.sendMessage(params, function(err,data){ if(err){ throw err; } else { console.log("Message Sent"); } }) } My problem is that it takes significantly longer to send 1000 messages using the Python script because it runs synchronously vs Node.js doing it asynchronously. I've looked everywhere and I can't seem to find any way to send messages asynchronously in Python. Insight would be greatly appreciated.
type: Question
tagged with: amazon-sqs
has answer: http://stackoverflow.com/a/74432580
has answer: http://stackoverflow.com/a/46821242
tagged with: amazon-web-services
answer count: 2
downvote count: 0
tagged with: asynchronous
favorite count: 0
has title: How to send SQS message asynchronously in python?
type: UnansweredQuestion
tagged with: python
tagged with: node.js
score: 3

http://stackoverflow.com/comment/80548771
score: 0
comment on: http://stackoverflow.com/q/46800902
type: Comment
type: QuestionComment
has text: If you want the `dict` attribute to be a class attribute, why not create it as one? Just put `dict = {}` at the class's top level (not inside a method) and remove the equivalent line from `__init__`. Usually that's not what you want, but it seems like it's exactly what you're asking for.

http://stackoverflow.com/a/46872361
accepted answer of: http://stackoverflow.com/q/46872223
has comment: http://stackoverflow.com/comment/80691918
downvote count: 0
upvote count: 2
has body: Use: df = df[df.groupby(pd.to_datetime(df['datetime_event']).dt.floor('H')).cumcount() &lt; 3] print (df) id datetime_event title 0 11 2017-05-01T00:00:08 AAA 1 12 2017-05-01T00:00:08 BBB 2 13 2017-05-01T00:00:08 CCC 5 16 2017-05-01T01:01:00 EEE 6 17 2017-05-01T01:01:01 EEE 7 18 2017-05-01T01:01:09 DDD Timings df = pd.DataFrame({'datetime_event':pd.date_range('2000-01-01', freq='2T', periods=10**5)}) df['val'] = np.arange(len(df)) In [29]: %timeit df.groupby(pd.to_datetime(df['datetime_event']).dt.floor('H')).head(3) 100 loops, best of 3: 15.8 ms per loop In [30]: %timeit df[df.groupby(pd.to_datetime(df['datetime_event']).dt.floor('H')).cumcount() &lt; 3] 100 loops, best of 3: 15.8 ms per loop df = pd.DataFrame({'datetime_event':pd.date_range('2000-01-01', freq='2S', periods=10**5)}) df['val'] = np.arange(len(df)) In [33]: %timeit df.groupby(pd.to_datetime(df['datetime_event']).dt.floor('H')).head(3) 100 loops, best of 3: 14.1 ms per loop In [34]: %timeit df[df.groupby(pd.to_datetime(df['datetime_event']).dt.floor('H')).cumcount() &lt; 3] 100 loops, best of 3: 14.5 ms per loop
answers question: http://stackoverflow.com/q/46872223
has comment: http://stackoverflow.com/comment/80691935
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/80691945
type: AcceptedAnswer

http://stackoverflow.com/comment/80451251
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46752285
type: AnswerComment
has text: Wheres the best place to add this to the code? I add this and it keeps giving invalid syntax errors.

http://stackoverflow.com/a/46862123
answers question: http://stackoverflow.com/q/46860908
has body: which words you want to replace are appearing in the second string so you can try something like : new_string=[string2.split()] new=[] new1=[j for item in new_string for j in item if j not in string1] new1.insert(0,string1) print(" ".join(new1)) with the first test case: string1 = 'Hello how are you' string2 = 'are you doing now?' output: Hello how are you doing now? second test case: string1 = 'This is a nice ACADEMY' string2 = 'DEMY you know!' output: This is a nice ACADEMY you know! Explanation : first, we are splitting the second string so we can find which words we have to remove or replace : new_string=[string2.split()] second step we will check each word of this splitter string with string1 , if any word is in that string than choose only first string word , leave that word in second string : new1=[j for item in new_string for j in item if j not in string1] This list comprehension is same as : new1=[] for item in new_string: for j in item: if j not in string1: new1.append(j) last step combines both string and join the list: new1.insert(0,string1) print(" ".join(new1))
score: 0
type: Answer

http://stackoverflow.com/comment/80563076
score: 0
has text: You can just do `data = pd.read_json(...)` - not sure why you've got the extra `pd.DataFrame(...)` around it...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46808017

http://stackoverflow.com/a/46787406
answers question: http://stackoverflow.com/q/46787046
type: Answer
has body: You'll have to visit every element if you wish to replace them with something else. Here's an idea on how you can achieve it in python. Assuming your dataset looks something like this: d = {'a':'apple', 'b': 'bread', 'c':'coke'} l = ['a', 'b', 'c'] You can do something like this using list comprehension: # look in the dictionary for the value, # if it's there replace with the value, else let it be there as it is l = [d[e] if e in d else e for e in l] or using map: l = map(lambda e: d[e] if e in d else e, l)
score: 0

http://stackoverflow.com/a/46749233
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46749181
has body: You can unpack the tuple in the for loop &gt;&gt;&gt; tup_list = [(1,2), (3,4)] &gt;&gt;&gt; for a,b in tup_list: ... print(a,b) ... 1 2 3 4
has comment: http://stackoverflow.com/comment/123626720
downvote count: 0

http://stackoverflow.com/a/46816807
has comment: http://stackoverflow.com/comment/80586373
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46816287
has comment: http://stackoverflow.com/comment/80583176
type: Answer
has comment: http://stackoverflow.com/comment/80606959
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80581148
has body: First, is there a commit() call on the SQLAlchemy session? Setting the Flask configuration attribute 'SQLALCHEMY_ECHO' to True will cause all DB queries to be printed to stdout: application = Flask(__name__) application.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(application) With SQLALCHEMY_ECHO enabled, you can watch the DB traffic to see if updating an object in a SQLAlchemy session causes the DB to be updated and eventually COMMITed or rolled back.
has comment: http://stackoverflow.com/comment/80583266
has comment: http://stackoverflow.com/comment/80585748
accepted answer of: http://stackoverflow.com/q/46816287

http://stackoverflow.com/comment/80581402
type: QuestionComment
type: Comment
has text: Perhaps you should Google for a *code writing service*.
comment on: http://stackoverflow.com/q/46817029
score: 0

http://stackoverflow.com/comment/99755038
type: Comment
score: 1
has text: @DangManhTruong With unicode it's Python 2 that has problems, not Python 3.
comment on: http://stackoverflow.com/a/46842547
type: AnswerComment

http://stackoverflow.com/q/46803291
has answer: http://stackoverflow.com/a/46804065
type: Question
has comment: http://stackoverflow.com/comment/80553346
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/46804065
has body: So, I was asked to code the Wallis product and it wasn't supposed to be really complicated. So I made a code but apparently, it could only work for Wallis(1) and not the rest. Could anyone help me? Thank you! def Wallis (n): result = 1 for count in range(2, n+2, 2): result = result * (count**2/((count-1)*(count+1))) return result Formula to compute Wallis product (2*2)/(3*5) * (4*4)/(5*7) * (6*6)/(7*9) and so on until ((n*2) ** 2)/ ((n-1)* (n+1)) Output Wallis(1) = (2*2)/(3*5) = 0.267 Wallis(2) = Wallis(1) * (4*4)/(5*7) = 0.122
answer count: 3
possible better answer: http://stackoverflow.com/a/46803700
favorite count: 0
has answer: http://stackoverflow.com/a/46803700
tagged with: python
has answer: http://stackoverflow.com/a/46803800
has title: What is wrong with my python code on Wallis product?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80553350
has comment: http://stackoverflow.com/comment/80553958
downvote count: 2

http://stackoverflow.com/comment/80680475
has text: Net Performance (accuracy) doesn't change but training is fastest if everything is on gpu
comment on: http://stackoverflow.com/q/46856265
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/80580278
comment on: http://stackoverflow.com/q/46816416
type: Comment
has text: ok, we got the input. Now, post the final expected output please
score: 0
type: QuestionComment

http://stackoverflow.com/q/46785347
has comment: http://stackoverflow.com/comment/80517487
possible better answer: http://stackoverflow.com/a/46785474
has title: Python read lines after finding specific lines
has answer: http://stackoverflow.com/a/46785474
type: Question
has answer: http://stackoverflow.com/a/46785593
has body: I am trying to take out the certain lines after a certain line is being found. Below is the example: 1. ABC01 2. AB_Name 3. AC_Name 4. ID_Name 5. ABC02 6. AB_Name 7. ABB_Name 8. AC_Name 9. AQ_Name 10. ID_Name 11. ABC01 12. AP_Name 13. AZ_Name 14. AB_Name 15. ID_Name What I am trying to take out is the everysingle line that goes after ABC01 and ignore ABC02 and line after it. So the output that I am looking for is: 1. ABC01 2. AB_Name 3. AC_Name 4. ID_Name 11. ABC01 12. AP_Name 13. AZ_Name 14. AB_Name 15. ID_Name I have tried if statements like: lines = [line.rstrip('\n') for line in open('File.txt')] listings = [] for line in lines: if line.startswith("ABC01"): continue if line.startswith("ID"): break listings.append(line.strip()) I am using Python 2.7
downvote count: 0
accepted answer: http://stackoverflow.com/a/46785471
answer count: 3
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46785471
score: 1

http://stackoverflow.com/a/46883682
score: 4
has comment: http://stackoverflow.com/comment/80750224
accepted answer of: http://stackoverflow.com/q/46881673
answers question: http://stackoverflow.com/q/46881673
has comment: http://stackoverflow.com/comment/80795550
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Put 'chromedriver.exe' inside script folder which is inside python folder on your installed driver(by default C://Python/script), then add C://Python and C://Python/script in path under environment variable. Follow the step here for more detail. After the setup restart once and then try your code
type: Answer

http://stackoverflow.com/q/46813603
answer count: 1
accepted answer: http://stackoverflow.com/a/46813770
tagged with: python
type: AnsweredQuestion
type: Question
has body: I have two lists: names = ['John', 'Mike'] years = ['1980','1975'] My code: combination = [] for n, nvalue in enumerate(names): for y, yvalue in enumerate(years): combination.append([nvalue,yvalue]) print (combination) this produces: [['John', '1980'], ['John', '1975'], ['Mike', '1980'], ['Mike', '1975']] I want possible combination where each row has a name in a list with a year. So The first name will appear first at all iterations, followed by other names. The same year can appear with multiple names. required output: [[('John','1980')('Mike','1975')], [('John','1980')('Mike','1980')], [('John','1975')('Mike','1975')], [('John','1975')('Mike','1980')]]
has answer: http://stackoverflow.com/a/46813770
score: 0
has title: pairwise combination from two lists with condition in Python

http://stackoverflow.com/a/46902410
has body: From this line: cumm_gpa_info = (cumm_gpa, total_credits) We can see that cumm_gpa_info is a tuple of two values. Then current_cumm_gpa, total_credits = cumm_gpa_info unpacks the values in the tuple to two variables, the first to current_cumm_gpa and the second to total_credits. It's a simpler way of doing: current_cumm_gpa = cumm_gpa_info[0] total_credits = cumm_gpa_info[1] From the docs: This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46902335
downvote count: 0

http://stackoverflow.com/q/46775801
upvote count: 0
tagged with: flask-wtforms
type: Question
score: -1
has title: Iterate over the results returned from session query in SqlAlchemy and print them in a flask template
tagged with: sqlalchemy
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/46778841
tagged with: flask
favorite count: 0
has body: How can I iterate over the results returned by session.query from a database and print them in a flask template? I have the following code where I am able to successfully iterate over the results returned from database and print employees name outside of my flask app. I am just not able to figure out as how to use the following code and print out the employees name in a flask template: def getEmployees(): engine = create_engine('mssql+pyodbc://<server name>/<DB name>?driver=SQL+Server+Native+Client+11.0') Base = declarative_base(engine) class Bookmarks(Base): __tablename__ = 'table name' Employee = Column(String(50)) __table_args__ = {'autoload':True} def loadSession(): metadata = Base.metadata Session = sessionmaker(bind=engine) session = Session() return session if __name__ == "__main__": session = loadSession() results = Bookmarks.query.filter_by(Manager='Bob') Route: @app.route('/employeesName', methods=['GET') def employeesName(): if request.method == 'GET': return render_template('getEmployees.html') Template (getEmployees.html): Results {% for employees in results %} {{ employees.Employee }} {% endfor %} How can I print employees name filtered by Manager = 'Bob' in the flask template? Thank you so much!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80499331
has comment: http://stackoverflow.com/comment/80497215

http://stackoverflow.com/comment/80704580
has text: @ThomasJacobs Then add the new ` Queue` to a separate list `new_queues`. Append `new_queues` to `listOfQueues` after the `for`-loop in the `run` method.
type: Comment
comment on: http://stackoverflow.com/a/46872597
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80642997
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46847282
score: 1
has text: Might help to also paste the content of `comment/comments.html`. There is no error in the python console?

http://stackoverflow.com/q/46751001
accepted answer: http://stackoverflow.com/a/46753657
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/31017306
favorite count: 0
has answer: http://stackoverflow.com/a/46753657
tagged with: django
tagged with: python
has body: I have a Django v1.3.1 site on a now-compromised server (used to be on Python v2.7.3). I've been able to reconstruct the bulk of the content via a cache of the old admin site but after re-installing Python and Django on a new server instance (Python v2.7.12), I'm running across the following error: TemplateDoesNotExist at /admin/ admin/login.html Request Method: GET Django Version: 1.3.1 Exception Type: TemplateDoesNotExist Exception Value: admin/login.html Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loader.py in find_template, line 138 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/var/django/mysite', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Sun, 15 Oct 2017 02:31:49 +0100 The relevant info from trying to load the templates: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /var/django/mysite/templates/admin/login.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: Looking on the new machine for /admin/index.html I get: locate admin/login.html /usr/local/django/contrib/admin/templates/admin/login.html On the old machine I get: locate admin/login.html /root/build/Django/build/lib.linux-x86_64-2.7/django/contrib/admin/templates/admin/login.html /root/build/Django/django/contrib/admin/templates/admin/login.html /root/build/Django/tests/templates/custom_admin/login.html /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/login.html What have I missed in getting this up and running / how do I resolve this before I start upgrading to the latest Django version? Edit - contents of TEMPLATE_DIRS: TEMPLATE_DIRS = ('/var/django/mysite/templates','C:/Users/jon/PycharmProjects/mysite/templates',) I …
has comment: http://stackoverflow.com/comment/80448832
type: AnsweredQuestion
score: 3
has title: Why does my aging Django 1.3.1 site say ''TemplateDoesNotExist at /admin/" after migration to a new server?
upvote count: 3
has comment: http://stackoverflow.com/comment/80448157
type: Question

http://stackoverflow.com/comment/80788399
type: Comment
type: QuestionComment
score: 0
has text: The browsable api runs more requests than is immediately apparent. For that reason your serializer and view need to handle them all: https://stackoverflow.com/questions/30323159/django-rest-framework-get-serializer-class-called-several-times-with-wrong-v
comment on: http://stackoverflow.com/q/46874087

scikit-learn
tags question: http://stackoverflow.com/q/46815252
tags question: http://stackoverflow.com/q/46762533
tags question: http://stackoverflow.com/q/46801983
tags question: http://stackoverflow.com/q/46783974
tags question: http://stackoverflow.com/q/46756606
tags question: http://stackoverflow.com/q/46762288
tags question: http://stackoverflow.com/q/46814467
tags question: http://stackoverflow.com/q/46852222
tags question: http://stackoverflow.com/q/46792252
tags question: http://stackoverflow.com/q/46760318
tags question: http://stackoverflow.com/q/46881360
tags question: http://stackoverflow.com/q/46770088
tags question: http://stackoverflow.com/q/46786036
tags question: http://stackoverflow.com/q/46888182
tags question: http://stackoverflow.com/q/46767890
tags question: http://stackoverflow.com/q/46820178
tags question: http://stackoverflow.com/q/46800147
tags question: http://stackoverflow.com/q/46833744
tags question: http://stackoverflow.com/q/46832637
tags question: http://stackoverflow.com/q/46758851
tags question: http://stackoverflow.com/q/46785169
tags question: http://stackoverflow.com/q/46869943
tags question: http://stackoverflow.com/q/46896386
tags question: http://stackoverflow.com/q/46900082
tags question: http://stackoverflow.com/q/46835428
tags question: http://stackoverflow.com/q/46815231
tags question: http://stackoverflow.com/q/46768519
tags question: http://stackoverflow.com/q/46775155
tags question: http://stackoverflow.com/q/46838799
tags question: http://stackoverflow.com/q/46750355
tags question: http://stackoverflow.com/q/46864926
tag name: scikit-learn
tags question: http://stackoverflow.com/q/46848413
tags question: http://stackoverflow.com/q/46884841
tags question: http://stackoverflow.com/q/46752650
tags question: http://stackoverflow.com/q/46864270
type: Tag
tags question: http://stackoverflow.com/q/46791191
tags question: http://stackoverflow.com/q/46804912
tags question: http://stackoverflow.com/q/46880576
tags question: http://stackoverflow.com/q/46777181
tags question: http://stackoverflow.com/q/46779605
tags question: http://stackoverflow.com/q/46766662
tags question: http://stackoverflow.com/q/46872385
tags question: http://stackoverflow.com/q/46793110
tags question: http://stackoverflow.com/q/46835181
tags question: http://stackoverflow.com/q/46834013
tags question: http://stackoverflow.com/q/46807106
tags question: http://stackoverflow.com/q/46766714
tags question: http://stackoverflow.com/q/46880894
tags question: http://stackoverflow.com/q/46899217
tags question: http://stackoverflow.com/q/46874061
tags question: http://stackoverflow.com/q/46781448
tags question: http://stackoverflow.com/q/46836848

http://stackoverflow.com/q/46793972
tagged with: python
tagged with: rabbitmq
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: remote-access
type: Question
has title: Why python code cannot connect to RabbitMQ remotely?
has answer: http://stackoverflow.com/a/46796405
has body: I'm trying to connect from the one machine to another remote server with installed RabbitMQ. The RabbitMQ is working perfectly locally, but when I connect to it from the another machine then an error is occurs: root@xxx:~# python3 rabbitmq.py Traceback (most recent call last): File "rabbitmq.py", line 8, in &lt;module&gt; connection = pika.BlockingConnection(pika.ConnectionParameters(parameters)) File "/usr/local/lib/python3.4/dist-packages/pika/connection.py", line 652, in __init__ self.host = host File "/usr/local/lib/python3.4/dist-packages/pika/connection.py", line 392, in host (value,)) TypeError: host must be a str or unicode str, but got &lt;ConnectionParameters host=111.111.111.111 port=5672 virtual_host=product ssl=False&gt; root@xxx:~# TypeError: host must be a str or unicode str, but got ConnectionParameters host=111.111.111.111 port=5672 virtual_host=product ssl=False The Python code on other remote machine: import pika credentials = pika.PlainCredentials(username='remoteuser', password='mypassword') parameters = pika.ConnectionParameters(host='111.111.111.111', port=5672, virtual_host='/', credentials=credentials) #connection = pika.BlockingConnection(pika.ConnectionParameters('111.111.111.111:15672')) # --- it doesn't work too connection = pika.BlockingConnection(pika.ConnectionParameters(parameters)) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close() User "remoteuser" has admin rights and access to virtual host "/" http://111.111.111.111:15672/#/users Name Tags Can access virtual hosts Has password remoteuser administrator / ● What is the problem?
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46796405

http://stackoverflow.com/comment/80568833
score: 0
type: Comment
type: QuestionComment
has text: Unrelated, but do you need CSV? Or can you write JSON, since that's what you're getting anyway? The error exists in the CSV writer, which would work fine even with missing values, but `w.writerow(my_dict)` definitely needs indented
comment on: http://stackoverflow.com/q/46810479

http://stackoverflow.com/comment/80521520
comment on: http://stackoverflow.com/a/46775606
type: Comment
score: 0
type: AnswerComment
has text: @JoeIddon Your answer's first part still conflicts with the second part that's why I am not accepting it. First part insists that django package is installed, while second part contradicts it. Please fix your answer.

http://stackoverflow.com/q/46877639
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46878041
score: 1
type: Question
has comment: http://stackoverflow.com/comment/80702457
has body: Given a model with an m2m field, let's say Article has multiple Authors. What is the most efficient way to get all the articles in which the set of their authors is a subset of another set? class Article(models.Model): authors = models.ManyToManyField('Author') Get all articles that were written by one or many of the authors in this list but doesn't have any author that is not part of this list. authors_list = ['Tom', 'John', 'Sara', 'Kati'] Articles written by 'Tom' would match. Articles written by 'Tom' and 'Sara' would match. But, Articles written by 'Tom' and 'Alter' would NOT match.
tagged with: database-optimization
answer count: 1
downvote count: 0
tagged with: m2m
upvote count: 1
has title: Django many2many is a subset of another set
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/46878041
tagged with: django

http://stackoverflow.com/q/46766048
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46766175
has answer: http://stackoverflow.com/a/46766486
favorite count: 0
tagged with: python
has title: How does pandas argsort work? How do I interpret the result?
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/46766175
accepted answer: http://stackoverflow.com/a/46766486
has body: I have the following pandas series: &gt;&gt;&gt;ser num let 0 a 12 b 11 c 18 1 a 10 b 8 c 5 2 a 8 b 9 c 6 3 a 15 b 10 c 11 When I use argsort, I get this: &gt;&gt;&gt;ser.argsort() num let 0 a 5 b 8 c 4 1 a 6 b 7 c 3 2 a 10 b 1 c 11 3 a 0 b 9 c 2 Which I don't really understand. Shouldn't ser[(1, 'c')] get the lowest value from argsort? I am further confused by how ordering ser according to ser.argsort() works like a charm: &gt;&gt;&gt;ser.iloc[ser.argsort()] num let 1 c 5 2 c 6 1 b 8 2 a 8 b 9 1 a 10 3 b 10 0 b 11 3 c 11 0 a 12 3 a 15 0 c 18 Will appreciate any input to help me sort this out.
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/80604675
comment on: http://stackoverflow.com/q/46828499
has text: Sorry, my question was not clear. I would be happy for argument code completion. But I would also be happy with class attributes code completion. This explain my comment on _dir_(). I don't know the analogue for picking arguments possible values.
score: 0
type: Comment
type: QuestionComment

ruby
tags question: http://stackoverflow.com/q/46772592
tag name: ruby
tags question: http://stackoverflow.com/q/46840920
type: Tag

http://stackoverflow.com/q/46752281
upvote count: 3
tagged with: machine-learning
has answer: http://stackoverflow.com/a/46752816
answer count: 1
has body: I am using the Anaconda distribution of python 2.7 and specifically the iPython shell (not sure if shell is the right term here). When I try to do from matplotlib.colors import ListedColorMap I get back this error: ImportError Traceback (most recent call last) &lt;ipython-input-12-6f067472330e&gt; in &lt;module&gt;() ----&gt; 1 from matplotlib.colors import ListedColorMap ImportError: cannot import name ListedColorMap However, when I do from matplotlib.colors import BoundaryNorm it does work and I don't get any exception. What might be the cause of this issue and how do I fix it?
tagged with: matplotlib
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46752816
score: 3
downvote count: 0
has title: Why can't I import ListedColorMap from matplotlib.colors?
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/46799554
has body: I don't think there is any serious problem with your code. For a list with 3 elements it is much readable if you do what you are already doing rather then writing unnecessary messy loops. I was playing a bit with your code and I changed just a few things, mainly the looks :) import random def get_cards(): nums, suits=['A','2','3','4','5','6','7','8','9','10','J','Q','K'], [u'\u2665',u'\u2663',u'\u2666',u'\u2660'] cards_dealt=[] while len(cards_dealt) &lt; 22: card = random.choice(nums) + random.choice(suits) if card not in cards_dealt: cards_dealt.append(card) else: continue return cards_dealt def get_piles(deck): P1 = [deck[i] for i in range(0,21,3)] P2 = [deck[i] for i in range(1,21,3)] P3 = [deck[i] for i in range(2,21,3)] return P1, P2, P3 ##################################### def get_newdeck(choice, P1, P2, P3): deck = P1+P3+P2 if choice == 1: deck = P2+P1+P3 elif choice == 2: deck = P1+P2+P3 return deck ##################################### def main(): deck = get_cards() print("Choose a card and remember it") for x in range(3): P1, P2, P3 = get_piles(deck) piles = {'Pile 1':P1, 'Pile 2': P2, 'Pile 3':P3} for numpile, pile in sorted(piles.items()): print(numpile+': ', end='\t') for card in pile: print(card, end='\t') print() print() choice = 0 while choice &gt; 3 or choice &lt; 1: while True: try: choice = int(input("Which pile is your card in? (1-3)? &gt; ")) break except ValueError: print("Must be a number") deck = get_newdeck(choice, P1, P2, P3) print() print('Your card is {}'.format(deck[10])) main()
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80553767
answers question: http://stackoverflow.com/q/46798399

http://stackoverflow.com/comment/80788725
has text: I'm not quite sure what your specific question is, but have you taken a look at [ExponentialMovingAverage](https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/train/ExponentialMovingAverage) and [tf.moving_average_variables](https://www.tensorflow.org/api_docs/python/tf/moving_average_variables)?
comment on: http://stackoverflow.com/q/46778562
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46889709
tagged with: apache
has body: I have a Django app on my ubuntu server. Up to now, I was using python 2.7. My Django version is 1.11.6. From now on, I want to use python 3.5. But when I run sudo service apache2 restart I get errors containing python 2.7: [Mon Oct 23 12:40:53.500064 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] mod_wsgi (pid=28615): Target WSGI script '/home/zinonas/guardianangel/GuardianAngel/wsgi.py' cannot be loaded as Python module. [Mon Oct 23 12:40:53.500102 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] mod_wsgi (pid=28615): Exception occurred processing WSGI script '/home/zinonas/guardianangel/GuardianAngel/wsgi.py'. [Mon Oct 23 12:40:53.500125 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] Traceback (most recent call last): [Mon Oct 23 12:40:53.500144 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/home/zinonas/guardianangel/GuardianAngel/wsgi.py", line 15, in &lt;module&gt; [Mon Oct 23 12:40:53.500203 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] application = get_wsgi_application() [Mon Oct 23 12:40:53.500213 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Mon Oct 23 12:40:53.500240 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] django.setup(set_prefix=False) [Mon Oct 23 12:40:53.500250 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup [Mon Oct 23 12:40:53.500281 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon Oct 23 12:40:53.500308 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ [Mon Oct 23 12:40:53.500371 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] self._setup(name) [Mon Oct 23 12:40…
answer count: 1
tagged with: ubuntu
score: 0
has title: django app on server: apache runs with python 2.7 instead of python 3.5
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46889792
tagged with: django
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/46889792

http://stackoverflow.com/comment/80638441
comment on: http://stackoverflow.com/q/46844603
has text: Another thing I forgot to mention earlier: check that your acceleration vector is directed towards the sun, not away from it!
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46876099
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46876240
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has title: Python & BeautifulSoup : Issues with soup.find_all
has comment: http://stackoverflow.com/comment/80699077
has body: h1 = soup.find('a', {'class': 'lien-jv topic-title'})['title'] print (h1) I had no problem to take the value which is in title tag with the soup.find function. But there is multiple tag like that on the page I am parsing, so I've to use the soup.find_all function, and it's not working. With this code h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] print (h1) I had this error Traceback (most recent call last): File "&lt;tmp 1&gt;", line 8, in &lt;module&gt; h1 = soup.find_all('a', {'class': 'lien-jv topic-title'})['title'] TypeError: list indices must be integers, not str Thanks for help.
type: Question
has comment: http://stackoverflow.com/comment/80699095
has answer: http://stackoverflow.com/a/46876151

http://stackoverflow.com/q/46899428
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46899665
has answer: http://stackoverflow.com/a/46902272
type: Question
has body: I'm trying to extract the values in &lt;paste_key&gt; with ElementTree and i'm getting the following error. Can anyone help show me what I'm doing wrong? from pastebin import PastebinAPI from xml.etree import cElementTree as ET import time x = self.apiobject.pastes_by_user(api_dev_key=self.DEVKEY, api_user_key=self.userkey) print x x = ET.fromstring(x) for key in list(x): self.pastekeys.append(key.find('paste_key').text) print self.pastekeys Error output: junk after document element: line 13, column 0 Sample Data that would exist in x &lt;paste&gt; &lt;paste_key&gt;afafafaf&lt;/paste_key&gt; &lt;paste_date&gt;1508796842&lt;/paste_date&gt; &lt;paste_title&gt;1508796842&lt;/paste_title&gt; &lt;paste_size&gt;36096&lt;/paste_size&gt; &lt;paste_expire_date&gt;0&lt;/paste_expire_date&gt; &lt;paste_private&gt;2&lt;/paste_private&gt; &lt;paste_format_long&gt;None&lt;/paste_format_long&gt; &lt;paste_format_short&gt;text&lt;/paste_format_short&gt; &lt;paste_url&gt;https://pastebin.com/afafafaf&lt;/paste_url&gt; &lt;paste_hits&gt;0&lt;/paste_hits&gt; &lt;/paste&gt; &lt;paste&gt; &lt;paste_key&gt;asdfasdf&lt;/paste_key&gt; &lt;paste_date&gt;1508796842&lt;/paste_date&gt; &lt;paste_title&gt;1508796842&lt;/paste_title&gt; &lt;paste_size&gt;36096&lt;/paste_size&gt; &lt;paste_expire_date&gt;0&lt;/paste_expire_date&gt; &lt;paste_private&gt;2&lt;/paste_private&gt; &lt;paste_format_long&gt;None&lt;/paste_format_long&gt; &lt;paste_format_short&gt;text&lt;/paste_format_short&gt; &lt;paste_url&gt;https://pastebin.com/asdfasdf&lt;/paste_url&gt; &lt;paste_hits&gt;0&lt;/paste_hits&gt; &lt;/paste&gt; ...
answer count: 2
tagged with: celementtree
has title: python element tree extract value not working
score: 0
has comment: http://stackoverflow.com/comment/80746079
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/a/46800783
accepted answer of: http://stackoverflow.com/q/46792334
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46792334
type: Answer
has body: As ImportanceOfBeingErnest noted in a comment, you shouldn't transform your ellipse path. Well, using the untransformed path wouldn't directly be useful either; you could probably make use of circle.get_verts(). But let me cut through your Gordian Knot: why not explicitly test for falling inside your ellipse? The equation of an ellipse with center (x0,y0) and semi-axes of length a and b is (x-x0)^2/a^2 + (y-y0)^2/b^2 = 1 and it's really simple to see that the inside of the ellipse is then defined by the inequality (x-x0)^2/a^2 + (y-y0)^2/b^2 &lt; 1 (it's easy to see this for a circle, and you can think of an ellipse as a circle that went through a linear transform along one of its axes). So use logical indexing to find which points are inside your ellipse! The only thing you need to watch out for is that the parameters passed to Ellipse are 2*a and 2*b: points = airbnb_prices['2015']'longitude', 'latitude' # shape (N,2) center = housing_prices_shapes['2015'][0][0] # shape (2,) broadcasts to (N,2) a = unitX / 2 # scalar b = unitY / 2 # scalar # make use of broadcasting while we're at it flag = ((points-center)**2 / np.array([a,b])**2).sum(axis=1) &lt; 1 Now flag is a shape-(N,) logical array, i.e. the same shape and size as expected from your original call to contains_points.
score: 0

http://stackoverflow.com/a/46857914
answers question: http://stackoverflow.com/q/46840037
downvote count: 2
has body: To close this issue: I installed the latest version of Keras from github and got the multi_gpu_model module working as expected. pip install git+git://github.com/fchollet/keras.git --upgrade
type: Answer
upvote count: 4
score: 2

http://stackoverflow.com/comment/80819541
comment on: http://stackoverflow.com/a/46882828
has text: Thanks Mofi! This worked and allowed me to see what the bad process was doing / identified a bug to fix. I knew there was one (somewhere) as of 16,128 issued jobs only 16,023 came back... :) Thanks & hats off to you!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46756628
score: 0
has body: Alright, so I'm a little outside of my league on this one I think. I'm attempting to facilitate custom HTTP headers what is noted here: API-Key = API key API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key from https://www.kraken.com/help/api I'm trying to work solely out of urllib if at all possible. Below is one of many attempts to get it encoded like required: import os import sys import time import datetime import urllib.request import urllib.parse import json import hashlib import hmac import base64 APIKey = 'ThisKey' secret = 'ThisSecret' data = {} data['nonce'] = int(time.time()*1000) data['asset'] = 'ZUSD' uripath = '/0/private/TradeBalance' postdata = urllib.parse.urlencode(data) encoded = (str(data['nonce']) + postdata).encode() message = uripath.encode() + hashlib.sha256(encoded).digest() signature = hmac.new(base64.b64decode(secret), message, hashlib.sha512) sigdigest = base64.b64encode(signature.digest()) #this is purely for checking how things are coming along. print(sigdigest.decode()) headers = { 'API-Key': APIKey, 'API-Sign': sigdigest.decode() } The above may be working just fine, where I'm struggling now is appropriately getting it to the site. This is my most recent attempt: myBalance = urllib.urlopen('https://api.kraken.com/0/private/TradeBalance', urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8"), headers) Any help is greatly appreciated. Thanks!
tagged with: python-3.x
has title: Python3: Custom Encrypted Headers URLLIB - KrakenAPI
tagged with: python
type: AnsweredQuestion
tagged with: urllib
has comment: http://stackoverflow.com/comment/80458605
type: Question
tagged with: api
tagged with: kraken.com
answer count: 1
has answer: http://stackoverflow.com/a/46757158
accepted answer: http://stackoverflow.com/a/46757158

http://stackoverflow.com/q/46854596
answer count: 3
has answer: http://stackoverflow.com/a/46854656
accepted answer: http://stackoverflow.com/a/46854656
has title: simple in memory positional inverted index in python
tagged with: python
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/46854700
has comment: http://stackoverflow.com/comment/80656712
has answer: http://stackoverflow.com/a/72487433
has answer: http://stackoverflow.com/a/46854700
score: 0
has body: I trying to make a simple positional index that but having some problems getting the correct output. Given a list of strings (sentences) I want to use the string position in the sting list as document id and then iterate over the words in the sentence and use the words index in the sentence as its position. Then update a dictionary of words with a tuple of the doc id and it's position in the doc. Code: main func - def doc_pos_index(alist): inv_index= {} words = [word for line in alist for word in line.split(" ")] for word in words: if word not in inv_index: inv_index[word]=[] for item, index in enumerate(alist): # find item and it's index in list for item2, index2 in enumerate(alist[item]): # for words in string find word and it's index if item2 in inv_index: inv_index[i].append(tuple(index, index2)) # if word in index update it's list with tuple of doc index and position return inv_index example list: doc_list= [ 'hello Delivered dejection necessary objection do mr prevailed', 'hello Delivered dejection necessary objection do mr prevailed', 'hello Delivered dejection necessary objection do mr prevailed', 'hello Delivered dejection necessary objection do mr prevailed', 'hello Delivered dejection necessary objection do mr prevailed' ] desired output: {'Delivered': [(0,1),(1,1),(2,1),(3,1),(4,1)], 'necessary': [(0,3),(1,3),(2,3),(3,3),(4,3)], 'dejection': [(0,2),(1,2),(2,2),(3,2),(4,2)], ect...} Current output: {'Delivered': [], 'necessary': [], 'dejection': [], 'do': [], 'objection': [], 'prevailed': [], 'mr': [], 'hello': []} An fyi, I do know about collections libarary and NLTK but I'm mainly doing this for learning/practice reasons.

http://stackoverflow.com/q/46870263
has answer: http://stackoverflow.com/a/46870869
has title: adding items from list to existing dictionary based on key
has body: Say I have this dictionary that uses a id_num as a key {1665845 : Person(1665845, stuff)} {1294919 : Person(1294919, stuff)} And I have another list that has lists containing [Id_num, date, data.....] counts. [[['1665845', '2001-01-06', '28,448,615,27,705'], ['1294919', '2001-01-04', '639,118,328,413,222,491,738,389,11,372,183,650,281,643,26,398,685,171'], ['1294919', '2001-01-03', '771,373']]] How can I sum up all the data belonging to the id_num and add it as a new item in the dictionary {1294919 : Person(1294919, stuff, sum)}
has comment: http://stackoverflow.com/comment/80687793
has comment: http://stackoverflow.com/comment/80687835
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/46870886
has answer: http://stackoverflow.com/a/46870277
type: Question
has answer: http://stackoverflow.com/a/46870349
score: 0

http://stackoverflow.com/comment/80661594
score: 0
has text: It's False every time for me. What do you actually get out of `time.time()`? What is your system time set to, and is it actually ticking?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46856981

http://stackoverflow.com/a/46810186
type: Answer
has comment: http://stackoverflow.com/comment/80567842
has comment: http://stackoverflow.com/comment/80568166
score: 0
answers question: http://stackoverflow.com/q/46810056
has body: Could this be what you want: definition = ['basename', 'dirname', 'supports_unicode_filenames'] condition = ['isabs', 'isdir', 'isfile', 'islink', 'ismount'] result = {i: globals()[i] for i in ['definition', 'condition']}

http://stackoverflow.com/q/46765013
has body: I want to iteratively solve the following (using scipy/numpy of course): (x_n+1)^2 = ((x_n)^2 + x_n+1) + 1 where x_0 = 1 and x_n &gt; 0 for all n and find the first 20 iterations (x_1, x_2,..., x_20) More precisely, at each iteration we have a quadratic equation of the form X^2 - X - ((x_n)^2 + 1). I want to keep finding the positive root for the first 10 iterations. For example when n = 0 we get, x_1^ - x_1 - 2 = 0 We can feed this into a solver such as scipy.optmize.root to find x_1. Use that value from the solver for the next iteration etc. I don't know how to even start coding this kind of a problem. Any help? A bit of math: The discriminant of the above general quadratic is positive and so we do indeed have real solutions.
has answer: http://stackoverflow.com/a/46765427
type: AnsweredQuestion
score: 3
has title: solve an iteratively defined equation using optimize.root
has comment: http://stackoverflow.com/comment/80475640
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80477893
answer count: 1
favorite count: 0
upvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/46765427
downvote count: 0

http://stackoverflow.com/a/46812157
has comment: http://stackoverflow.com/comment/80571573
has comment: http://stackoverflow.com/comment/80571484
has comment: http://stackoverflow.com/comment/80572094
downvote count: 0
has comment: http://stackoverflow.com/comment/80572060
has comment: http://stackoverflow.com/comment/80571611
has comment: http://stackoverflow.com/comment/80571457
has comment: http://stackoverflow.com/comment/80571663
answers question: http://stackoverflow.com/q/46811978
has comment: http://stackoverflow.com/comment/80571597
type: Answer
score: 1
upvote count: 1
has body: You still can do that lambda x: x.mode()[0] df.groupby(['Class',' Code',' Vendor',' State'])[' NumberOfDays'].agg(['mean','min','max','median',lambda x: x.mode()[0]]) Out[8]: mean min max median \ Class Code Vendor State 1 876 Name2 TX 10.043750 5.409722 12.510417 12.211111 2 876 Name1 NY 5.513194 5.513194 5.513194 5.513194 3 123 Name1 NE 6.773148 2.354167 12.584028 5.381250 456 Name2 NY 6.346528 6.346528 6.346528 6.346528 &lt;lambda&gt; Class Code Vendor State 1 876 Name2 TX 5.409722 2 876 Name1 NY 5.513194 3 123 Name1 NE 2.354167 456 Name2 NY 6.346528

http://stackoverflow.com/comment/80702028
has text: You use `super(Avatar, self).create_default_photoset(*args, **kwargs)` that means *call method of parent class*. Try to replace it with `self.create_default_photoset(*args, **kwargs)`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46877249

http://stackoverflow.com/comment/80553698
comment on: http://stackoverflow.com/q/46803527
has text: Did you try combine first?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80676741
type: Comment
comment on: http://stackoverflow.com/q/46864593
has text: Uhm, it is strange..when I try to get the lenght of isactive, I got below error: File "hoy.py", line 291, in <module> print len(isactive) TypeError: object of type 'bool' has no len()
score: 0
type: QuestionComment

http://stackoverflow.com/a/46868319
has body: Use enumerate to create a new list containing the indices of items in y that equal 1, keeping only the indices. ones = [i for i, elem in enumerate(y) if elem == 1] Use random.sample to randomly select items from this new list, in your case, using k=2 samples: sample_ones = random.sample(ones, k=2) sample_ones is a list containing the indices for the randomly-selected elements in y that equal 1.
score: 0
answers question: http://stackoverflow.com/q/46868072
type: Answer

http://stackoverflow.com/q/46778142
has comment: http://stackoverflow.com/comment/80502751
score: 0
tagged with: pandas
tagged with: python
has title: Problems calling pandas_datareader
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80502488
tagged with: anaconda
has body: I would like to install and use pandas_datareader from anaconda, but I am having some trouble. I am installing the package in the same manner as I always do: conda install pandas-datareader The package installs just fine and when I check to see that it is installed with conda list the package is listed as the most recent version of 0.5.0 and is for py27_0. Then if I try something like import pandas_datareader as pdr I always get the following import error ImportError: No module named pandas_datareader I have tried importing datareader from a script and with ipython but I can't figure out why this would be giving me an error.
type: Question

http://stackoverflow.com/comment/80738057
type: Comment
has text: For the second one I get invalid syntax somewhere around approximatelyEqual. I have no idea :/
type: AnswerComment
comment on: http://stackoverflow.com/a/46895361
score: 0

http://stackoverflow.com/comment/88404354
comment on: http://stackoverflow.com/a/46867318
type: Comment
has text: why is it that the series method get_dummies does not accept the argument prefix=... while pandas.get_dummies() does accept it?
score: 1
type: AnswerComment

http://stackoverflow.com/comment/80711859
score: 1
comment on: http://stackoverflow.com/q/46882299
type: Comment
type: QuestionComment
has text: Why are you returning the `num1` and `num2` in your loops ?

http://stackoverflow.com/comment/80652208
comment on: http://stackoverflow.com/a/46851907
has text: yea I tried reading it but did not fully follow it... But thank you, you made it very clear as to where my error was
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80686988
comment on: http://stackoverflow.com/a/46869716
type: AnswerComment
score: 0
type: Comment
has text: @MiguelNunez No, forget Python2, it's worse in every way (except certain very few 3rd party packages that *still* haven't updated)

http://stackoverflow.com/a/46832579
has body: You are using your temperature as the index value in this line: date = data["DATE"][maxvalue] maxvalue is a temperature and you are using it as an index. You can get the index value (i.e. the date) via: date = data.DATE[data.TX==maxvalue] NOTE: if using floats, be careful in comparing the float values.
has comment: http://stackoverflow.com/comment/80613082
has comment: http://stackoverflow.com/comment/80614036
answers question: http://stackoverflow.com/q/46832108
score: 0
has comment: http://stackoverflow.com/comment/80614732
type: Answer
has comment: http://stackoverflow.com/comment/80614174
has comment: http://stackoverflow.com/comment/80613530

http://stackoverflow.com/comment/80458546
type: Comment
has text: This works, but doesn't do what I'm after. I need to keep all the numeric data in the MJD_DUPLICATES, not just a second column.
comment on: http://stackoverflow.com/a/46756542
score: 0
type: AnswerComment

http://stackoverflow.com/a/74946986
score: -1
downvote count: 1
type: Answer
upvote count: 0
has body: To store image with bounding box: cv2.imwrite('output.jpg',input_image) eg. Input Image : Saved Image :
answers question: http://stackoverflow.com/q/46879245

http://stackoverflow.com/a/46813220
has comment: http://stackoverflow.com/comment/80573789
answers question: http://stackoverflow.com/q/46812446
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: So basically since keys need to be sorted in the nested dict, go through the dictionary and transfer the data to a new dictionary. &gt;&gt;&gt; new_d = OrderedDict() &gt;&gt;&gt; for key,val in d.items(): #go through the dictionary new_d[key] = OrderedDict(sorted(val.items())) #sort according to keys #driver values IN : d { 'test' :{ 0:[1,3] , 1:[5,6] }, 'test2':{ 7:[9], 3:[4,6] } } OUT : new_d OrderedDict([('test', {0: [1, 3], 1: [5, 6]}), ('test2', {3: [4, 6], 7: [9]})]) Edit : As the OP wants the dictionary's initial keys (EX : test3:{ ... } , test2:{ ... } ) to be sorted too, the below changes need to be done : &gt;&gt;&gt; initial_sort = OrderedDict(sorted(d.items())) &gt;&gt;&gt; inital_sort OrderedDict([('test2', {7: [9], 3: [4, 6]}), ('test3', {0: [1, 3], 1: [5, 6]})]) &gt;&gt;&gt; new_d = OrderedDict() &gt;&gt;&gt; for key,val in initial_sort.items(): #go through the first key sorted dictionary new_d[key] = OrderedDict(sorted(val.items())) #driver values IN : d = {'test3': {0: [1, 3], 1: [5, 6]}, 'test2': {7: [9], 3: [4, 6]}} OUT : new_d = OrderedDict([('test2', OrderedDict([(3, [4, 6]), (7, [9])])), ('test3', OrderedDict([(0, [1, 3]), (1, [5, 6])]))])

http://stackoverflow.com/comment/80723279
comment on: http://stackoverflow.com/q/46887762
score: 0
type: Comment
type: QuestionComment
has text: try to create the unique xpath. Use the tag names in the xpath accordingly.

http://stackoverflow.com/q/46828879
has comment: http://stackoverflow.com/comment/84813456
has body: Say I have this df: sort_countries"country", "Total".to_dict() {'Total': {'Afghanistan': 1, 'Albania': 1, 'Algeria': 1, 'Argentina': 6, 'Armenia': 5, 'Australia': 76, 'Austria': 9, 'Bangladesh': 1, 'Barbados': 1, 'Belarus': 12, 'Belgium': 27, 'Brazil': 34, 'Bulgaria': 2, 'Canada': 78, 'Chile': 3, 'China': 149, 'Colombia': 4, 'Costa Rica': 1, 'Croatia': 4, 'Czech Republic': 14, 'Denmark': 6, 'Ecuador': 1, 'Egypt': 4, 'El Salvador': 1, 'Estonia': 7, 'Finland': 18, 'France': 125, 'Germany': 106, 'Greece': 18, 'Hungary': 13, 'India': 145, 'Indonesia': 4, 'Iran': 6, 'Ireland': 10, 'Israel': 28, 'Italy': 31, 'Japan': 74, 'Kenya': 1, 'Kyrgyzstan': 1, 'Latvia': 2, 'Lebanon': 1, 'Lithuania': 7, 'Luxembourg': 1, 'Macedonia': 1, 'Madagascar': 2, 'Malaysia': 4, 'Mauritius': 1, 'Mexico': 3, 'Moldova': 1, 'Morocco': 2, 'Mozambique': 1, 'Nepal': 1, 'Netherlands': 59, 'New Zealand': 10, 'Nigeria': 1, 'North Korea': 1, 'Norway': 6, 'Pakistan': 1, 'Panama': 1, 'Philippines': 6, 'Poland': 51, 'Portugal': 15, 'Qatar': 1, 'Romania': 8, 'Russian Federation': 223, 'Senegal': 1, 'Serbia': 3, 'Singapore': 55, 'Slovakia': 8, 'Slovenia': 6, 'South Africa': 13, 'South Korea': 11, 'Spain': 52, 'Sri Lanka': 5, 'Sweden': 20, 'Switzerland': 24, 'Taiwan': 27, 'Thailand': 2, 'Turkey': 10, 'Ukraine': 40, 'United Arab Emirates': 2, 'United Kingdom': 117, 'United States': 852, 'Venezuela': 2, 'Vietnam': 5}, 'country': {'Afghanistan': 'Afghanistan', 'Albania': 'Albania', 'Algeria': 'Algeria', 'Argentina': 'Argentina', 'Armenia': 'Armenia', 'Australia': 'Australia', 'Austria': 'Austria', 'Bangladesh': 'Bangladesh', 'Barbados': 'Barbados', 'Belarus': 'Belarus', 'Belgium': 'Belgium', 'Brazil': 'Brazil', 'Bulgaria': 'Bulgaria', 'Canada': 'Canada', 'Chile': 'Chile', 'China': 'China', 'Colombia': 'Colombia', 'Costa Rica': 'Costa Rica', 'Croatia': 'Croatia', 'Czech Republic': 'Czech Republic', 'Denmark': 'Denmark', 'Ecuador': 'Ecuador', 'Egypt': 'Egypt', 'El Salvador': 'El Salvador', 'Estonia': 'Estonia', …
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/46828992
accepted answer: http://stackoverflow.com/a/46828992
upvote count: 1
has title: Pandas apply function row by row
tagged with: pandas
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/80694900
type: Comment
type: QuestionComment
has text: edited! for er_ai I would need: count number of entries which are >0 and divide by number of all entries
comment on: http://stackoverflow.com/q/46873846
score: 0

http://stackoverflow.com/a/46851042
has body: If your DataFrame is called df try this: df['hour'] = Series(np.random.randint(0,24), index=df.index) This should add a column with name 'hour' filled with integers generated between 0 and 23.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46850934

http://stackoverflow.com/a/46908660
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You are probably calling tf.global_variables_initializer().run() in build_graph after you restored the model. So you basically load the weights and then overwrite them with the initialisation values and your network starts from scratch. I implemented restoring the checkpoints with command line options for a small project working with Latin and you can have a look at the code here: https://github.com/CarstenIsert/LatinLearner/blob/master/word2vec.py
answers question: http://stackoverflow.com/q/46785690
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/80770952
accepted answer of: http://stackoverflow.com/q/46785690

http://stackoverflow.com/q/46799070
linked to: http://stackoverflow.com/q/20849805
tagged with: amazon-s3
has body: I am using the following code to make a simple PUT request to AWS S3 using a version 4 signature: from collections import OrderedDict from dateutil import parser import datetime import hashlib import hmac import requests key_id = "REDACTED" secret = "REDACTED" bucket_name = "REDACTED" def hashb16(message): return hashlib.sha256(message).hexdigest() def HMAC(key, message): return hmac.new(key, message, hashlib.sha256) current_time = datetime.datetime.utcnow() url = "https://s3-eu-west-2.amazonaws.com/{}/sometest.txt".format(bucket_name) payload = "Welcome to Amazon S3." headers = { 'date': current_time.strftime("%a, %d %b %Y %H:%m:%S GMT"), 'host': "s3-eu-west-2.amazonaws.com", 'x-amz-content-sha256': hashb16(payload), 'x-amz-date': current_time.strftime('%Y%m%dT%H%M%SZ'), 'x-amz-storage-class': 'REDUCED_REDUNDANCY' } sorted_headers = sorted([k for k in headers]) region = "eu-west-2" service = "s3" # step 1 HTTPRequestMethod = "PUT" CanonicalURI = "/sometest.txt" CanonicalQueryString = "" CanonicalHeaders = "" for key in sorted_headers: CanonicalHeaders += "{}:{}\n".format(key.lower(), headers[key]) SignedHeaders = "{}".format(";".join(sorted_headers)) HexEncondeHashRequestPayload = hashb16(payload) CanonicalRequest = "{}\n{}\n{}\n{}{}\n{}".format(HTTPRequestMethod, CanonicalURI, CanonicalQueryString, CanonicalHeaders, SignedHeaders, HexEncondeHashRequestPayload) # step 2 Algorithm = "AWS4-HMAC-SHA256" RequestDateTime = current_time.strftime('%Y%m%dT%H%M%SZ') CredentialScope = "{}/{}/{}/{}".format(current_time.strftime("%Y%m%d"), region, service, "aws4_request") HashedCanonicalRequest = hashb16(CanonicalRequest) StringToSign = "{}\n{}\n{}\n{}".format(Algorithm, RequestDateTime, CredentialScope, HashedCanonicalRequest) #step 3 kDate = HMAC("AWS4" + secret, current_time.strftime("%Y%m%d")).digest() kRegion = HMAC(kDate, region).digest() kService = HMAC(kRegion, service).digest() kSigning = HMAC(kService, "aws4_request").digest() signature = HMAC(kSigning, StringToSign)…
tagged with: sign
type: AnsweredQuestion
has title: What I am doing wrong with S3 PUT request using AWS Signature Version 4
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/46800349
type: Question
tagged with: python
score: 0
accepted answer: http://stackoverflow.com/a/46800349
answer count: 1

http://stackoverflow.com/comment/80730675
score: 0
type: Comment
type: QuestionComment
has text: So you want to check if a certain element (`el_12`) is found in a certain position (second position)?
comment on: http://stackoverflow.com/q/46891727

http://stackoverflow.com/comment/80630079
has text: Ahah! That did it. Turns out there was some other code running elsewhere that was monkeypatching os.path.exists and screwing everything up, it all makes sense now.
score: 0
comment on: http://stackoverflow.com/q/46840481
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80601955
type: Comment
comment on: http://stackoverflow.com/a/46827237
has text: Use `{}` for set comprehension, you created a generator
score: 0
type: AnswerComment

http://stackoverflow.com/a/46871637
has comment: http://stackoverflow.com/comment/80695679
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46870621
answers question: http://stackoverflow.com/q/46870621
has body: WFM on an x32 machine with 1,25GB of RAM. So the issue must be something not related to the specific code you presented. Doing the operation one step at a time and checking memory consumption by variables, by the process and objects' internal state might give you a clue. (As is the good old problem localization: if it goes away when you throw away other parts of the code, or throw everything away then start adding it back. Adding/removing half the amount at a time will give you a result in a logarithmic number of steps.) In [41]: x=np.random.randint(2**30,size=(260923*225),dtype=np.int64).reshape( ...: (260923,225)) In [42]: x.nbytes Out[42]: 469661400 In [43]: x_selected = x[:,0] In [44]: x_selected.nbytes Out[44]: 2087384 In [45]: from dump import dump In [46]: dump(x_selected) T : [ 728497578 1063110548 71820681 ..., 701362408 1030850648 908176708] base : [728497578 297238747 162734746 ..., 262530510 654517286 329271071] ctypes : &lt;numpy.core._internal._ctypes object at 0x028DEC10&gt; dtype : int64 flags : C_CONTIGUOUS : False F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False flat : &lt;numpy.flatiter object at 0x027A3C30&gt; imag : [0 0 0 ..., 0 0 0] itemsize : 8 nbytes : 2087384 ndim : 1 real : [ 728497578 1063110548 71820681 ..., 701362408 1030850648 908176708] shape : (260923,) size : 260923 strides : (1800,) In [58]: x.base is None Out[58]: False #due to .reshape(), x does not own its memory In [57]: x_selected.base is x.base Out[57]: True # but they use the same memory anyway, so x_selected does not use up extra In [48]: c=(x_selected &gt;1000000) In [49]: c.nbytes Out[49]: 260923 #c is an ndarray of bools, each bool is thus 1 byte In [50]: n=c.nonzero() In [59]: sys.getsizeof(n) Out[59]: 32 #just holds a reference to the sole element In [51]: r=n[0] In [52]: r.nbytes Out[52]: 1042656
type: Answer

http://stackoverflow.com/comment/80614371
has text: @zplush Happy to help! If this answer or any other one solved your issue, please mark it as accepted: stackoverflow.com/help/someone-answers
comment on: http://stackoverflow.com/a/46833220
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/80687266
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46864539
has text: Should your new array be an entirely new array of arrays, not sharing any storage with the old array? So your problems are coming about because you are modifying the original board, not a copy?

http://stackoverflow.com/comment/80548235
has text: Thanks for your answers gogomo! but unfortunately I couldn't load the model using the load() method, and that's why I search for help in stackflow to find if there is anyone who write some code to fix that problem (and the gensim version problem as well).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46797974

http://stackoverflow.com/a/77263540
type: Answer
has body: Use pypdf (PyPDF2 is deprecated) I'm the maintainer of both libraries. Here is an example how to add metadata to a given document using pypdf: from pypdf import PdfWriter writer = PdfWriter(clone_from="source.pdf") writer.add_metadata( { "/Author": "Martin", "/Producer": "Libre Writer", "/Title": "Title", "/Subject": "Subject", "/Keywords": "Keywords", "/Creator": "Creator", "/CustomField": "CustomField", } ) with open("result.pdf", "wb") as fp: writer.write(fp)
score: 7
answers question: http://stackoverflow.com/q/46849733
upvote count: 7
downvote count: 0

http://stackoverflow.com/comment/93346072
type: AnswerComment
has text: @AmirHadi Your best bet would be to get off Channels 1. Channels 2 uses asyncio. If you write all your code async and don't write code that blocks the event loop you should be able to handle many thousands of connections. You need to be careful because any of the default caching or database methods in Django will block the event loop and make your site run slower than if it was running Channels 1. You need to make sure your using async versions of all the libraries that do IO or wrap the methods that do IO in the `@sync_to_async` decorator.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/46775484

http://stackoverflow.com/q/46844963
has comment: http://stackoverflow.com/comment/80638981
has comment: http://stackoverflow.com/comment/80637920
tagged with: python
has title: Python / matplotlib: print to resolution and without white space / borders / margins
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: plot
type: Question
has answer: http://stackoverflow.com/a/46849891
has comment: http://stackoverflow.com/comment/80637935
has comment: http://stackoverflow.com/comment/80640005
tagged with: matplotlib
has body: I have time series data (signal) of different length that I would like to plot without any margins between scale and signal. Goal: plot each signal so (physical) printing of the plot will show every single data point. The plot shall be saved to a file. Given: printer with 600 dpi maximum printing resolution. signals with different number of data points (from 30000 to 100000). example of signal: import numpy as np Fs = 512 # Create random signal np.random.seed(1) data = [np.random.uniform(-10000, 20000) for i in range(5*Fs)] If I just plot it with matplotlib: import matplotlib.pyplot as plt plt.figure(figsize=(len(data)/600,2)) # divide by 600 which is dpi resolution of printer plt.plot(data, color = "black", linewidth = 1.0) plt.show() I do not want any white space between the first data point and the Y axis or between the last data point and the right border. The label of the Y axis should also not interfere with the plot's size, so its width should also be considered. How do I accomplish to have every single point printed?
answer count: 1
has comment: http://stackoverflow.com/comment/80760575
downvote count: 0
accepted answer: http://stackoverflow.com/a/46849891
favorite count: 0

http://stackoverflow.com/q/46897952
tagged with: unique
tagged with: python-3.x
tagged with: right-to-left
has answer: http://stackoverflow.com/a/46898177
type: AnsweredQuestion
type: Question
upvote count: 4
answer count: 1
downvote count: 0
has title: Remove Right-to-left character \u200f in Python (Hebrew)
score: 4
accepted answer: http://stackoverflow.com/a/46898177
favorite count: 0
tagged with: pandas
tagged with: python
has body: I have a dataframe, and I want the unique strings of a specific column. The strings are in Hebrew. Because I'm using pandas dataframe, I wrote: all_names = history.name.unique() (history is the data frame with a name column). I get strange duplicates with the character. Like ערן and another one with the all_names array(['ערן', 'ערן', ...., None], dtype=object) How can I remove these characters? (From the original data frame)

http://stackoverflow.com/a/46795569
accepted answer of: http://stackoverflow.com/q/46794890
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46794890
has body: Problem solved, thanks to @pgv. issue 1: Node arguments need to be passed as key=value pairs, not a dict issue 2: fillcolor does not work by itself, parameter style must be set to "filled" corrected code: import pydotplus as ptp graph = ptp.Dot(graph_type='graph') edges = [(1,2), (1,3), (2,4), (2,5), (3,5)] nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")] for e in edges: graph.add_edge(ptp.Edge(e[0], e[1])) for n in nodes: node = ptp.Node(name=n[0], label= n[1], fillcolor=n[2], style="filled" ) graph.add_node(node) graph.write_png("file.png")
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/80572076
has text: Okay, change `lambda`s to classic functions :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46812283

http://stackoverflow.com/comment/80545624
type: QuestionComment
comment on: http://stackoverflow.com/q/46798527
has text: Can you share the site? I would be interested in trying a few things.
score: 0
type: Comment

http://stackoverflow.com/comment/80706822
comment on: http://stackoverflow.com/q/46879790
score: 0
type: Comment
type: QuestionComment
has text: did you try pip install fpdf

http://stackoverflow.com/a/46915969
answers question: http://stackoverflow.com/q/46901622
has body: On many Python third party libraries (including matplotlib), you can look at the source and see what is going on behind the scenes and often you can use that as a guide for what you want to do - maybe even an opportunity for a subclass to implement your customization or. bezier.Curve.plot source is pretty straightforward and if your intent is to just plot the curve you can use its code, in your own (bezier.Curve.evaluate_multi returns numpy.ndarray: The points on the curve. As a two dimensional NumPy array, with the rows corresponding to each *s* value and the columns to the dimension. nodes1 = np.array([[0.0, 0.0],[0.625, .75], [1.0, 1.0]]) curve1 = bezier.Curve(nodes1, degree=2) # if you need to create x values. s_vals = np.linspace(0.0, 1.0, num_pts) points = curve1.evaluate_multi(s_vals) Where the x values are points[:, 0] and the y values are points[:, 1]. Depending on what you actually need... (from pylab_examples example code: subplots_demo.py f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(points[:, 0], points[:, 1]) ax1.set_title('Sharing Y axis') ax2.scatter(points[:, 0], points[:, 1]) I haven't actually tried this - lacking bezier on this machine.
score: 0
type: Answer

http://stackoverflow.com/comment/80755602
has text: Can You provide some other way by using google s2 library only
comment on: http://stackoverflow.com/q/46903935
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80596029
type: Comment
has text: Thanks stamaimer
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46824155

http://stackoverflow.com/a/46867529
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46867407
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46867407
has comment: http://stackoverflow.com/comment/80682459
has body: The problem here is that you're trying to create the source file path by joining source variable and files. Here source is a list of all the files and folders in your "Rides" directory. It is not possible to join a list of files and folders to a folder name. That is why the error is happening. So replacing os.path.join(source, files) to os.path.join(root_path, files) should work for you. if (files.startswith('2016_')): shutil.move(os.path.join(source, files), dest1) should be changed to if (files.startswith('2016_')): shutil.move(os.path.join(root_path, files), dest1)
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/80665021
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46781541
has text: This means that the credentials that you supplied are either wrong (typo) or do not have permission to create a key pair. Where did your access key come from? What policy is attached to the user that created the access key? You will find these details in the Amazon IAM console. Update your question with these details. Note: do not include your access key in your question. Suggestion, go to the IAM console and create a new set of keys and try those. Make sure that the user's policy grants EC2 permissions.
type: Comment

http://stackoverflow.com/a/46843905
answers question: http://stackoverflow.com/q/46812096
score: 0
type: Answer
has body: The error you get is related to the fact that you quantified a $ end-of-string anchor. An unescaped $ is a zero-width assertion that match at the end of the string. To match a literal $, you need to escape it. The . chars in your expression also need to get escaped to match literal dots. However, there is also a problem with - forming a range in the character class in [][.,;"'?():-_`]. To make sure - matches a -, put it at the end, before the last ]. Besides, it seems you want to match words that do not contain underscores (as you placed the _ in the last character class). Thus, I suggest to subtract _ form \w pattern, and replace \w+(?:-\w+)* with [^\W_]+(?:-[^\W_]+)*. Here is a pattern with my suggestions implemented: sentence_re = r'''\$?\d+(?:\.\d+)?%?|[A-Z](?:\.[A-Z])+\.?|[^\W_]+(?:-[^\W_]+)*|(?:\.{3}|)[][.,;"'?():_`-]''' See the regex demo

http://stackoverflow.com/a/46819249
type: Answer
has body: Just read the last few bytes and use a regular expression in order to extract the float number. Untested: import re with open('/path/to/file.txt') as input_file: input_file.seek(-100, 2) last_100_bytes = input_file.read() match = re.search(r'\D(\d+\.\d+)$', last_100_bytes) if match: print('The float is {}'.format(match.group(0))) else: print('no float found at the end of the file')
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46819094
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80625017
answers question: http://stackoverflow.com/q/46819094

http://stackoverflow.com/q/46783142
has answer: http://stackoverflow.com/a/46795374
answer count: 2
tagged with: beautifulsoup
score: 0
has title: Python: not every web page have a certain element
tagged with: python
has answer: http://stackoverflow.com/a/46783311
type: UnansweredQuestion
tagged with: web-scraping
type: Question
has body: When I tried to use urls to scrape web pages, I found that some elements only exists in some pages and other have not. Let's take the code for example Code: for urls in article_url_set: re=requests.get(urls) soup=BeautifulSoup(re.text.encode('utf-8'), "html.parser") title_tag = soup.select_one('.page_article_title') if title_tag=True: print(title_tag.text) else: #do something if title_tag exits, I want to print them, if it's not, just skip them. Another thing is that, I need to save other elements and title.tag.text in data. data={ "Title":title_tag.text, "Registration":fruit_tag.text, "Keywords":list2 } It will have an error cause not all the article have Title, what should I do to skip them when I try to save? 'NoneType' object has no attribute 'text' Edit: I decide not to skip them and keep them as Null or None.

http://stackoverflow.com/q/46756457
type: Question
has title: Saving Animation in matplotlib of Progress Line
has body: Objective: To save a plotted graph(x,y) with a moving a vertical line over the graph w.r.t to timer. I've built a simple graph with a moving vertical progress line basically identical to this example, but I now need to save it. I do not need the functionality to relocate the progress bar on-click, only to have the progress bar move along the data. I'm not sure where to call the save function because this code does not rely on FuncAnimation. import sys import matplotlib.pyplot as plt import time import numpy fig = plt.figure() ax = fig.add_subplot(111) max_height = 100 n_pts = 100 y1 = [0, max_height] x1 = [0, 0] y = numpy.random.randn(n_pts) * max_height x = numpy.arange(0, n_pts) # draw the data line1, = ax.plot(x, y, color='black') # fix the limits of the plot ax.set_ylim(0, max_height) ax.set_xlim(0, n_pts) # draw the plot so that we can capture the background and then use blitting plt.show(block=False) # get the canvas object canvas = ax.figure.canvas background = canvas.copy_from_bbox(ax.bbox) # add the progress line. # XXX consider using axvline line, = ax.plot(x1, y1, color='r', animated=True) starttime=time.time() mytimer=0 mytimer_ref=0 def update(canvas, line, ax): # revert the canvas to the state before any progress line was drawn canvas.restore_region(background) # compute the distance that the progress line has made (based on running time) t = time.time() - starttime mytimer = t + mytimer_ref x1 = [mytimer,mytimer] # update the progress line with its new position line.set_xdata(x1) # draw the line, and blit the axes ax.draw_artist(line) canvas.blit(ax.bbox) timer=fig.canvas.new_timer(interval=100) args=[canvas,line,ax] timer.add_callback(update,*args) # every 100ms it calls update function timer.start() plt.show()
score: 0
has comment: http://stackoverflow.com/comment/80511187
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80489746
tagged with: animation
tagged with: python
linked to: http://stackoverflow.com/q/11942936
tagged with: matplotlib
tagged with: save

http://stackoverflow.com/comment/80465450
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46759928
has text: You're welcome! If this solution resolved your issue, please mark it accepted by clicking the checkmark next to the answer.

http://stackoverflow.com/comment/80751202
score: 0
type: Comment
has text: @qu2021 If you replace the `break` with `return`, it will work the same. Also, if you are using Python 2, make sure to write `str(input())` to make sure you have a string `'1'` instead of an integer `1`.
comment on: http://stackoverflow.com/a/46901591
type: AnswerComment

http://stackoverflow.com/a/62701856
score: 0
type: Answer
has body: I know that post is old but for those who are in 2020 is looking for solution( all browsers and not only chrome) that can be achieved with BrowserMob(BrowserUP) proxy itself - you can set a rules on requests and responses that will delete headers related to caching mechanisms in browsers( there are lot of them). Below are scripts I use( them might be incomplete so if you found what is missing please let know): Requests: curl --location --request POST 'your_proxy_api_host:your_proxy_api_port/proxy/your_proxy_port/filter/request' \ --header 'Content-Type: text/plain' \ --data-raw 'request.headers().remove('\''If-Modified-Since'\'');request.headers().remove('\''If-None-Match'\'');' Response: curl --location --request POST '0.0.0.0:8080/proxy/8081/filter/response' \ --header 'Content-Type: text/plain' \ --data-raw 'response.headers().remove('\''Age'\'');response.headers().remove('\''ETag'\'');response.headers().remove('\''Cache-Control'\'');response.headers().remove('\''Expires'\'');response.headers().remove('\''Last-Modified'\'');response.headers().remove('\''Vary'\'');response.headers().add('\''Expires'\'', 0);response.headers().add('\''Cache-Control'\'', '\''private'\'');response.headers().add('\''Cache-Control'\'', '\''no-cache'\'');response.headers().add('\''Cache-Control'\'', '\''no-store'\'');response.headers().add('\''Cache-Control'\'', '\''must-revalidate'\'');response.headers().add('\''Vary'\'', '\''*'\'');' I work with http 1.1 so I didn't add anything for http 1.0 or http 2.0. Checked on Chrome Edge Safari FF. Also, I use little proxy api( new api of browsermob) - for reference
answers question: http://stackoverflow.com/q/46791043

http://stackoverflow.com/comment/80560404
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46806127
has text: I know I can use MLPRegressor in Scikit-learn, however there is no way of using cosine similarity instead of the dot product..
score: 0

http://stackoverflow.com/comment/80707614
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46880050
score: 0
has text: The original dataset had many records with an `occurred_date` and `nc_type` associated and I used groupby to get to my current dataframe

http://stackoverflow.com/comment/103542443
score: 1
type: AnswerComment
type: Comment
has text: this helped me.
comment on: http://stackoverflow.com/a/46813599

http://stackoverflow.com/comment/80686252
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46869511
has text: Nice, thank you ! I'll try it now. It looks like I'll have to adapt it, but you gave me the direction, thanks.
score: 0

http://stackoverflow.com/comment/80578613
score: 0
comment on: http://stackoverflow.com/q/46815492
type: Comment
type: QuestionComment
has text: to turn off the camera i am using release nd recreate the object... also to keep the buffer empty.

http://stackoverflow.com/comment/80547631
score: 1
has text: Have you tried spieler.split("\n")?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46800335

http://stackoverflow.com/comment/87369756
comment on: http://stackoverflow.com/a/46829613
has text: Why is `in` included for `boto3.dynamodb.conditions` but DynamoDB does not support it yet?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46844603
linked to: http://stackoverflow.com/q/29009771
answer count: 1
has title: Gravity Problems
has comment: http://stackoverflow.com/comment/80637495
has comment: http://stackoverflow.com/comment/80637149
has comment: http://stackoverflow.com/comment/80637025
accepted answer: http://stackoverflow.com/a/46845856
has comment: http://stackoverflow.com/comment/80637226
has comment: http://stackoverflow.com/comment/80638261
has comment: http://stackoverflow.com/comment/80638402
has comment: http://stackoverflow.com/comment/80637409
has body: I've been trying to make a code with pygame to simulate simple gravity. At the moment, there is only one object (HOM) which is orbiting the sun. However, for reasons unknown to me, whenever I run the code, HOM travels round the sun in an orbit at the start, but then accelerates away from the sun when it reaches ~135 degrees from vertical. Does anyone know why this is happening and how I can fix it? I have been printing some variables to try and source the problem, but have had no luck so far. Code: import pygame,sys,time from math import * screen=pygame.display.set_mode((800,600)) G = 5 class Object: #Just an object, like a moon or planet def __init__(self,mass,init_cds,init_vel,orbit_obj='Sun'): self.mass = mass self.cds = init_cds self.velocity = init_vel self.accel = [0,0] self.angle = 0 self.orb_obj = orbit_obj def display(self): int_cds = (round(self.cds[0]),round(self.cds[1]))#Stores its co-ordinates as floats, has to convert to integers for draw function pygame.draw.circle(screen,(255,0,0),int_cds,10) def calc_gravity(self): if self.orb_obj == 'Sun': c_x,c_y = 400,300 c_mass = 10000 else: c_x,c_y = self.orb_obj.cds c_mass = self.orb_obj.mass d_x = self.cds[0]-c_x d_y = self.cds[1]-c_y dist = sqrt(d_x**2+d_y**2) #Find direct distance angle = atan(d_x/d_y) #Find angle print(d_x,d_y) print(dist,degrees(angle)) if dist == 0: acc = 0 else: acc = G*c_mass/(dist**2) #F=G(Mm)/r^2, a=F/m -&gt; a=GM/r^2 print(acc) acc_x = acc*sin(angle) #Convert acceleration from magnitude+angle -&gt; x and y components acc_y = acc*cos(angle) self.accel = [acc_x,acc_y] print(self.accel) self.velocity = [self.velocity[0]+self.accel[0],self.velocity[1]+self.accel[1]] #Add acceleration to velocity print(self.velocity) self.cds = (self.cds[0]+self.velocity[0],self.cds[1]+self.velocity[1]) #Change co-ordinates by velocity print(self.cds) print('-------------------') #For seperating each run of the function when printing variables HOM = Object(1000000,(400,100),[10,0]) #The problem planet cl…
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80637232
type: Question
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/46845856
has comment: http://stackoverflow.com/comment/80638441
has comment: http://stackoverflow.com/comment/80637892
has comment: http://stackoverflow.com/comment/80637094
upvote count: 1

http://stackoverflow.com/q/46842951
has comment: http://stackoverflow.com/comment/80649900
favorite count: 0
tagged with: gpu
has body: I am a beginner trying to learn how to use a GPU to perform high speed calculations.I am trying to implement a simple FFT program using GPU. Below is the program I used for calculating FFT using the CPU core. from time import time as timer import numpy as np import matplotlib.pyplot as plt winsize=512 shift=16 my_cmap='gray_r' Fs = 8000 f = 1000 sample =200000 x = np.arange(sample) y = np.sin(2 * np.pi * f * x / Fs) data_len=len(y) window_func=np.blackman(winsize) fftdata=np.zeros((0,int(winsize/2))) startime=timer() for frame in range(0, data_len, shift): #============================================================================== # if frame&gt;0: # break #============================================================================== kiri=y[frame:frame+winsize] if len(kiri) != winsize: break windata = window_func * kiri fftframe=np.fft.fft(windata,n=winsize) magframe=np.abs(fftframe)**2 powerframe=np.log10(magframe):int(winsize/2)].reshape((1,int(winsize/2))) fftdata=np.append(fftdata,powerframe,axis=0) endtime=timer()-startime fftdata=np.asarray(fftdata) fftfrq=np.fft.fftfreq(winsize,d=1/Fs)[:int(winsize/2)] print("CPU runtime:",endtime,"sec") Now below figure is the output as spectrogram when plotted using imshow() function: Timing output is as follows: CPU runtime: 65.02100014686584 sec Now I rewrite the above program to use the GPU of my PC which is Quadro K2200 using pyculib and numba packages offered by Anaconda. from time import time as timer import numpy as np import pyculib.fft from numba import cuda import matplotlib.pyplot as plt winsize=512 shift=16 Fs = 8000 f = 1000 sample =200000 t = np.arange(sample,dtype=np.float64) y = np.sin(2 * np.pi * f * t / Fs) my_cmap='gray_r' data_len=len(y) window_func=np.blackman(winsize) fftdata_gpu=np.zeros((0,int(winsize/2))) startime=timer() for frame in range(0, data_len, shift): # ============================================================================= # if frame&gt;0: # break # =============================…
tagged with: numba
has title: pyculib fft using gpu: speed up
has comment: http://stackoverflow.com/comment/80834992
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
tagged with: cufft
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/80835374
score: 1

http://stackoverflow.com/comment/80736970
comment on: http://stackoverflow.com/a/46894759
has text: @Luke: I edited the answer by what I think is valid MySQL.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46750017
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/80446191
has title: np.dot(A,A,A) changes the value of A
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80446085
has body: Let A be a fixed matrix in numpy, then after executing the function &gt;&gt; np.dot(A,A,A) the value of A change. I don't understand why this is happening? The same if I execute for a given matrix B the function &gt;&gt;&gt; np.matmul(B,B,B) then the value of B is setting to zero. Why?
answer count: 0
has comment: http://stackoverflow.com/comment/80446146
has comment: http://stackoverflow.com/comment/80446272

http://stackoverflow.com/comment/80677483
comment on: http://stackoverflow.com/q/46863993
score: 0
has text: just use Block() to initialize the block. I use a subclass to initialize the group, in the same fashion. Then I set block.goup
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46793573
has comment: http://stackoverflow.com/comment/80534058
has title: 4suite-xml for Python 3.6?
has comment: http://stackoverflow.com/comment/80585282
tagged with: python-3.6
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80534238
has comment: http://stackoverflow.com/comment/80534149
favorite count: 0
has body: I have an application that was written in Python 2.4 that I have taken over development for. I have since converted the application to Python 3, but parts of the application use 4suite-xml. Is it possible to get 4suite-xml under Python 3? I have tried 'pip3 install 4suite-xml' but it fails to install.
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46877010
accepted answer: http://stackoverflow.com/a/46877010
has comment: http://stackoverflow.com/comment/80534227
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80535468

http://stackoverflow.com/a/46815722
accepted answer of: http://stackoverflow.com/q/46801833
answers question: http://stackoverflow.com/q/46801833
type: Answer
has body: I changed the name of your last column to vs_2 before creating the initial data frame, since you already have a column named vs. After that, the following seems to work: remaining_columns = columns[4:] for num, col in enumerate(remaining_columns, start=2): print(num, col) # Flatten the list and assign it to the relevant column flat_list = [item for sublist in parsed_stats[num:][::19] for item in sublist] qb[col] = flat_list qb.iloc[0] player_id 1 name Matt Ryan team Atl vs KC ffpts 37.00 pass_att 31 pass_comp 23 pass_yds 299 pass_tds 3 int 0 pass2 0 rush_att 3 rush_yds 25 rush_tds 1 rush_2 0 rec 0 rec_yds 0 rec_tds 0 rec_2 0 fum 0 vs_2 0 Name: 0, dtype: object Please double check that everything is in the right order and that the numbers make sense, I am not familiar enough with American football to assess it.
score: 0
type: AcceptedAnswer

scrapy
tags question: http://stackoverflow.com/q/46865404
tags question: http://stackoverflow.com/q/46758830
tags question: http://stackoverflow.com/q/46865284
tags question: http://stackoverflow.com/q/46892962
tags question: http://stackoverflow.com/q/46788478
tags question: http://stackoverflow.com/q/46762778
tags question: http://stackoverflow.com/q/46767862
tags question: http://stackoverflow.com/q/46790044
tags question: http://stackoverflow.com/q/46803034
tags question: http://stackoverflow.com/q/46804324
tags question: http://stackoverflow.com/q/46760671
tags question: http://stackoverflow.com/q/46841939
tags question: http://stackoverflow.com/q/46765881
tags question: http://stackoverflow.com/q/46786173
tags question: http://stackoverflow.com/q/46876110
tags question: http://stackoverflow.com/q/46888809
tags question: http://stackoverflow.com/q/46848323
tags question: http://stackoverflow.com/q/46871133
tags question: http://stackoverflow.com/q/46828207
tags question: http://stackoverflow.com/q/46806050
tags question: http://stackoverflow.com/q/46858394
tags question: http://stackoverflow.com/q/46836064
tags question: http://stackoverflow.com/q/46888107
tags question: http://stackoverflow.com/q/46782193
tags question: http://stackoverflow.com/q/46845823
tags question: http://stackoverflow.com/q/46895000
tags question: http://stackoverflow.com/q/46749659
tag name: scrapy
tags question: http://stackoverflow.com/q/46821341
tags question: http://stackoverflow.com/q/46887738
tags question: http://stackoverflow.com/q/46843125
tags question: http://stackoverflow.com/q/46767498
tags question: http://stackoverflow.com/q/46797362
tags question: http://stackoverflow.com/q/46768361
tags question: http://stackoverflow.com/q/46839861
tags question: http://stackoverflow.com/q/46900437
tags question: http://stackoverflow.com/q/46888276
type: Tag
tags question: http://stackoverflow.com/q/46815950
tags question: http://stackoverflow.com/q/46852669

http://stackoverflow.com/q/46800380
has answer: http://stackoverflow.com/a/46804366
downvote count: 0
has comment: http://stackoverflow.com/comment/80547728
favorite count: 0
has comment: http://stackoverflow.com/comment/80547762
accepted answer: http://stackoverflow.com/a/46804366
upvote count: 2
tagged with: python
has body: I wrote a script to remove the seven least significant bits and only keep the MBS for each pixel of a gray-scale 8-bit image. To do this, I mask each pixel with 0b10000000, but am not getting the expected output. import cv2 import numpy as np imageSource = 'input.jpg' original_img = cv2.imread(imageSource,cv2.COLOR_BGR2GRAY) cv2.imshow( "original", original_img ) result = original_img &amp; 0b10000000 cv2.imshow( "out", result ) cv2.imwrite('out.jpg',result) cv2.waitKey(0) cv2.destroyAllWindows() Original image: Output from my code: Desired result:
tagged with: opencv
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80547761
tagged with: image-processing
has comment: http://stackoverflow.com/comment/80556940
possible better answer: http://stackoverflow.com/a/46801111
type: Question
has title: How to remove seven low bits of a grayscale image using OpenCV
answer count: 2
has answer: http://stackoverflow.com/a/46801111

http://stackoverflow.com/comment/80724225
type: Comment
type: QuestionComment
has text: you want `str.format`: `"{1} {0}".format(a,b)` right?
comment on: http://stackoverflow.com/q/46888583
score: 1

http://stackoverflow.com/a/46795277
type: Answer
upvote count: 1
has body: Can you try the following : xpath as : "//span[@class='ui-tree-toggler ui-icon ui-icon-triangle-1-e']" OR css as : "span.ui-tree-toggler.ui-icon.ui-icon-triangle-1-e"
score: 1
answers question: http://stackoverflow.com/q/46795098
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46795098

http://stackoverflow.com/a/47263575
has comment: http://stackoverflow.com/comment/81535551
has comment: http://stackoverflow.com/comment/81534361
accepted answer of: http://stackoverflow.com/q/46852426
answers question: http://stackoverflow.com/q/46852426
type: Answer
has comment: http://stackoverflow.com/comment/81568124
has body: The prompt width is set in notebook/static/notebook/less/cell.less#L80, so you could do something like: /* Narrow the prompts */ .prompt { min-width: 10ex; } /* Hide prompts altogether for non-conda cells */ .cell:not(.code_cell) .prompt { display: none; }
has comment: http://stackoverflow.com/comment/81567807
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81536560

http://stackoverflow.com/a/46838315
downvote count: 0
has comment: http://stackoverflow.com/comment/80629128
has comment: http://stackoverflow.com/comment/80652716
type: Answer
has body: What you're probably looking for is this from multiprocessing import Pool def process_results(single_dict): first_result, second_result, count = [], [], 0 first_result.append(single_dict) if 'pi' in single_dict: second_result.append(single_dict) count += 1 return first_result, second_result if __name__ == '__main__': lst_dict = [{'a':1, 'b':2, 'c':3},{'c':4, 'pi':3.14}, {'pi':'3.14', 'not pi':8.3143}, {'sin(pi)': 0, 'cos(pi)': 1}]; pool = Pool() print pool.map(process_results, lst_dict) pool.map executes process_results for each element in the iterable lst_dict. Since lst_dict is a list of dictionaries that means that process_results will be called for every dictionary in lst_dict using it as an argument. process_results will be processing every dictionary rather than the whole list. process_results in this program is changed accordingly: for a given dictionary in the list, it appends the dictionary to the first_result list and then appends the dictionary to the second_result list if the 'pi' key exist. Result is a list with two sublists - one containing the dictionary and one containing either the copy of the first or an empty list if no 'pi' was found. All this can be modified if you for instance need the first_result and second_result lists to be shared among processes. For a better picture of how pool.map() works look at the first example in the documentation. To retrieve the results in their original/target form of two lists you can collect the data into a list and then process it: results = [] results = pool.map(process_results, lst_dict) first_result = [i[0][0] for i in results] second_result = [i[0][0] for i in results if i[1]] results is a list of tuples. The tuples represent the result of processing of each dictionary - first element is the whole dictionary and the second is either an empty list, or the whole dictionary if 'pi' key was found. Remaining two lines retrieve that data into first_result and second_result lists.
has comment: http://stackoverflow.com/comment/80624952
upvote count: 1
has comment: http://stackoverflow.com/comment/80624859
has comment: http://stackoverflow.com/comment/80624834
answers question: http://stackoverflow.com/q/46837823
score: 1
has comment: http://stackoverflow.com/comment/80627304
accepted answer of: http://stackoverflow.com/q/46837823
has comment: http://stackoverflow.com/comment/80652478
has comment: http://stackoverflow.com/comment/80625055
type: AcceptedAnswer

http://stackoverflow.com/a/46895361
has comment: http://stackoverflow.com/comment/80739197
downvote count: 0
has comment: http://stackoverflow.com/comment/80738389
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80739240
has comment: http://stackoverflow.com/comment/80738129
has comment: http://stackoverflow.com/comment/80738044
type: Answer
has comment: http://stackoverflow.com/comment/80739001
score: 3
accepted answer of: http://stackoverflow.com/q/46895157
upvote count: 3
has comment: http://stackoverflow.com/comment/80738057
has comment: http://stackoverflow.com/comment/80739314
answers question: http://stackoverflow.com/q/46895157
has comment: http://stackoverflow.com/comment/80738893
has comment: http://stackoverflow.com/comment/80738465
has comment: http://stackoverflow.com/comment/80738193
has body: First of all, I suggest using a different data structure than a dict here for the following reasons: The good thing about dicts is the quick access to elements when given a key. However, you don't know the key, you only know something that is close to the key - therefore you need to iterate over the dict anyways. The problem with a dict is that it requires a certain voltage to only be associated with exactly one chemical reaction. Even if that is true for the subset of chemical reactions you use, I would still suggest you try to avoid this problem from the beginning. Instead, why not use a list of tuples (here, we convert the voltage-strings from your input files into floats) res = [(float(v), k) for k, v in answer.items()] Now you have to define what it means for two voltages to be close. For example def approximatelyEqual(v1, v2): epsilon = 0.001 # Define this however you want return abs(v1 - v2) &lt; epsilon Once you have this the rest is simple similarChemicalReactions = [(voltage, reaction) for (voltage, reaction) in res if approximatelyEqual(voltage, userinput)] gives you a list of approximately close chemical reactions. If you want the closest one, do: similarChemicalReaction = min(((voltage, reaction) for (voltage, reaction) in res), key=lambda v1: approximatelyEqual(v1, userinput))

http://stackoverflow.com/q/46836857
has comment: http://stackoverflow.com/comment/80654779
linked to: http://stackoverflow.com/q/42022950
has comment: http://stackoverflow.com/comment/92763127
score: 10
has answer: http://stackoverflow.com/a/46886311
has comment: http://stackoverflow.com/comment/100766222
has comment: http://stackoverflow.com/comment/92763730
tagged with: random
has answer: http://stackoverflow.com/a/55497594
has comment: http://stackoverflow.com/comment/92762658
downvote count: 0
linked to: http://stackoverflow.com/q/32419510
tagged with: keras
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/56089322
has body: I have the problem, that I am not able to reproduce my results with Keras and ThensorFlow. It seems like recently there has been a workaround published on the Keras documentation site for this issue but somehow it doesn't work for me. What I am doing wrong? I'm using a Jupyter Notebook on a MBP Retina (without Nvidia GPU). # ** Workaround from Keras Documentation ** import numpy as np import tensorflow as tf import random as rn # The below is necessary in Python 3.2.3 onwards to # have reproducible behavior for certain hash-based operations. # See these references for further details: # https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED # https://github.com/fchollet/keras/issues/2280#issuecomment-306959926 import os os.environ['PYTHONHASHSEED'] = '0' # The below is necessary for starting Numpy generated random numbers # in a well-defined initial state. np.random.seed(42) # The below is necessary for starting core Python generated random numbers # in a well-defined state. rn.seed(12345) # Force TensorFlow to use single thread. # Multiple threads are a potential source of # non-reproducible results. # For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) from keras import backend as K # The below tf.set_random_seed() will make random number generation # in the TensorFlow backend have a well-defined initial state. # For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed tf.set_random_seed(1234) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) # ** Workaround end ** # ** Start of my code ** # LSTM and CNN for sequence classification in the IMDB dataset from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers.embeddings import Embedding …
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60865583
answer count: 4
has comment: http://stackoverflow.com/comment/121469534
linked to: http://stackoverflow.com/q/55200768
upvote count: 10
tagged with: tensorflow
type: Question
has title: Results not reproducible with Keras and TensorFlow in Python

http://stackoverflow.com/q/46901178
type: UnansweredQuestion
has title: Add own realtime custom parser to Python to generate and compile AST
tagged with: python
score: 2
answer count: 0
tagged with: syntax
type: Question
tagged with: abstract-syntax-tree
linked to: http://stackoverflow.com/q/768634
downvote count: 0
has body: My task is to add switch statement and remove mandatory colons from functions, classes, loops in Python. Maybe to add some other nice features from Coffeescript. The .py files with custom syntax must be imported with python interpreter, than parsed with a custom parser (just like Coffeescript compiler does). (I already had a little experience in writing Python-like "for" syntax to already created custom parser, corrected several bugs. But it takes a long time to read all code and get it. So I decided to ask advice first.) I searched a long time through internet, found several helpful answers, but still don't know how to implement it better. Some from what I found: Parse a .py file, read the AST, modify it, then write back the modified source code Python's tokenize module Python's ast module Python's c-like preprocessor with import hook What I think to do: Rewrite Coffeescript parser or Python parser into pure Python Make import hook to parse files to AST by my own parser. Continue import (compile AST and import it to module) (like Coffeescript does it) So I have such questions: - Is there a Python parser written in Python (not to rewrite all Coffeescript parser) ? - Maybe is there any way to make ast.AST class frow own parser not rewriting ast library from C into Python ? - How can I do it better and easier ? (except modifying Python's sources, all must be done in runtime and be totally compatible with all other Python interpreters) - Maybe there are already some libraries, that help modifying Python's syntax ? Thank you very much. Best regards, Serj.
has comment: http://stackoverflow.com/comment/80749364
favorite count: 0
tagged with: parsing
upvote count: 2

http://stackoverflow.com/a/46884966
downvote count: 0
has body: Most, but not all settings you can do, have an equivalent matplotlib rc paramter. I think here you are lucky, the following would the rc Parameters for the "economist" style in question. To put them in a file, see the matplotlib customize guide. import numpy as np import matplotlib.pyplot as plt params = {"figure.facecolor": "#cad9e1", "axes.facecolor": "#cad9e1", "axes.grid" : True, "axes.grid.axis" : "y", "grid.color" : "#ffffff", "grid.linewidth": 2, "axes.spines.left" : False, "axes.spines.right" : False, "axes.spines.top" : False, "ytick.major.size": 0, "ytick.minor.size": 0, "xtick.direction" : "in", "xtick.major.size" : 7, "xtick.color" : "#191919", "axes.edgecolor" :"#191919", "axes.prop_cycle" : plt.cycler('color', ['#006767', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])} plt.rcParams.update(params) x = np.random.randn(1000) y = np.sin(x) fig, ax = plt.subplots(figsize=(12, 10)) ax.scatter(x, y) plt.show()
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46879764
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46879764
type: Answer
score: 2

http://stackoverflow.com/comment/80490818
has text: I'm getting a different error now, when I try to import boto3, I get this error: **ImportError: No module named 'httplib'**, which shoudn't happen when installing boto3 from pip3. I'm pretty confused now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46772012
score: 0

http://stackoverflow.com/comment/80659688
score: 0
type: Comment
type: QuestionComment
has text: @wen yes 01-09-2017 would be included yes
comment on: http://stackoverflow.com/q/46854545

http://stackoverflow.com/comment/80668806
comment on: http://stackoverflow.com/a/46860583
score: 0
type: Comment
has text: My bad!! I missed that line. Will update the answer soon.
type: AnswerComment

http://stackoverflow.com/comment/80738193
has text: @ivdito is right, I changed my answer to adress that. You need to change the type of userinput as well, i.e. userinput = `float(input("Voltage? "))`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46895361
score: 0

http://stackoverflow.com/comment/80516465
type: QuestionComment
score: 1
has text: Are you basing the assertion that `__eq__` is not defined solely on those lines? Because I see [other code that handles operator overrides in a generic manner](https://github.com/tensorflow/tensorflow/blob/27767d8e9c1325979cf32ff5b81c10df9006fd57/tensorflow/python/ops/math_ops.py#L875-L935) for example.
type: Comment
comment on: http://stackoverflow.com/q/46785041

http://stackoverflow.com/comment/80445092
has text: Oops! That was just a typo ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/46749258
score: 0
type: Comment

http://stackoverflow.com/comment/80615419
score: 3
comment on: http://stackoverflow.com/a/46832956
type: AnswerComment
type: Comment
has text: What I can say definitely is that simple NN without built-in normalizing mechanism (batch norm, weight norm, SELU, etc.) is *very* sensitive to hyperparameters. It's so often that one or two changes in init stdev, learning rate or some other param makes NN learn much better. This question is one of those cases. So I wouldn't give up on NN so quickly

http://stackoverflow.com/q/46756555
answer count: 2
duplicate of: http://stackoverflow.com/q/10664856
upvote count: 0
has answer: http://stackoverflow.com/a/46756580
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I made a dictionary using python dictionary = {'key':'a', 'key':'b'}) print(dictionary) print (dictionary.get("key")) When run this code then shows the last value of dictionary, Is there any way to access the first value of dictionary if keys of both elements of dictionary are same.
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80458416
has answer: http://stackoverflow.com/a/46756594
has title: access value of dictionary if keys are same of each value in python?
linked to: http://stackoverflow.com/q/10664856
score: -1

http://stackoverflow.com/a/46784762
type: Answer
answers question: http://stackoverflow.com/q/46771437
score: 0
has body: Iterate through the output['sentences'] list: text=‘This is it, kid. This is our chance. When you got a chance, you better take it.’ output = nlp.annotate(text, properties={‘annotators’: ‘tokenize,ssplit,lemma,pos,depparse,parse’, ‘outputFormat’: ‘json’}) for sent in output[‘sentences’]: print(sent[‘parse’]) Alternatively, you can use the CoreNLP API in NLTK, see https://github.com/nltk/nltk/blob/develop/nltk/parse/corenlp.py#L343

http://stackoverflow.com/comment/80495611
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46774656
type: Comment
has text: *"the code should move his details"* - Why? What problem does it solve to move line around in the CSV?

http://stackoverflow.com/a/46843533
has comment: http://stackoverflow.com/comment/80634829
type: Answer
has comment: http://stackoverflow.com/comment/80635674
has comment: http://stackoverflow.com/comment/80636624
score: 1
has comment: http://stackoverflow.com/comment/80636362
answers question: http://stackoverflow.com/q/46843196
has comment: http://stackoverflow.com/comment/80636384
upvote count: 1
has comment: http://stackoverflow.com/comment/80635717
has comment: http://stackoverflow.com/comment/80635762
downvote count: 0
has body: The change will be done at this line (I've already change it): filtered_text = re.findall(r"^[\w()-.$]*$", result) Note: I removed \d because \w represents all alphanumeric characters (letters and numbers). As you want to include some special characters, reason why I put it ()-.$ there.

http://stackoverflow.com/a/46795813
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46795665
has comment: http://stackoverflow.com/comment/80538299
type: Answer
answers question: http://stackoverflow.com/q/46795665
score: 2
downvote count: 0
has body: You can use numpy.random.choice. This randomly samples from the original list. If you feed it the original list, you don't need to use weights: import numpy as np Dalc = [1,2,1,1,1,1,1,1,1,1,1,1,5,1,1,3,1,2,1,1,1,1,2] new_choices = np.random.choice(Dalc, size=10000) Dalc += list(new_choices)

http://stackoverflow.com/q/46779060
tagged with: python
has comment: http://stackoverflow.com/comment/80504074
tagged with: pyqt5
linked to: http://stackoverflow.com/q/46633698
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/80504551
has comment: http://stackoverflow.com/comment/80504980
has title: set QPainter background
has body: Hi every one I am working on using QPainter and mouse events and I want to set the background of the QPainter to black I used this code but doesn't work Thanks in advance class Drawer(QWidget): newPoint = pyqtSignal(QPoint) def __init__(self, parent=None): QWidget.__init__(self, parent) self.path = QPainterPath() def paintEvent(self, event): painter = QPainter(self) painter.setPen(QColor(168, 34, 3)) painter.setFont(QFont('Decorative', 10)) bbrush = QtGui.QBrush( QtGui.QColor(0,0,0),QtCore.Qt.SolidPattern) painter.setBackground(painter,bbrush) painter.drawPath(self.path) def mousePressEvent(self, event): self.path.moveTo(event.pos()) self.update() def mouseMoveEvent(self, event): self.path.lineTo(event.pos()) self.newPoint.emit(event.pos()) self.update() def sizeHint(self): return QSize(400, 400) class MyWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setLayout(QVBoxLayout()) label = QLabel(self) drawer = Drawer(self) drawer.newPoint.connect(lambda p: label.setText( 'Coordinates: ( %d : %d )' % (p.x(), p.y()))) self.layout().addWidget(label) self.layout().addWidget(drawer)
score: 0
has comment: http://stackoverflow.com/comment/80510563
has comment: http://stackoverflow.com/comment/80504457
has answer: http://stackoverflow.com/a/46858261
type: UnansweredQuestion

http://stackoverflow.com/q/46853086
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has title: My program is taking very long to print out results over 25, is there a way to make this more efficient when I run?
has answer: http://stackoverflow.com/a/46853521
tagged with: math
tagged with: python-3.6
type: Question
has answer: http://stackoverflow.com/a/46853872
linked to: http://stackoverflow.com/q/20193555
answer count: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/20193555
favorite count: 0
has body: These are the lines I'm using, it produces a list of the possible combinations of the sum to an integer typed in and then states the amount of combinations. import itertools val = int(input()) r = range(val)[1:] res = [] for i in range(len(r)+1): res += [list(x) for x in itertools.combinations(r, i) if sum(list(x)) == val] print("Solution : %s " % res) print("Combinations : %s" % len(res))

http://stackoverflow.com/comment/80526602
type: QuestionComment
has text: @Ev.Kounis Then you'll have 2 backslashes at the end of your string.
score: 2
comment on: http://stackoverflow.com/q/46790104
type: Comment

http://stackoverflow.com/q/46893226
type: AnsweredQuestion
has body: I am studying the different types of testing for a Django application. I know how to do functional and unit testing in Django and how to apply different methodologies, but now I am facing a new challenge, I need to know how to do: Performance testing Load testing Stress testing I know the difference between them but I dont know which is the best methodology to follow,which are the best packages for do it or simply where I can get some documentation about it. So my question is, how can I start to do these types of tests in a Django app or where can I get some good documentation about it? Thanks
upvote count: 21
tagged with: django
type: Question
tagged with: testing
has answer: http://stackoverflow.com/a/46927322
score: 21
has comment: http://stackoverflow.com/comment/80748129
has title: Performance, load and stress testing in Django
tagged with: performance-testing
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46927322
tagged with: python

http://stackoverflow.com/comment/80485603
score: 4
comment on: http://stackoverflow.com/q/46770171
has text: Fantastic. Can you please show your code for this and indicate what difficulties you are facing in your own implementation?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47378359
answers question: http://stackoverflow.com/q/46904931
score: 0
has body: This is what worked for me for a somewhat similar scenario: I copied .bash_profile into .bashrc In Pycharm's Terminal settings, make sure that the 'Shell integration' option is not checked I left 'Shell path' to only have the path to bash (no further --rcfile arguments required) It may help to add an echo with a custom message in your .bashrc file to confirm if indeed this file is being read
type: Answer

http://stackoverflow.com/q/46826617
tagged with: python
tagged with: dummy-variable
upvote count: 0
tagged with: loops
type: Question
has title: Create Dummy Variables with Loop in Python
has answer: http://stackoverflow.com/a/46826725
has body: I'm trying to create a bunch of new Binary variables just for some columns that contain a certain word (and I want to name these new binary variables BINARY_ +column name), I'm trying to do it in this was way but it doesn't work: # create empty list List_of_dummy_names = [] # word string = "WORD" for col in list(df.columns.values): if string in df.columns.values[col]: List_of_dummy_names.append('BINARY_'+col)
has comment: http://stackoverflow.com/comment/80600769
has answer: http://stackoverflow.com/a/46826767
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/80602495
tagged with: pandas
favorite count: 0
type: UnansweredQuestion
score: -3

http://stackoverflow.com/a/46869579
has comment: http://stackoverflow.com/comment/80686579
has comment: http://stackoverflow.com/comment/80686751
score: -1
has comment: http://stackoverflow.com/comment/80686612
upvote count: 0
has comment: http://stackoverflow.com/comment/80686663
has comment: http://stackoverflow.com/comment/80686666
has comment: http://stackoverflow.com/comment/80686684
type: Answer
has comment: http://stackoverflow.com/comment/80686712
has body: instead of iterating the (unsorted) dict of people: for id_num, person in people.items(): You can iterate the keys ordered by the number of steps: for id_num in sorted(people, key=lambda x: x.total_steps): p = person_dict[id_num] #...
has comment: http://stackoverflow.com/comment/80686400
downvote count: 1
answers question: http://stackoverflow.com/q/46869502
has comment: http://stackoverflow.com/comment/80686641
has comment: http://stackoverflow.com/comment/80686645

http://stackoverflow.com/comment/80600106
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46804012
has text: @dvectR Oh. Perhaps the `\x00,i` is also part of the header. So you'd need to slice that off as well, eg `int.from_bytes(bstring[6:], 'little')`. If that doesn't work, add a few more examples of integers and their encodings to your question & I'll try to figure out the real encoding format. Eg, 1, 2, 3, 10, 100, 1000. And some negative numbers too, if they are permitted.
type: AnswerComment

http://stackoverflow.com/q/46875525
has title: Python : Print only the results that are in a specific list
has answer: http://stackoverflow.com/a/46876114
answer count: 1
downvote count: 0
score: 1
tagged with: permutation
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80698638
has body: Full code: cp1=[1,2,3,4,5,6] cp1=[1,2,3,4,5,6] cn1=[7,8,9,10,11,12] cn2=[13,14,15,16,17,18] cn3=[19,20,21,22,23,24] cn4=[25,26,27,28,29,30] import itertools sets = [cp1,cn1]; ks = [3,2] for i in itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)]): a = i[0]+i[1] for i in itertools.permutations(a) : i_sum1 = i[0] + i[1] i_sum2 = i_sum1 + i[2] i_sum3 = i_sum2 + i[3] i_sum4 = i_sum3 + i[4] i2_sum1 = i[1] + i[2] i2_sum2 = i2_sum1 + i[3] i2_sum3 = i2_sum2 + i[4] i3_sum1 = i[2] + i[3] i3_sum2 = i3_sum1 + i[4] i4_sum1 = i[3] + i[4] allsum =(i_sum1, i_sum2,i_sum3,i_sum4, i2_sum1, i2_sum2, i2_sum3, i3_sum1,i3_sum2,i4_sum1) if (i_sum1 or i_sum2 or i_sum3 or i_sum4 or i2_sum1 or i2_sum2 or i2_sum3 or i3_sum1 or i3_sum2 or i4_sum1) not in (cn1 or cn2 or cn3) : for b in itertools.product(cn4, repeat=2): if (b[0] and b[1]) in allsum : print (i,allsum) Explanation: random lists cp1=[1,2,3,4,5,6] cn1=[7,8,9,10,11,12] cn2=[13,14,15,16,17,18] cn3=[19,20,21,22,23,24] cn4=[25,26,27,28,29,30] combination between 2 lists, using 3 elements of one and 2 of the other one for each result import itertools sets = [cp1,cn1]; ks = [3,2] for i in itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)]): merging the results a = i[0]+i[1] permutation of the results for i in itertools.permutations(a) : specific sum of the permutations i_sum1 = i[0] + i[1] i_sum2 = i_sum1 + i[2] i_sum3 = i_sum2 + i[3] i_sum4 = i_sum3 + i[4] i2_sum1 = i[1] + i[2] i2_sum2 = i2_sum1 + i[3] i2_sum3 = i2_sum2 + i[4] i3_sum1 = i[2] + i[3] i3_sum2 = i3_sum1 + i[4] i4_sum1 = i[3] + i[4] allsum =(i_sum1, i_sum2,i_sum3,i_sum4, i2_sum1, i2_sum2, i2_sum3, i3_sum1,i3_sum2,i4_sum1) printing only specific results: avoid the the result if any of it sums are in any of the lists, cn1, cn2, or cn3: (here is where I'm having problems) if (i_sum1 or i_sum2 or i_sum3 or i_sum4 or i2_sum1 or i2_sum2 or i2_sum3 or i3_sum1 or i3_sum2 or i4_sum1) not in (cn1 or cn2 or cn3) : Print only the r…
upvote count: 1
type: Question
tagged with: combinations
tagged with: python-itertools
tagged with: if-statement
has comment: http://stackoverflow.com/comment/80698331

http://stackoverflow.com/q/46796885
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80724344
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/96282480
tagged with: python
has title: BigQuery: loading excel file
downvote count: 0
score: 1
tagged with: excel
type: Question
has body: Is there any way we can load direct excel file into BigQuery, instead of converting to CSV. I get the files every days in excel format and need to load into BigQuery. Right now converting into CSV manually and loading into BigQuery. Planning to schedule the job. If not possible to load the excel files directly into BigQuery then I need to write a process(Python) to convert into CSV before loading into BigQuery. Please let me know if any better options are there. Thanks,
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/46799866

http://stackoverflow.com/q/46893982
type: Question
accepted answer: http://stackoverflow.com/a/46894383
type: AnsweredQuestion
tagged with: python
has body: Yeah I know, it's not possible. Or maybe I didn't see. But, I'm gonna explain why I need this. Let's do some dummy classes: class A(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() lvl_struct = GenericForeignKey('content_type', 'object_id') Let's say A can be attached to a struct (logical struct, like department in jobs). An A instance can be attached to only one struct, but there're 4 disctinct type of struct, and that's where I discovered generic foreign key (instead of a polymorphism on A). But now, my problem is, in my form, I want to attach the actual struct when I create a A instance : class CreateAForm(forms.ModelForm) lvl_struct = forms.ModelChoiceField( queryset=None, #here is my problem required=True ) So here I would like to have a unique select with all possibilities (all instances of first struct type, all instances of second struct type and so on). So is there any way to do this, or will I have to do like four select with some js to check at least one and only one select has a value? Or of course a third solution which I didn't see. Tell me. Thank you in advance for your time.
score: 0
tagged with: django
answer count: 1
tagged with: forms
has title: Django : several models returns in queryset
has answer: http://stackoverflow.com/a/46894383

http://stackoverflow.com/q/46777506
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80500718
has comment: http://stackoverflow.com/comment/80500780
tagged with: python
tagged with: utf-8
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/46777638
type: Question
has comment: http://stackoverflow.com/comment/80500790
has body: I'm trying to write a Python script that uses UTF-8 information, but I'm getting SyntaxError: Non-ASCII character messages. It looks like I can solve this by adding the following to the top of my script: #!/usr/bin/python # coding: utf8 But I get ascii when I run this script: #!/usr/bin/python # coding: utf8 import sys print sys.getdefaultencoding() Also, I've tried with the same results: #!/usr/bin/python # -*- coding: utf-8 -*- Why isn't my script using UTF-8?
linked to: http://stackoverflow.com/q/38374489
has title: Python Not Accepting UTF-8 Coding
accepted answer: http://stackoverflow.com/a/46777638

http://stackoverflow.com/q/46751153
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80448548
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/80448313
has comment: http://stackoverflow.com/comment/80448317
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/80448332
has answer: http://stackoverflow.com/a/46754422
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80448365
has answer: http://stackoverflow.com/a/46752921
has body: I want to select the points that fall within two arbitrary curves, each defined by an array of points. Below is an example. In reality, the curves I have are not based on a functional form, they are arrays. How can I select only the points that fall within the red and blue curve, and say, color them a different color? import numpy as np import matplotlib.pyplot as plt # generate arrays from gaussian x = np.linspace(0.5, 3.5, 120) y = np.exp(-np.power(x - 2, 2.) / (2 * np.power(.8, 2.))) yy = .5*np.exp(-np.power(x - 2, 2.) / (2 * np.power(.4, 2.))) # generate random data points data_x = 4*np.random.rand(1000) data_y = np.random.rand(1000) fig = plt.figure() ax = plt.axes() ax.scatter(data_x, data_y, c='k', s=.1) ax.scatter(x,y, s=3) ax.scatter(x,yy, c='r', s=3) plt.show()
has comment: http://stackoverflow.com/comment/80448429
has comment: http://stackoverflow.com/comment/80448398
has comment: http://stackoverflow.com/comment/80448209
tagged with: python-2.7
upvote count: 3
answer count: 2
downvote count: 1
favorite count: 0
tagged with: interpolation
has comment: http://stackoverflow.com/comment/80448446
has title: Python: select points that fall within two arbitrary curves

http://stackoverflow.com/q/46850398
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80649450
answer count: 0
type: UnansweredQuestion
type: Question
duplicate of: http://stackoverflow.com/q/6523886
has title: Parsing a single line from XML with Python
duplicate of: http://stackoverflow.com/q/40796231
has body: Using Python 3.x I need to read / modify the text highlighted in the picture below: The code I have developped crawls thru the XML file and it displays eg: the 7F7F7F and the hu-HU correctly, but not the highlighted text. (which makes sense to me, because I am certainly missing something) How can I read / modify that part of the XML? Is there any trivial way to do it, or do I need to use my recursive algorithm? (I am completely new to python as well as to XML) import xml.etree.ElementTree as ET tree = ET.parse('c:\\temp\\document.xml') root = tree.getroot() def myRecursion(param1): for child in param1: myString = str(child.attrib) print(child.items()) myRecursion(child) myRecursion(root)`
has comment: http://stackoverflow.com/comment/80650954
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/6523886
has comment: http://stackoverflow.com/comment/80649727
tagged with: ms-word
has comment: http://stackoverflow.com/comment/80649259
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/comment/80608360
type: QuestionComment
has text: this is how it looks: with open('words.txt', 'r') as f: context = f.read() count = {} words = context.split()
score: 0
comment on: http://stackoverflow.com/q/46830435
type: Comment

http://stackoverflow.com/comment/80746870
comment on: http://stackoverflow.com/q/46899816
has text: @souldeux I fixed the parentheses but the issue persists. Also updated the question with the contents of webapp.urls
score: 0
type: Comment
type: QuestionComment

import
type: Tag
tag name: import
tags question: http://stackoverflow.com/q/46792595
tags question: http://stackoverflow.com/q/46828371
tags question: http://stackoverflow.com/q/46819728
tags question: http://stackoverflow.com/q/46877236
tags question: http://stackoverflow.com/q/46786847
tags question: http://stackoverflow.com/q/46751905
tags question: http://stackoverflow.com/q/46841214
tags question: http://stackoverflow.com/q/46859615
tags question: http://stackoverflow.com/q/46893461
tags question: http://stackoverflow.com/q/46831733
tags question: http://stackoverflow.com/q/46899376
tags question: http://stackoverflow.com/q/46845247

http://stackoverflow.com/comment/80598745
type: Comment
comment on: http://stackoverflow.com/a/46812603
type: AnswerComment
has text: Ok your solution is simple and quick, but what if instead of 0 and 1 I had "A and B"? I know this is a little different from my first question, but I am trying to find a way that could work in most situations.
score: 0

http://stackoverflow.com/a/46786404
type: Answer
upvote count: 13
has body: You need str.cat with lower first for concanecate all values to one string, then need word_tokenize and last use your solution: top_N = 4 #if not necessary all lower a = data['Firm_Name'].str.lower().str.cat(sep=' ') words = nltk.tokenize.word_tokenize(a) word_dist = nltk.FreqDist(words) print (word_dist) &lt;FreqDist with 17 samples and 20 outcomes&gt; rslt = pd.DataFrame(word_dist.most_common(top_N), columns=['Word', 'Frequency']) print(rslt) Word Frequency 0 society 3 1 ltd 2 2 the 1 3 co 1 Also is possible remove lower if necessary: top_N = 4 a = data['Firm_Name'].str.cat(sep=' ') words = nltk.tokenize.word_tokenize(a) word_dist = nltk.FreqDist(words) rslt = pd.DataFrame(word_dist.most_common(top_N), columns=['Word', 'Frequency']) print(rslt) Word Frequency 0 Society 3 1 Ltd 2 2 MMV 1 3 Kensington 1
score: 13
has comment: http://stackoverflow.com/comment/81622667
downvote count: 0
answers question: http://stackoverflow.com/q/46786211
has comment: http://stackoverflow.com/comment/81829306

amazon-ec2
tags question: http://stackoverflow.com/q/46791798
type: Tag
tags question: http://stackoverflow.com/q/46802777
tags question: http://stackoverflow.com/q/46752867
tags question: http://stackoverflow.com/q/46801711
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/46801899

http://stackoverflow.com/comment/80712081
score: 0
type: QuestionComment
type: Comment
has text: x= int(input("Please enter the value of x: ")) y= int(input("Please enter the value of y: ")) operator = input("Please enter an operator you would like to complete the equation:") if operator > '*': print("The result of the equation is: ", x*y) elif operator > '+': print("The result of the equation is: ", x+y) elif operator > '-': print("The result of the equation is: ", x-y) elif operator > '/': print("The result of the equation is: ", x/y)
comment on: http://stackoverflow.com/q/46882406

http://stackoverflow.com/q/46901324
type: UnansweredQuestion
tagged with: python
tagged with: text
has body: Is there any approach to have certain words with certain fond in "canvas items"? Like tag_configure and tag_add for "text widget"? x = canvas.create_text(10, 10, text = "$-3", font = "calibri 30") I need $ a font, and -3 a font. I have tried to create Text() in master, but the text is blocked by the canvas items.
tagged with: widget
tagged with: fonts
score: 0
has title: different fonts in tkinter canvas text items
type: Question
has answer: http://stackoverflow.com/a/46905391
answer count: 1
has comment: http://stackoverflow.com/comment/80757258
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80756763
has comment: http://stackoverflow.com/comment/80757131

wsgi
type: Tag
tags question: http://stackoverflow.com/q/46817901
tags question: http://stackoverflow.com/q/46761979
tags question: http://stackoverflow.com/q/46832162
tags question: http://stackoverflow.com/q/46840875
tag name: wsgi

http://stackoverflow.com/a/46800117
accepted answer of: http://stackoverflow.com/q/46796618
answers question: http://stackoverflow.com/q/46796618
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has body: You can try with this, I used comvibe_first to merge two dataframe. start_date = datetime.datetime.today() end_date = datetime.datetime(2017, 10, 19) ​ dd = pd.date_range( start_date, end_date, freq="3min" ​ ) dd = dd.map(lambda item: calendar.timegm(item.timetuple())) columns = ['some', 'column', 'headers'] df = pd.DataFrame(columns=columns, index=dd) myarray = np.random.random((len(dd),3)) for val, item in enumerate(myarray): df.ix[df.index.values[val]] = item index_new = df.sample(frac=0.8, random_state=200) df = df.drop(index_new.index) df_ok = pd.DataFrame(columns=columns, index=dd) df_ok = df_ok.combine_first(df)
upvote count: 1

http://stackoverflow.com/q/46756019
has body: I load a DataFrame from a database and have a column that is a dict, like so: id some_value ... coordinates 15 34.7 {'type': 'Point', 'coordinates': [-3.2, 37.0]} However, when I save my DataFrame to disk using pd.to_csv() and then re-read it, the column containing the coordinates is not a dict, but a string: id some_value ... coordinates 15 34.7 "{'type': 'Point', 'coordinates': [-3.2, 37.0]}" How can I tell Pandas to read this column as a dict, or how can I convert this column back into a dict?
accepted answer: http://stackoverflow.com/a/46756069
favorite count: 0
possible better answer: http://stackoverflow.com/a/54724063
upvote count: 5
has comment: http://stackoverflow.com/comment/80457442
has comment: http://stackoverflow.com/comment/80457374
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/46756069
has answer: http://stackoverflow.com/a/54724063
type: AnsweredQuestion
type: Question
tagged with: export-to-csv
score: 5
answer count: 2
tagged with: eval
tagged with: pandas
has title: Pandas df.to_csv() saves dict values as string. How can I get the dicts back when calling pd.read_csv()?
downvote count: 0

http://stackoverflow.com/q/46863568
answer count: 1
has comment: http://stackoverflow.com/comment/80674877
has body: Are these two functions that create x equivalent? I don't understand why itemgetter seems to return the correct variable when using 0 as an input in this case. Is itemgetter correctly sorting by dictionary key?. They both print the same from operator import itemgetter lvls = {1: ["t1","t2"], 2: ["t3","t4"], 3: ["tdfgdf99","x99"]} x = sorted((v for k,v in lvls.items()),key=itemgetter(0),reverse=True) print (x) x = sorted((v for k,v in lvls.items()),key=lambda k: k,reverse=True) print (x)
tagged with: sorting
has comment: http://stackoverflow.com/comment/80675169
has answer: http://stackoverflow.com/a/46863718
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/80675188
has title: Python sorting dictionary by key returning list of values itemgetter
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/46863718
has comment: http://stackoverflow.com/comment/80674668
score: 0
has comment: http://stackoverflow.com/comment/80675133

http://stackoverflow.com/comment/80701798
type: AnswerComment
score: 0
type: Comment
has text: I just tried using `last` and it worked! So thanks although I don't understand what caused it to work? Any recommended reading would be appreciated!
comment on: http://stackoverflow.com/a/46877057

http://stackoverflow.com/comment/80558250
comment on: http://stackoverflow.com/a/46805147
type: AnswerComment
score: 0
type: Comment
has text: Ok, I read a tutorial about Django & Ajax. I'll try this on my free time. Thanks treegarden & neuhaus :)

http://stackoverflow.com/q/46779860
has answer: http://stackoverflow.com/a/63797696
has answer: http://stackoverflow.com/a/50878600
has answer: http://stackoverflow.com/a/75577448
score: 9
linked to: http://stackoverflow.com/q/56716470
has answer: http://stackoverflow.com/a/46780815
tagged with: multiprocessing
upvote count: 9
has title: Multiprocessing managers and custom classes
answer count: 5
accepted answer: http://stackoverflow.com/a/63797696
type: AnsweredQuestion
downvote count: 0
has body: I do not know why, but I get this strange error whenever I try to pass to the method of a shared object shared custom class object. Python version: 3.6.3 Code: from multiprocessing.managers import SyncManager class MyManager(SyncManager): pass class MyClass: pass class Wrapper: def set(self, ent): self.ent = ent MyManager.register('MyClass', MyClass) MyManager.register('Wrapper', Wrapper) if __name__ == '__main__': manager = MyManager() manager.start() try: obj = manager.MyClass() lst = manager.list([1,2,3]) collection = manager.Wrapper() collection.set(lst) # executed fine collection.set(obj) # raises error except Exception as e: raise Error: --------------------------------------------------------------------------- Traceback (most recent call last): File "D:\Program Files\Python363\lib\multiprocessing\managers.py", line 228, in serve_client request = recv() File "D:\Program Files\Python363\lib\multiprocessing\connection.py", line 251, in recv return _ForkingPickler.loads(buf.getbuffer()) File "D:\Program Files\Python363\lib\multiprocessing\managers.py", line 881, in RebuildProxy return func(token, serializer, incref=incref, **kwds) TypeError: AutoProxy() got an unexpected keyword argument 'manager_owned' --------------------------------------------------------------------------- What's the problem here?
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/78668229
possible better answer: http://stackoverflow.com/a/50878600

http://stackoverflow.com/q/46884596
tagged with: http://stackoverflow.com/tag/json
has title: Parsing with ijson, lists become strings - make them nested lists of floats
score: 0
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/46886641
tagged with: ijson
tagged with: python
has comment: http://stackoverflow.com/comment/80716433
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80717758
accepted answer: http://stackoverflow.com/a/46886641
type: Question
has body: I have large .GEOJSON files that I parse using ijson. One data I load is coordinates listed as for example: "coordinates": [[[47335.8499999996, 6571361.68], [47336.2599999998, 6571360.54], [47336, 6571335.4]]] I'm able to load this data, having changed its type from Decimal.decimal() to float in the ijson object class. I use the following to parse the JOSN file. class ReadJSON: def __init__(self, filename, name=""): self.name = name self.f = open(datafolder+filename) self.objects = ijson.items(self.f, 'features') def load_file(self): for obj in self.objects: final_list = list() for entry in obj: temp_list = list() col_names = list() for key in entry.keys(): for col in entry[key]: temp_list.append(entry[key][col]) col_names.append(self.name+'.'+col) final_list.append(temp_list) df = pd.DataFrame(final_list, columns=col_names) return df Everything ends up where it should, but the list of coordinates is string type. I need to be able to work with the individual points and xy-coordinates. I will have for example: df_rivers, where df_rivers["coordinates"] will contain such lists. I have tried temp_list = "[[[47335.8499999996, 6571361.68], [47336.2599999998, 6571360.54], [47336, 6571335.4]]]" t_list = temp_list.split('],') print(temp_list[0]) out: [[[47335.8499999996, 6571361.68 type(temp_list[0]) is 'str' point = temp_list[0].split(',') print(point[0]): [[[47335.8499999996 type(point[0]) is 'str So I am able to access each point and coordinate, however it is quite cumbersome. In addition, point[1] suddenly became out of bounds in the middle of a temp_list. I have many of these lists, which are in reality much longer, and I need to be able to work easily with them. I don't care whether the fix lies in the loading of the data, or if I can apply it afterwards on the whole column as the script will rarely be run once finished. However, I will have 153 files with up to 60000 rows it will have to run through, so efficiency would be nice. I'm using Python 3.6.3

http://stackoverflow.com/a/46768606
has body: The thing to understand here is the kind of entities you are subtracting. a.keys() is an iterable. Which simply means that it can be iterated through using a for or iter. Formally speaking , in python anything is an iterable that implements __iter__ function. Check this link &gt;&gt; type(a.keys) &gt;&gt; dict_keys And dict_keys is an iterable, how do you know that? because it has an attribute __iter__. &gt;&gt; hasattr(a.keys() , '__iter__') &gt;&gt; True a.keys() returns a view object. Which allows you to subtract other iterables from itself. As stated in the docs: dictview - other Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set. So, to subract something from a.keys() , that entity should be an iterable too. In your case : a.keys() - 'a' works because strings are iterables in python &gt;&gt; hasattr('a' , '__iter__') &gt;&gt; True So, strings are iterables a.keys() - {'a'} works because {'a'} is a set, which is an iterable &gt;&gt; hasattr({'a'} , '__iter__') &gt;&gt; True On the other hand if you try this: &gt;&gt; a.keys() - 1 &gt;&gt; TypeError: 'int' object is not iterable So, you cannot subtract two objects which are not iterables. Hope this helps :)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46768337
type: Answer
answers question: http://stackoverflow.com/q/46768337
has comment: http://stackoverflow.com/comment/80482634
score: 1

http://stackoverflow.com/q/46867474
type: UnansweredQuestion
has body: I'm using the Anaconda Python distribution: Python 2.7 x64 with Windows 7 SP1 x64 Ultimate. Today after conda update --all importing matplotlib has broken: ImportError Traceback (most recent call last) &lt;ipython-input-4-6f467123fe04&gt; in &lt;module&gt;() ----&gt; 1 import matplotlib.pyplot C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\pyplot.py in &lt;module&gt;() 27 from cycler import cycler 28 import matplotlib ---&gt; 29 import matplotlib.colorbar 30 from matplotlib import style 31 from matplotlib import _pylab_helpers, interactive C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\colorbar.py in &lt;module&gt;() 34 import matplotlib.collections as collections 35 import matplotlib.colors as colors ---&gt; 36 import matplotlib.contour as contour 37 import matplotlib.cm as cm 38 import matplotlib.gridspec as gridspec C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\contour.py in &lt;module&gt;() 19 import matplotlib.colors as colors 20 import matplotlib.collections as mcoll ---&gt; 21 import matplotlib.font_manager as font_manager 22 import matplotlib.text as text 23 import matplotlib.cbook as cbook C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\font_manager.py in &lt;module&gt;() 56 57 import matplotlib ---&gt; 58 from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir 59 from matplotlib.compat import subprocess 60 from matplotlib.fontconfig_pattern import ( ImportError: DLL load failed: The specified procedure could not be found. Do you have any ideas how to roll back to stable version or what to downgrade? conda install anaconda and conda update anaconda do not change any packages. My current conda version is 4.3.30, matplotlib version is 2.1.0.
has answer: http://stackoverflow.com/a/47704230
has comment: http://stackoverflow.com/comment/80682684
downvote count: 0
has comment: http://stackoverflow.com/comment/80682762
has title: import matplotlib ImportError: DLL load failed: The specified procedure could not be found
favorite count: 0
has answer: http://stackoverflow.com/a/47593337
type: Question
answer count: 2
tagged with: python
score: 4
tagged with: anaconda
tagged with: matplotlib
upvote count: 4
has comment: http://stackoverflow.com/comment/81665737
has comment: http://stackoverflow.com/comment/81679883

http://stackoverflow.com/q/46880842
answer count: 0
tagged with: subset-sum
upvote count: 1
downvote count: 1
type: Question
has body: Problem: Given an array of size N, is it possible to divide the array into two groups of exactly N/2 elements each such that the sum of elements in both the groups are equal? What I tried: use the concept of subset sum where dp[i][j] is true if j elements can sum up to i. In the end the answer would be dp[sum/2][len(array)/2]. def equal_subset(a): s = sum(a) if len(a)%2 != 0 or s%2 != 0: return False dp = [[0 for j in range(len(a)+1)] for i in range(s+1)] dp[0][0] = 1 for i in range(1, s/2+1): for j in range(1, (len(a)+1)): dp[i][j] = dp[i][j-1] if i &gt;= a[j-1]: dp[i][j] = dp[i][j] or dp[i-a[j-1]][j-1] return dp[s/2][len(a)/2] print(equal_subset([2, 10, 20, 4, 5, 23])) Some folks are using dp with bitmasking as below: dp[i] gives you the bitmask of possible numbers of players that can make up a team with total experience i. To add 1 to each of the possible numbers of players for a given total experience, shift left by 1. To merge two sets of numbers, just take the bitwise OR. dp[i] |= dp[i-array[j]] &lt;&lt; 1 In the end the answer will be dp[sum/2][len(array)/2] Question: In both of the approaches, I think the time complexity would be the same, except in the second approach you will get better space complexity. Right?
has comment: http://stackoverflow.com/comment/80715793
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80716841
has comment: http://stackoverflow.com/comment/80717038
score: 0
tagged with: dynamic-programming
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: subset sum divisible in two groups with equal elements

http://stackoverflow.com/a/46829405
answers question: http://stackoverflow.com/q/46820182
upvote count: 1
has body: If you need single bits (one per call), you already did your benchmark and other answers provide additional info. If you need many bits or can pre-calculate bit-arrays for later consumption, numpy's methods might shine. Here is some more demo-approach using numpy (which surprisingly does not have a method dedicated for this job exactly): import numpy as np import random def sample_bits(N): assert N % 8 == 0 # demo only n_bytes = N // 8 rbytes = np.random.randint(0, 255, dtype=np.uint8, size=n_bytes) return np.unpackbits(rbytes) def alt(N): return np.random.choice([-1,1],size=N) def alt2(N): return [1 if random.random() &lt; 0.5 else -1 for i in range(N)] if __name__ == '__main__': import timeit print(timeit.timeit("sample_bits(1024)", setup="from __main__ import sample_bits", number=10000)) print(timeit.timeit("alt(1024)", setup="from __main__ import alt", number=10000)) print(timeit.timeit("alt2(1024)", setup="from __main__ import alt2", number=10000)) Output: 0.06640421246836543 0.352129537507486 1.5522800431775592 The general idea is: use numpy to generate many uint8's in one step (there might be something better using internal functions without the randint-API) unpack uint8's to 8 bits uniformity follows from randint's uniformity guarantees Again, this is only a demo: for one specific case not caring about different result-types of these functions not caring about -1 vs. 0 (might be important in your use-case) (not even optimal compared to much more low-level approaches; MT used internally can be used as a bit-source, which does not need fp-math, like many other PRNGs!)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/80531871
type: Comment
has text: what if tags contain commas, parentheses? wouldn't it be simpler to generate the list properly in the first place?
comment on: http://stackoverflow.com/q/46792667
score: 0
type: QuestionComment

http://stackoverflow.com/a/46789857
answers question: http://stackoverflow.com/q/46789586
type: Answer
has body: You should fix your sql: make one string in the form you want it to be. Something like select to_char(date(time), 'FMDay, FMDD, FMYear') + " - " + to_char(dec_value) + "% errors" Otherwise you will get array as return.
has comment: http://stackoverflow.com/comment/80535815
has comment: http://stackoverflow.com/comment/80527467
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46789586
score: 0

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/46788470
type: Tag
tags question: http://stackoverflow.com/q/46904355
tags question: http://stackoverflow.com/q/46873569
tags question: http://stackoverflow.com/q/46857639

http://stackoverflow.com/comment/80591440
type: QuestionComment
has text: You are simply mistaken. In Python, if a name isn't found in the local scope, it checks globals.
comment on: http://stackoverflow.com/q/46821912
score: 0
type: Comment

http://stackoverflow.com/q/46853873
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/80655444
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46854127
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80655656
has comment: http://stackoverflow.com/comment/80655655
type: Question
has body: I installed Python 3.6 on my Windows 64 bit machine (I already had Python 2.7 installed on it) I tried to pip3 install seaborn but scipy is a dependecy. I thought I had it installed but apparently I do not. I downloaded the corresponding wheel file from here: scipy‑0.19.1‑cp36‑cp36m‑win_amd64.whl. But when running pip3 installscipy‑0.19.1‑cp36‑cp36m‑win_amd64.whl` I am getting the error: scipy‑0.19.1‑cp36‑cp36m‑win_amd64.whl is not a supported wheel on this platform This problem has happened to many other people, but none of the solutions I've read had helped me: I made sure I am trying to install the correct version: Python 3.6 and 64-bit. Actually I downloaded and installed the wheel file for seaborn successfully, but that's not good enough because I still need scipy. I have tried upgrading pip with pip3 install --upgrade pip but the most recent version was already installed. What can I do other than installing Anaconda and having to set up again my Python 3 environment again? (and I wouldn't even be positive that this will work with Anaconda)
has comment: http://stackoverflow.com/comment/80655619
tagged with: python
has comment: http://stackoverflow.com/comment/80655431
accepted answer: http://stackoverflow.com/a/46854127
score: 0
has comment: http://stackoverflow.com/comment/80655531
tagged with: pip
has comment: http://stackoverflow.com/comment/80655287
answer count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/80655490
has title: SciPy Windows install: f.whl is not a supported wheel on this platform

http://stackoverflow.com/q/46853903
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/80655296
has comment: http://stackoverflow.com/comment/80655586
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46854129
downvote count: 3
has body: I am trying to create a function that takes two list compares them and give back a list which shows where the first list is different from the other one.Some examples follows: Example 1: list1: [1, 2, 3] list2: [1, 3] desired result: [0, 1, 0] Example 2 list1: [1, 3, 1, 2, 4] list2: [1, 1, 4] desired result: [0, 1, 0, 1, 0] Example 3 list1: [3, 5, 2, 9, 9] list2: [3, 5, 9, 9] desired result: [0, 0, 1, 0, 0] Example 4 list1: [1, 1, 1] list2: [1] desired result: [0, 1, 1] Example 5 list1: [1, 2, 2, 1] list2: [1, 2, 1] desired result: [0, 0, 1, 0] Some facts: list1 is always bigger or equal length with the list2 desired list has the length of the list1 The number of ones in the desired list is equal with the difference of the length of the two lists. My apologies that I do not provide any answer but I can not think of any way to implement this. Any guidance/tip?
has comment: http://stackoverflow.com/comment/80655229
type: Question
has answer: http://stackoverflow.com/a/46854088
accepted answer: http://stackoverflow.com/a/46854088
upvote count: 0
has comment: http://stackoverflow.com/comment/80655259
has title: Finding difference between two lists and creating a zero-one list
has answer: http://stackoverflow.com/a/46854053
has comment: http://stackoverflow.com/comment/80655168
has comment: http://stackoverflow.com/comment/80655220
answer count: 3
possible better answer: http://stackoverflow.com/a/46854129
favorite count: 0

http://stackoverflow.com/q/46879688
type: Question
has comment: http://stackoverflow.com/comment/80708354
has answer: http://stackoverflow.com/a/46879919
answer count: 2
has title: How to save an array of objects with Django Rest Framework
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
has body: I have this json code: { "word" : "world", "days" : ["tuesday", "thursday"] } And DRF gives me this error: 'days': [{'non_field_errors': ['Invalid data. Expected a dictionary, but got string.']}, This is my days serializer: class DaysSerializer(serializers.ModelSerializer): class Meta: model = Days fields = ('day') And this my top level serializer: class WordsSerializer(serializers.ModelSerializer): days = DaysSerializer(many=True) class Meta: model = Words fields = ('word', 'days') The Days model is: class Days(models.Model): DAYS = ( ("sunday", "Sunday"), ("monday", "Monday"), ("tuesday", "Tuesday"), ("wednesday", "Wednesday"), ("thursday", "Thursday"), ("friday", "Friday"), ("saturday", "Saturday")) day = models.TextField(choices=DAYS) I want to emphasize that the input: "days" : ["tuesday", "thursday"] are the values not the keys in the Days table. I read that I need to use bulk serializers. Is that the route that is recommended today? Or there is a simpler way? If I need to use the bulk serializer library, I don't understand from their example how I could use that library for my purposes? Namely to (bulk) save the many to many entries (the Days) with one of the records (the Word). P.S. By the way, the relation between days and Words is M2M with no through field. Just plain M2M P.S (2) The way that I image this should work is DRF will look in the Days table and try to find the Day where the day column equals tuesday and make a M2M. If it's not there, DRF needs to create the record and then make the M2M. Same thing for thursday.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46891286
tagged with: django
tagged with: python
downvote count: 0
score: 1

http://stackoverflow.com/comment/80625185
score: 0
comment on: http://stackoverflow.com/q/46767498
type: Comment
type: QuestionComment
has text: @rm4 Thanks for the reply, I'm not too keen on using a webdriver thing, I've attached my code for my spider above where i tried to do it based on your second option. Problem is I'm not getting any results when i run the spider

http://stackoverflow.com/a/46834672
has body: This is an example from Turbogears' default full-stack quickstart. from sqlalchemy import Table, ForeignKey, Column from sqlalchemy.types import Unicode, Integer, DateTime from sqlalchemy.orm import relation, synonym from .model import DeclarativeBase, metadata, DBSession # This is the association table for the many-to-many relationship between # groups and permissions. group_permission_table = Table('tg_group_permission', metadata, Column('group_id', Integer, ForeignKey('tg_group.group_id', onupdate="CASCADE", ondelete="CASCADE"), primary_key=True), Column('permission_id', Integer, ForeignKey('tg_permission.permission_id', onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)) # This is the association table for the many-to-many relationship between # groups and members - this is, the memberships. user_group_table = Table('tg_user_group', metadata, Column('user_id', Integer, ForeignKey('tg_user.user_id', onupdate="CASCADE", ondelete="CASCADE"), primary_key=True), Column('group_id', Integer, ForeignKey('tg_group.group_id', onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)) class Group(DeclarativeBase): __tablename__ = 'tg_group' group_id = Column(Integer, autoincrement=True, primary_key=True) group_name = Column(Unicode(16), unique=True, nullable=False) users = relation('User', secondary=user_group_table, backref='groups') class User(DeclarativeBase): __tablename__ = 'tg_user' user_id = Column(Integer, autoincrement=True, primary_key=True) user_name = Column(Unicode(16), unique=True, nullable=False) email_address = Column(Unicode(255), unique=True, nullable=False) display_name = Column(Unicode(255)) class Permission(DeclarativeBase): __tablename__ = 'tg_permission' permission_id = Column(Integer, autoincrement=True, primary_key=True) permission_name = Column(Unicode(63), unique=True, nullable=False) description = Column(Unicode(255)) groups = relation(Group, secondary=group_permission_table, backref='permissions')
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/46832855
has comment: http://stackoverflow.com/comment/80635595
type: Answer
downvote count: 0

http://stackoverflow.com/comment/95578711
comment on: http://stackoverflow.com/a/46781256
type: Comment
score: 0
type: AnswerComment
has text: Awesome answer, hats off! Saved loads of time.

http://stackoverflow.com/q/46858325
score: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46859744
type: Question
has title: Format output in python and Flask
answer count: 1
has body: I finally got the data to show in my browser however the issue I have a bit is how that data is displayed and the only thing I can do at the moment is create a new line. I am trying to actually put stuff into seperated line. My flask code from __future__ import print_function import flask from myoptimizer_optimizer import Site, Sport, get_optimizer app = flask.Flask(__name__) @app.route('/yield') def index(): def inner(): optimizer = get_optimizer(Site.SomeSite, Sport.SomeSport) optimizer.load_players_from_CSV("/myssdvfile.csv") player = optimizer.players[0] # get random player from optimizer players player.max_exposure = 0.5 lineup_generator = optimizer.optimize(3) for lineup in lineup_generator: yield '%s&lt;/br&gt;\n' % lineup return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show the partial page immediately app.run(debug=True) This returns info like this 1. Player1 Position Points 2. Player2 Position Points.... It does this 5 times in a row.. However I am trying to put something like: 1.Player1 Position Points 2.Player2 Position Points ------------------------- Next generated lines 1.Player1 Position Points 2.Player2 Position Points I have NO idea on how to separate the players. With Print and No flask it comes out just like I explained above.. but with Flask.. I just don't know how to format the text like that.
tagged with: flask

http://stackoverflow.com/q/46900207
tagged with: python-3.x
has body: I have this program: def NoOfPeople(people): if people.isdigit() and (int(people)&gt;=1) and (int(people)&lt;=1000): return True else: print('invalid') while True: people = input('No. of people:') if NoOfPeople(people): break How do I use data from it to a new defined function as I have this menu and program which I am stuck at right now on how to continue to get the data from the previous one.It is to check if the selected room can accommodate to the number of people that are entered in NoOfPeople(people). So how can I compare the number of people with which room it can accommodate: Room [1] Room A (10 person) [2] Room B (30 person) [3] Room C (50 person) venue = input('Please select a venue:') def validateVenue(venue): if venueList == '1': (what should I continue from here?) Help and suggestion please as I am new in using python.Thanks
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question
has title: Python: How to get data from other defined function to the other?
has answer: http://stackoverflow.com/a/47183908
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/46838640
has comment: http://stackoverflow.com/comment/80729471
has comment: http://stackoverflow.com/comment/80644537
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: data-science-experience
type: Question
has title: How to use python interactive gadgets in Data Science Experience DSX?
linked to: http://stackoverflow.com/q/45959687
has body: How can one use interactive gadgets in IBM Data Science Experience (DSX)? In Jupyter notebook I can use the following to have an interactive gadget: from ipywidgets import interact import ipywidgets as widgets # Very basic function def f(x): return x # Generate a slider to interact with interact(f, x=10,); I found the reason why ipywidgets does not work with DSX in another question (it seems IBM controls the configuration of the notebook server, including the list of enabled notebook extensions). How can I have a similar interactive gadget using DSX? Is there a neat way that I can get the same result as the above code in DSX?
score: 0

http://stackoverflow.com/comment/80520717
has text: didn't get you this time, can you please update your answer.
comment on: http://stackoverflow.com/a/46785814
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46881110
answers question: http://stackoverflow.com/q/46880968
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0
has body: The writerow method in the CSV writer library takes a list of columns. Currently, you are providing your whole string the value of the first column writer.writerow([line]) Instead, try splitting the string by \t, thus creating a list of each individual word and provide that to the library instead. writer.writerow(line.split("\t"))
score: 1
accepted answer of: http://stackoverflow.com/q/46880968

http://stackoverflow.com/comment/102059555
comment on: http://stackoverflow.com/a/46895617
type: AnswerComment
type: Comment
has text: Aha! The worst part is that it still syntax highlights it as a built-in when it's not.
score: 0

http://stackoverflow.com/comment/80572405
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46812096
score: 0
has text: @ctwheels, I don't want to to embed importance, merely tokens I would like to extract i.e. one is not important than any other.

http://stackoverflow.com/a/46845047
downvote count: 0
type: Answer
has body: You can replace the function used to format the messages; for example: def warning_on_one_line(message, category, filename, lineno, file=None, line=None): return '%s:%s: %s:%s\n' % (filename, lineno, category.__name__, message) warnings.formatwarning = warning_on_one_line Python Module of the week article
answers question: http://stackoverflow.com/q/46844809
score: 4
upvote count: 4

http://stackoverflow.com/a/46806097
has comment: http://stackoverflow.com/comment/117762460
has body: In the link to your task1 function, include the current URL as a query string: Task 1 Then in the view: from django.shortcuts import redirect def task1(request): # Do task 1... next = request.GET.get('next') if next: return redirect(next) # some fallback here… For completeness, and based on @Alasdair's comments, you can mimic what Django does to ensure that the redirect URL is safe: from django.conf import settings from django.shortcuts import redirect from django.utils.http import url_has_allowed_host_and_scheme def task1(request): # Do task 1... pass # Return the user-originating redirect URL if it's safe. redirect_to = request.GET.get("next") url_is_safe = url_has_allowed_host_and_scheme( url=redirect_to, allowed_hosts=settings.ALLOWED_HOSTS, require_https=request.is_secure(), ) if url_is_safe and redirect_to: return redirect(redirect_to) return redirect("http://www.example.com") For the original see https://github.com/django/django/blob/master/django/contrib/auth/views.py#L68, though that's a class-based view, rather than a function-based view as you have here. In a bid to future-proof this answer for a while longer: Read the comments below; @mlissner is talking sense, for example, regarding the renaming of this in Django 3+, Know that there are security implications with acting on user input, even from a query string and GET request, and if you're not writing to the database.
has comment: http://stackoverflow.com/comment/80559409
has comment: http://stackoverflow.com/comment/117762271
has comment: http://stackoverflow.com/comment/117762623
has comment: http://stackoverflow.com/comment/126678073
score: 8
accepted answer of: http://stackoverflow.com/q/46805965
has comment: http://stackoverflow.com/comment/80559822
answers question: http://stackoverflow.com/q/46805965
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/126698000
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/comment/80669693
score: 1
type: AnswerComment
has text: @AsheKetchum its not a matter of how frequently you call it but rather of how often this kind of idea is used in your code - if it happens more than once you might want to solve the problem once and for all by, for example, implementing a class for each region
type: Comment
comment on: http://stackoverflow.com/a/46839133

http://stackoverflow.com/a/46886929
score: 2
accepted answer of: http://stackoverflow.com/q/46886245
has body: Setting redirect_field_name isn't going to work - it is the name of a parameter, by default 'next', not the url to redirect to. If you want to the success url, you should override get_success_url. class LoginUserView(auth_views.LoginView): template_name = "Login/login.html" def get_success_url(self): url = self.get_redirect_url() if url: return url elif self.request.user.is_superuser: return reverse("admin") else: return reverse("profile") The get_redirect_url() call at the beginning of the method means that the default behaviour that tries to use the redirect field will still work.
answers question: http://stackoverflow.com/q/46886245
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/46881413
favorite count: 0
accepted answer: http://stackoverflow.com/a/46881459
has body: Cython's datetime.pyd exposes a datetime_new function, which is a wrapper around datetime.h's PyDateTime_CAPI.DateTime_FromDateAndTime. However, whenever I actually try to use this function, I get a segmentation fault immediately, even with valid values. Here is a minimal working example of Cython code: cimport cpython.datetime cpdef cpython.datetime.datetime construct_datetime(): return cpython.datetime.datetime_new(2017, 12, 1, 12, 30, 15, 0, None) Here is the setup.py: from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize('test_segfault.pyx')) And if I run it I get this: $ python setup.py build_ext --inplace &gt; /dev/null $ $ python -c 'from test_segfault import construct_datetime; construct_datetime()' Segmentation fault (core dumped) I'm using Cython version 0.25.2 on Arch Linux, Python 3.6.1: $ python -c 'import sys; print(sys.version)' 3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:09:58) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] Am I using this function wrong? I am aware that I can just call the standard cpython.datetime.datetime constructor here, but datetime_new bypasses the range checks, and I'm trying to see how much time the additional checks take.
tagged with: datetime
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46881459
score: 1
tagged with: cython
has title: Cython's cpython.datetime.datetime_new causes segmentation fault
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/q/46854872
duplicate of: http://stackoverflow.com/q/240178
answer count: 0
type: UnansweredQuestion
type: Question
has title: How do I assign an element in matrix?
has comment: http://stackoverflow.com/comment/80657657
has body: I have mat = [[0]*5]*5 to create a 2-d matrix of all zeros. When I do mat[0][0] = 1, I want it to be only [[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] but when I print mat, I get: [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0]] How do I access an individual element?
has comment: http://stackoverflow.com/comment/80657817
score: 0
has comment: http://stackoverflow.com/comment/80657441
linked to: http://stackoverflow.com/q/240178
tagged with: python

http://stackoverflow.com/q/46851212
has title: Django first app
has answer: http://stackoverflow.com/a/46851274
score: 0
answer count: 1
has body: I have some problems with my first django app (its name is magghy). I'm at the start of development. So, I have: magghy/urls.py: from django.conf.urls import * from magghy import views from . import views app_name = 'magghy' urlpatterns = [ # esempio: /magghy/ url(r'^$', views.index, name='index'), #esempio: /magghy/5/ url(r'^(?P&lt;question_id&gt;[0-9]+)/$', views.detail, name='detail'), # ex: /magghy/5/results/ url(r'^(?P&lt;question_id&gt;[0-9]+)/results/$', views.results, name='results'), # ex: /magghy/5/vote/ url(r'^(?P&lt;question_id&gt;[0-9]+)/vote/$', views.vote, name='vote'), ] In magghy/views.py: from __future__ import unicode_literals from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from .models import Choice, Question from django.template import loader from django.urls import reverse #visualizzare domande e argomento specifico - collegare con modulo magghy.urls def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) #visualizzare pagina html secondo schema index.html oppure html 404 (eccezione) def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('magghy/index.html') context = RequestContext (request, { 'latest_question_list': latest_question_list, }) return HttpResponse(template.render(context)) #visualizzare pagina 404 def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) In mysite/urls.py: from django.conf.urls import * from django.contrib import admin from magghy import views u…
accepted answer: http://stackoverflow.com/a/46851274
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/46892175
answers question: http://stackoverflow.com/q/46890257
type: Answer
has comment: http://stackoverflow.com/comment/80796718
accepted answer of: http://stackoverflow.com/q/46890257
score: 0
type: AcceptedAnswer
has body: You could just use the messages framework - that's what it's for. Oh and yes: if that's just for displaying informations (no side effect on the server), you should use a GET request - POST is for submitting data for processing by the server.

http://stackoverflow.com/comment/99754144
type: AnswerComment
has text: @DangManhTruong No it doesn't.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46842547

http://stackoverflow.com/a/46775180
score: 1
accepted answer of: http://stackoverflow.com/q/46774723
has body: If I understood correctly what you want is this: l2=[2,1,8,3,6,4] l1=[] def check(): i = max(l2) l2.remove(i) if len(l1) &gt; 0: for number in l1: if abs(number - i) &lt; 2: return l1 l1.append(i) check()
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46774723

http://stackoverflow.com/q/46853123
has title: Does pyspark.sql.DataFrameReader read a single csv file in parallel on S3?
favorite count: 0
tagged with: python
answer count: 0
downvote count: 0
has body: So, I am looking at the pyspark docs and using pyspark.sql.DataFrameReader I am wondering though does it process a single csv file in parallel when I give it an S3 path? How could each of the worker nodes read the same csv file on S3?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80753015
type: Question
score: 3
tagged with: apache-spark-sql
tagged with: amazon-s3
tagged with: pyspark
upvote count: 3
tagged with: apache-spark

http://stackoverflow.com/comment/80644528
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46846714
type: AnswerComment
has text: Tried, No luck! My earlier code was also tested using online python compiler https://repl.it/Mwpx. I've anyways edited code in the main question with the code provided by you again along with new error - "errorMessage": "Bad handler 'index_handler'". I've also attached the snapshot of the image from my AWS portal in the main question. Please check.

http://stackoverflow.com/a/46753072
has body: After some trying, I did something like this: for crisis in crisisList: plansInCrisis = planList.filter(plan_crisisID__crisis_ID=crisis.crisis_ID) max = plansInCrisis[0] for plan in plansInCrisis: if(plan.plan_ID &gt; max.plan_ID ): max = plan toDisplay.append(max) As i'm new to python programming, I assume this is bad practice if I loop twice without using any inbuilt methods, but it works for now. Sorry for the poor question, cheers
type: Answer
answers question: http://stackoverflow.com/q/46752477
score: 0

http://stackoverflow.com/q/46759090
answer count: 1
has title: create_image() function python only displays last image in loop
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/80463895
has body: I'm trying to create a program that shows a series of images in a loop, but the create_image() function only draws the last image I try to draw. for i in range(len(imgList)): filename = PhotoImage(file = str(imgList[i]).lower() + ".png") C.create_image(45 * (i + 1), 5, anchor=NE, image=filename) print("created image") This prints "created image" however many times it needs to, but only the last image is shown. imgList is just the name of all the images
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/46765976
tagged with: tkinter-canvas
score: 0

http://stackoverflow.com/q/46751271
accepted answer: http://stackoverflow.com/a/46751455
score: 0
has comment: http://stackoverflow.com/comment/80448580
has comment: http://stackoverflow.com/comment/80448422
has comment: http://stackoverflow.com/comment/80448844
has answer: http://stackoverflow.com/a/46751455
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80448833
favorite count: 0
has title: Why is HomeBrew (MacOs) installing Python 3.5.2 instead of Python 3.6.3 (latest as shown on https://www.python.org/downloads/)
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/80448910
upvote count: 1
tagged with: python
has body: I used homebrew to install Python3 and instead of getting Python 3.6.3, I am getting 3.5.2 As per https://www.python.org/downloads/, the latest stable version of Python3 is 3.6.3. Looks like others hit the same issue as well - see Why can&#39;t i install python 3.6 with homebrew? Can anyone help out with what is going on here? a-mac:Cellar AB$ brew install python3 Updating Homebrew... ==&gt; Installing dependencies for python3: sqlite, gdbm, openssl ==&gt; Installing python3 dependency: sqlite ==&gt; Downloading https://homebrew.bintray.com/bottles/sqlite-3.20.1.sierra.bottle.tar.gz ######################################################################## 100.0% ==&gt; Pouring sqlite-3.20.1.sierra.bottle.tar.gz ==&gt; Caveats This formula is keg-only, which means it was not symlinked into /usr/local, because macOS provides an older sqlite3. If you need to have this software first in your PATH run: echo 'export PATH="/usr/local/opt/sqlite/bin:$PATH"' &gt;&gt; ~/.bash_profile For compilers to find this software you may need to set: LDFLAGS: -L/usr/local/opt/sqlite/lib CPPFLAGS: -I/usr/local/opt/sqlite/include ==&gt; Summary /usr/local/Cellar/sqlite/3.20.1: 11 files, 3.0MB ==&gt; Installing python3 dependency: gdbm ==&gt; Downloading https://homebrew.bintray.com/bottles/gdbm-1.13.sierra.bottle.tar.gz ######################################################################## 100.0% ==&gt; Pouring gdbm-1.13.sierra.bottle.tar.gz /usr/local/Cellar/gdbm/1.13: 19 files, 554.4KB ==&gt; Installing python3 dependency: openssl ==&gt; Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2l.sierra.bottle.tar.gz ######################################################################## 100.0% ==&gt; Pouring openssl-1.0.2l.sierra.bottle.tar.gz ==&gt; Caveats A CA file has been bootstrapped using certificates from the SystemRoots keychain. To add additional certificates (e.g. the certificates added in the System keychain), place .pem files in /usr/local/etc/openssl/certs and run /…
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/80692577
score: 0
comment on: http://stackoverflow.com/q/46872566
type: Comment
type: QuestionComment
has text: @ the (now deleted) comment: I can't speak for the downvoter, but the drop command didn't work, the "name" of the column isn't "fast"/"slow", it's `close_#_ema`, but even changed the argument `axis` throws an error

http://stackoverflow.com/a/62007026
score: 0
type: Answer
has body: calling class of 'btn--alt' when you go to second page will not work as this is the same class name for both buttons 'Next' and 'Previous', and it was clicking on previous button and return me back again !! below code change worked for me perfectly nextButton = driver.find_element_by_xpath('//input[@value="Next"]') nextButton.click() full function: def duckduckGoSearch(query,searchPages = None,filterTheSearch = False,searchFilter = None): URL_ = 'https://duckduckgo.com/html?' driver = webdriver.Chrome() driver.get(URL_) query = query searchResults = {} filterTheSearch = filterTheSearch searchFilter = searchFilter searchFilter = searchFilter # # click on search textBox # item = driver.find_element_by_xpath('//*[@id="sb_form_q"]').click() # # #Enter your search query item = driver.find_element_by_xpath('//*[@id="search_form_input_homepage"]').send_keys(query) # # Click enter to perform the search process item = driver.find_element_by_xpath('//*[@id="search_form_input_homepage"]').send_keys(Keys.RETURN) time.sleep(2) page_number = 1 while True: # loop for the required number of pages if page_number &lt;= searchPages: try: nextButton = driver.find_element_by_xpath('//input[@value="Next"]') nextButton.click() page_number += 1 try: webPageSource = driver.page_source # parse and get the urls for the results soup = BeautifulSoup(webPageSource, "html.parser") Data_Set_div_Tags = soup.findAll('h2') + soup.findAll('div', {'class': 'result__body links_main links_deep'}) for i in range(0, len(Data_Set_div_Tags)): try: resultDescription = Data_Set_div_Tags[i].findAll('a')[0].text resultURL = Data_Set_div_Tags[i].findAll('a')[0]['href'] except: print('nothing to parse') pass if resultURL not in searchResults.keys(): if filterTheSearch: if searchFilter in resultURL: searchResults[resultURL] = resultDescription else: searchResults[resultURL] = resultDescription except: print('search is done , found ', len(searchResults), 'Results') break # pass except: # change something so it stops…
answers question: http://stackoverflow.com/q/46771995

http://stackoverflow.com/q/46848067
has comment: http://stackoverflow.com/comment/80643365
has answer: http://stackoverflow.com/a/46848373
has comment: http://stackoverflow.com/comment/80643520
tagged with: anaconda
score: 0
answer count: 1
has title: anaconda python running py file
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I downloaded python anaconda 2.7. I used to work with the regular python from python.org, but I was asked to work with anaconda. any how, I have 2 problems. right click ->edit with idle (does not exist). can't run py file as a program (like cmd)/.
has comment: http://stackoverflow.com/comment/80644008
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/46798399
has body: Right now, I have a code that look something along the lines of: def get_newdeck(choice, P1, P2, P3): deck = [] if choice == 1: deck = P2+P1+P3 return deck elif choice == 2: deck = P1+P2+P3 return deck else: deck = P1+P3+P2 return deck This is part of a code that is part of a code for a magic trick, which guesses the user's card from a 'deck' of 21. choice is a user input (integer that is either 1, 2, or 3) for which pile the card was previously in, P1, P2, P3 are lists that represent the three piles; more is explained about these piles below. An algorithmic card trick works as follows: The magician deals 21 shuffled playing cards face up into three piles working left-to-right row-by-row. The first time the magician does this an audience member is asked to choose one of the cards and keep their choice secret. The magician asks the audience member to say whether their card is in the first, second or third pile. 3. The magician collects the cards pile by pile ensuring the selected pile is placed in between the other two piles. Steps 1-3 are repeated 2 more times. Once these steps are completed, the chosen card will ‘magically’ be in the middle of the deck of 21 cards. The step in question is step three, and I am trying to make it look less repetitive. Is there a way that I could get my code (shown above) to work using a loop? F.Y.I I am using Python-3.x If you want it, here is the full code - I know it's messy, and there are no comments, but I am trying to fix it, starting with the 'messy' part. import random def get_cards(): nums, suits=['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'], ['Hearts','Clubs','Diamonds','Spades'] cards_dealt=[] while len(cards_dealt) &lt; 22: card = random.choice(nums) + " of " + random.choice(suits) if card not in cards_dealt: cards_dealt.append(card) else: continue return cards_dealt def get_piles(deck): P1, P2, P3 = [], [], [] for i in range(21): if i%3 == 0: P1.append(deck[i]) elif i%3 == 1: P2.append(deck[i]) else: P…
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80544692
tagged with: loops
has comment: http://stackoverflow.com/comment/80543992
type: Question
has comment: http://stackoverflow.com/comment/80544774
has answer: http://stackoverflow.com/a/46799354
has answer: http://stackoverflow.com/a/46799554
score: 0
has title: How to put lists into one larger list in a certain order for certain conditions? - Python 3.x
answer count: 3
accepted answer: http://stackoverflow.com/a/46799309
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46799354
tagged with: python
has answer: http://stackoverflow.com/a/46799309

http://stackoverflow.com/q/46861899
score: 1
accepted answer: http://stackoverflow.com/a/46861917
type: Question
tagged with: group-by
has answer: http://stackoverflow.com/a/46861917
tagged with: dataframe
upvote count: 2
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/72965011
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/72965011
tagged with: python
has body: I have dataframe which looks like this: revisionId itemId wikidataType 1 307190482 23 Q5 6 305019084 80 Q5 8 303692414 181 Q5 9 306600439 192 Q5 11 294597048 206 Q5 In complete dataframe, there are 100 such different values present in column wikidataType. Its a large dataframe, so I want to restrict it to 1000 records per wikidataType. Hence, I used following thing: df = df[df.groupby('wikidataType')['wikidataType'].cumcount() &lt; 1000] This gives e like first 1000 records for each wikidataType. I want to choose these 1000 records randomly. So I tried using df = df[random.sample(list(df.groupby('wikidataType')['wikidataType']), 1000)] But gave an error as: TypeError: 'Series' objects are mutable, thus they cannot be hashed I even tried df = df[df.groupby('wikidataType')['wikidataType'].cumcount().random() &lt; 1000] But that also didn't work. Anyone know how can I do this? Thanks in advance.
has title: Picking random elements from groupby using pandas
type: AnsweredQuestion

http://stackoverflow.com/q/46890464
has comment: http://stackoverflow.com/comment/80728425
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/46890545
has body: I have a Django (v1.11.6) app on my Ubuntu server and was using Python v2.7. I am now using Python 3.5 (not using virtualenv), however when I run sudo service apache2 restart I get the following error in my browser: ImportError at / No module named 'django.urls' Request Method: GET Request URL: https://dev.ga.coach/ Django Version: 1.8.7 Exception Type: ImportError Exception Value: No module named 'django.urls' Python Executable: /usr/bin/python3 Python Version: 3.5.2 When I run python3 manage.py runserver I get no error. When I execute sudo pip freeze | grep -i 'django' I get the following: Django==1.11.6 django-allauth==0.33.0 django-filter==1.0.4 django-rest-auth==0.9.1 djangorestframework==3.6.3 djangorestframework-jwt==1.11.0
favorite count: 0
has comment: http://stackoverflow.com/comment/80728703
has title: django app on server: No module named 'django.urls'
has comment: http://stackoverflow.com/comment/80728322
has comment: http://stackoverflow.com/comment/80729394
has comment: http://stackoverflow.com/comment/80729369
has comment: http://stackoverflow.com/comment/80729184
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80728527
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46890545
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80729328
has comment: http://stackoverflow.com/comment/80729129
tagged with: apache
score: -1
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/80729233
has comment: http://stackoverflow.com/comment/80728162

http://stackoverflow.com/comment/80747422
comment on: http://stackoverflow.com/q/46899862
score: 0
type: QuestionComment
type: Comment
has text: I've updated the question with the code. Please take a look.

http://stackoverflow.com/a/46881441
answers question: http://stackoverflow.com/q/46881382
score: 4
downvote count: 0
type: Answer
has body: Python follows the IEEE 754 floating point specification.* (64-bit) IEEE floats are essentially a form of base 2 scientific notation, broken down as follows: One bit for the sign (positive or negative) 53 bits for the mantissa or significand, including the implied leading one. 11 bits for the exponent. Multiplying or dividing a floating point value by two, or any power of two, only affects the exponent, and not the mantissa.** As a result, it is normally a fairly "stable" operation by itself, so 2/3 should yield the same result as 4/6. However, IEEE floats still have the following problems: Most operations are not associative (e.g. (a * b) * c != a * (b * c) in the general case). More complicated operations are not required to be correctly rounded (however, as Tim Peters points out, division certainly is not a "more complicated" operation and will be correctly rounded).*** Intermediate results are always rounded to 53 bits. You should be prepared to handle these issues and assume that most mathematically-equivalent floating point expressions will not result in identical values. In Python specifically, you can use math.isclose() to estimate whether two floats are "close enough" to be "probably the same value." * Actually, this is a lie. Python follows C's double, which nearly always follows IEEE 754 in some fashion, but might deviate from it on sufficiently exotic architectures. In such cases the C standard provides few or no guarantees, so you will have to look to your architecture or compiler's floating point documentation. ** Provided the exponent does not overflow or underflow. If it does, then you will typically land on an appropriately-signed infinity or zero, respectively, or you might underflow to a denormal number depending on architecture and/or how Python was compiled. *** The exact set of "more complicated" operations varies somewhat because IEEE 754 made a lot of operations optional while still demanding precision. As a result, it is seldom obvious wheth…
has comment: http://stackoverflow.com/comment/80710288
upvote count: 4

http://stackoverflow.com/q/46893448
has comment: http://stackoverflow.com/comment/80743721
has comment: http://stackoverflow.com/comment/80734332
has comment: http://stackoverflow.com/comment/80734596
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80734302
tagged with: python
has comment: http://stackoverflow.com/comment/80734356
has comment: http://stackoverflow.com/comment/80735682
type: Question
has body: I have a set of data that has column names and values to create a dataframe. However one of the column values is another dataframe is it possible to do this in pandas, or are each column values meant to be a single value? For example what I am trying to achieve would look something like this; df out: A B C 0 A1 B1 D E D1 E1 F G F1 G1 This is where letters that have numbers with them are the values, and just letters are the column names.
has comment: http://stackoverflow.com/comment/80734439
score: 0
has title: Is there a way to put a dataframe as the value of a specific column in pandas python?
tagged with: pandas
has comment: http://stackoverflow.com/comment/80734246
answer count: 1
has answer: http://stackoverflow.com/a/46898960

http://stackoverflow.com/q/46842923
tagged with: python-multiprocessing
accepted answer: http://stackoverflow.com/a/46843159
upvote count: 4
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/80633745
has body: So, I'm working on an application that has to check ~50 GB of data against a list of hashes every time it starts up. Obviously this needs to be parallelized, and I don't want the application hanging on a "LOADING..." screen for a minute and a half. I'm using multiprocessing.Pool's map_async to handle this; the main thread calls map_async(checkfiles, path_hash_pairs, callback) and provides a callback that tells it to throw up a warning if mismatches are found. Trouble is... nothing happens. Looking at the Python processes with my task manager shows they spawn and then immediately terminate without doing any work. They never print anything and certainly never finish and call the callback. This minified example also exhibits the same problem: def printme(x): time.sleep(1) print(x) return x**2 if __name__ == "__main__": l = list(range(0,512)) def print_result(res): print(res) with multiprocessing.Pool() as p: p.map_async(printme, l, callback=print_result) p.join() time.sleep(10) Run it, and... nothing happens. Swapping map_async for map works exactly as expected. Am I just making a stupid mistake or what?
has title: multiprocessing.Pool.map_async doesn't seem to... do anything at all?
tagged with: python
has answer: http://stackoverflow.com/a/46843159
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/46865816
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Read py.test's output as object
score: 3
tagged with: pytest
upvote count: 3
tagged with: python-unittest
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/46866403
has body: Earlier I was using python unittest in my project, and with it came unittest.TextTestRunner and unittest.defaultTestLoader.loadTestsFromTestCase. I used them for the following reasons, Control the execution of unittest using a wrapper function which calls the unittests's run method. I did not want the command line approach. Read the unittest's output from the result object and upload the results to a bug tracking system which allow us to generate some complex reports on code stability. Recently there was a decision made to switch to py.test, how can I do the above using py.test ? I don't want to parse any CLI/HTML to get the output from py.test. I also don't want to write too much code on my unit test file to do this. Can someone help me with this ?
answer count: 2
has answer: http://stackoverflow.com/a/46867867
downvote count: 0

http://stackoverflow.com/a/46769522
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can create an iterator for your date and responder lists and then call next() in your if statement to take the next item from the list data = [{'response': 'This is a response', 'review': 'This is a review'}, {'review': 'This is only a review'}, {'response': 'This is also a response', 'review': 'This is also a review'}] date = ['4 days ago', '3 days ago'] responder = ['Manager', 'Customer service'] d_iter = iter(date) r_iter = iter(responder) for d in data: if 'response' in d: d['date'] = next(d_iter) d['responder'] = next(r_iter) print(data) &gt;&gt; [ {'date': '4 days ago', 'review': 'This is a review', 'responder': 'Manager', 'response': 'This is a response'}, {'review': 'This is only a review'}, {'date': '3 days ago', 'review': 'This is also a review', 'responder': 'Customer service', 'response': 'This is also a response'} ]
has comment: http://stackoverflow.com/comment/80484490
accepted answer of: http://stackoverflow.com/q/46769257
answers question: http://stackoverflow.com/q/46769257
score: 4
upvote count: 4

http://stackoverflow.com/comment/80709377
type: Comment
has text: Thanks folks. I made your changes but I am getting a blank output. $count is just a counter that I will use in the py script to loop. test.php is $count = 3; $before_json = array("qwe","wer","ert"); $after_json = json_encode($before_json ); $escaped_json = escapeshellarg($after_json); $command = escapeshellcmd("python test.py $escaped_json $count"); $output = shell_exec($command); echo $output; and test.py is import sys, json escaped_json = sys.argv[1] count = sys.argv[2] parsed_data = json.loads(escaped_json) print (parsed_data[0])
comment on: http://stackoverflow.com/a/46866801
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80537159
type: Comment
comment on: http://stackoverflow.com/a/46779568
has text: Hey, Could you also advise me that how can I preprocess the text if my text is a dataframe column. I want to remove all punctuation, digits, and lemmatize text and remove stopwords from all rows of one column of dataframe.
score: 0
type: AnswerComment

http://stackoverflow.com/q/46751441
possible better answer: http://stackoverflow.com/a/58582789
tagged with: radix
has answer: http://stackoverflow.com/a/58582789
has comment: http://stackoverflow.com/comment/80448939
tagged with: string
has answer: http://stackoverflow.com/a/46752068
favorite count: 0
has comment: http://stackoverflow.com/comment/80448983
has comment: http://stackoverflow.com/comment/80449843
has comment: http://stackoverflow.com/comment/80449677
has title: Converting from a string to a number in base-64
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80448801
accepted answer: http://stackoverflow.com/a/46752068
linked to: http://stackoverflow.com/q/46739875
has comment: http://stackoverflow.com/comment/80448967
type: Question
tagged with: number-theory
answer count: 2
has body: So, I am trying to write a program to decode 6-character base-64 numbers. Here is the problem statement: Return the 36-bit number represented as a base-64 number in reverse order by the 6-character string s where the order of the 64 numerals is: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-+ i.e. decode('000000') → 0 decode('gR1iC9') → 9876543210 decode('++++++') → 68719476735 I would like to do this WITHOUT strings. The easiest way to do this would be to create the inverse of the following function: def get_digit(d): ''' Convert a base 64 digit to the desired character ''' if 0 &lt;= d &lt;= 9: # 0 - 9 c = 48 + d elif 10 &lt;= d &lt;= 35: # A - Z c = 55 + d elif 36 &lt;= d &lt;= 61: # a - z c = 61 + d elif d == 62: # - c = 45 elif d == 63: # + c = 43 else: # We should never get here raise ValueError('Invalid digit for base 64: ' + str(d)) return chr(c) # Test `digit` print(''.join([get_digit(d) for d in range(64)])) def encode(n): ''' Convert integer n to base 64 ''' out = [] while n: n, r = n // 64, n % 64 out.append(get_digit(r)) while len(out) &lt; 6: out.append('0') return ''.join(out) # Test `encode` for i in (0, 9876543210, 68719476735): print(i, encode(i)) Output 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-+ 0 000000 9876543210 gR1iC9 68719476735 ++++++ Which is actually from PM 2Ring on this page. How do I write the inverse of this program? A start: The inverse of get_digits as above is below: def inv_get_digit(c): if 0 &lt;= c &lt;= 9: d = ord(c) - 48 elif 'A' &lt;= c &lt;= 'Z': d = ord(c) - 55 elif 'a' &lt;= c &lt;= 'z' d = ord(c) - 61 elif c == '+': d = 63 elif c == '-': d = 62 else: raise ValueError('Invalid Input' + str(c)) return d def decode(n): out = [] while n: n, r= n % 10, n ** (6-len(str)) out.append(get_digit(r)) while len(out) &lt; 10: out.append('0') return ''.join(out)
downvote count: 0
has comment: http://stackoverflow.com/comment/80449188

http://stackoverflow.com/comment/80680269
type: QuestionComment
has text: What's going on with stuff under header2 and 4 then?
score: 0
comment on: http://stackoverflow.com/q/46866327
type: Comment

http://stackoverflow.com/comment/80698958
has text: Wise words by dirkgroten.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46876000

axes
tag name: axes
type: Tag
tags question: http://stackoverflow.com/q/46895674

http://stackoverflow.com/comment/80647183
type: Comment
comment on: http://stackoverflow.com/q/46849831
type: QuestionComment
has text: Possible duplicate of [Numpy where function multiple conditions](https://stackoverflow.com/questions/16343752/numpy-where-function-multiple-conditions)
score: 3

http://stackoverflow.com/q/46878471
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/49865152
answer count: 3
linked to: http://stackoverflow.com/q/46135302
has title: Download files via selenium headless chrome on python
has answer: http://stackoverflow.com/a/46886948
favorite count: 0
tagged with: selenium-chromedriver
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: So the issue of downloading files via headless chrome with selenium still seems to be a problem as it was asked here with no answer over a month ago. but I don't understand how they are implementing the js which is in the bug thread. Is there an option I can add or a current fix for this? The original bug page located here All of my stuff is up to date as of today 10/22/17 In python: from selenium import webdriver options = webdriver.ChromeOptions() prefs = {"download.default_directory": "C:/Stuff", "download.prompt_for_download": False, "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True } options.add_experimental_option("prefs", prefs) options.add_argument('headless') driver = webdriver.Chrome(r'C:/Users/aaron/chromedriver.exe', chrome_options = options) # test file to download which doesn't work driver.get('http://ipv4.download.thinkbroadband.com/5MB.zip') If the headless option is removed this works no problem. The actual files I'm attempting to download are PDFs located at .aspx URLs. I'm downloading them by doing a .click() and it works great except not with the headless version. The hrefs are javascript do_postback scripts.
tagged with: selenium-webdriver
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47054421

http://stackoverflow.com/comment/80514362
has text: can you be specific actually where is the problem with my code? @Linovia
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46783667
score: 0

http://stackoverflow.com/q/46793459
has body: I would like to to fill pdf forms of pdf file from website: https://e-justice.europa.eu/content_european_payment_order_forms-156-en.do#action The file name is Form A - Application for a European order for payment (click on pdf picture). Lets say I want to fill first two fields using python: from fdfgen import forge_fdf fields = [('field1','Some text'), ('field2', 'some text')] fdf = forge_fdf("",fields,[],[],[]) fdf_file = open("data.fdf","wb") fdf_file.write(fdf) fdf_file.close() Then I fill my pdf with above data.fdf file: pdftk form.pdf fill_form data.fdf output output.pdf flatten If I then open my pdf I can see symbols (little cubes) instead of text: If I click in the form the text appears, but only if form is active. Do you know why I get symbols instead text?
tagged with: fdfgen
has comment: http://stackoverflow.com/comment/80533589
has comment: http://stackoverflow.com/comment/80533835
has comment: http://stackoverflow.com/comment/80533646
type: Question
score: 0
has title: Symbols instead text when fill pdf forms
tagged with: pdftk
tagged with: pdf-form
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/80544822
tagged with: python
has comment: http://stackoverflow.com/comment/80533911
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/46813998
has comment: http://stackoverflow.com/comment/80587413
upvote count: 7
has body: It's a known bug, use: def percentile_25(x): return np.percentile(x, 25) def percentile_75(x): return np.percentile(x, 75)
has comment: http://stackoverflow.com/comment/80577149
type: Answer
accepted answer of: http://stackoverflow.com/q/46813921
downvote count: 0
answers question: http://stackoverflow.com/q/46813921
score: 7
type: AcceptedAnswer

http://stackoverflow.com/comment/80651858
score: 0
has text: Totally forgot to include that haha - edited
comment on: http://stackoverflow.com/q/46852209
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80601405
type: AnswerComment
comment on: http://stackoverflow.com/a/46818614
has text: cool! i know where i had gone wrong now. was trying to append the dictionary to a specific position in the list. that will definitely not work. still very new to python. at least i know now. thanks eyllanesc!
score: 0
type: Comment

http://stackoverflow.com/comment/80511194
score: 0
has text: @snakepain good, glad it works. I was scratching my head for a second there.
type: AnswerComment
comment on: http://stackoverflow.com/a/46782360
type: Comment

http://stackoverflow.com/q/46810211
has body: I am wondering is their anyway I can iterate over a worksheet and determine len of my index using xlsxwriter? The code that I am using right now isnt working how I want. for worksheet in workbook.worksheets(): if len(worksheet.index) &lt;= 1: worksheet.hide() else: move on and do something else what I am expecting it to do is look and see if their is more than 1 row of data and if their is continue else hide that worksheet. once again I am using xlsxwriter and I havent found a way to do that. Any help would be greatly appreciated
tagged with: loops
tagged with: worksheet
type: Question
score: 3
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/46813071
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46813071
has title: Looping through sheets looking at index using xlsxwriter
upvote count: 3

http://stackoverflow.com/comment/80552193
type: QuestionComment
comment on: http://stackoverflow.com/q/46802164
has text: @TomKarzes no using python 2.6
score: 0
type: Comment

http://stackoverflow.com/a/46758290
has comment: http://stackoverflow.com/comment/80461957
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/46758178
answers question: http://stackoverflow.com/q/46758178
downvote count: 0
score: 1
has body: Do $ export KERAS_BACKEND=tensorflow and re-run your program. Apparently you defined it, but chose something outside of those 3 values.

http://stackoverflow.com/comment/80596728
type: QuestionComment
score: 0
has text: That said, the file apparently contains non-ascii characters, and it seems that the bit of Anaconda code there can't deal with non-ascii `iid` values even if they are decoded correctly?
type: Comment
comment on: http://stackoverflow.com/q/46824087

http://stackoverflow.com/q/46780577
upvote count: 2
tagged with: file
accepted answer: http://stackoverflow.com/a/46780828
has body: I have a csv file like this: (no headers) aaa,1,2,3,4,5 bbb,2,3,4,5,6 ccc,3,5,7,8,5 ddd,4,6,5,8,9 I want to search another csv file: (no headers) bbb,1,2,3,4,5,,6,4,7 kkk,2,3,4,5,6,5,4,5,6 ccc,3,4,5,6,8,9,6,9,6 aaa,1,2,3,4,6,6,4,6,4 sss,1,2,3,4,5,3,5,3,5 and print rows in the second file(based on matching of the first columns) that exist in the first file. So results will be: bbb,1,2,3,4,5,,6,4,7 ccc,3,4,5,6,8,9,6,9,6 aaa,1,2,3,4,6,6,4,6,4 I have following code, but it does not print anything: labels = [] with open("csv1.csv", "r") as f: f.readline() for line in f: labels.append((line.strip("\n"))) with open("csv2.csv", "r") as f: f.readline() for line in f: if (line.split(",")[1]) in labels: print (line) If possible, could you tell me how to do this, please ? What is wrong with my code ? Thanks in advance !
downvote count: 1
possible better answer: http://stackoverflow.com/a/46780684
type: AnsweredQuestion
type: Question
has title: Searching rows of a file in another file and printing appropriate rows in python
answer count: 2
has comment: http://stackoverflow.com/comment/80507311
has answer: http://stackoverflow.com/a/46780828
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: read-write
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/46780684

http://stackoverflow.com/comment/80613057
score: 0
comment on: http://stackoverflow.com/a/46832514
type: Comment
type: AnswerComment
has text: @ryan9025 Done.

http://stackoverflow.com/comment/80718972
has text: `for entry in wordlist_2: found_difference = binary_search(sorted_list=wordlist_1, element=entry) if found_difference is False: matches.append(entry)` Does the trick, and returns a list of words not in the other list.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46885272
type: Comment

http://stackoverflow.com/a/46752779
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46752472
answers question: http://stackoverflow.com/q/46752472
type: Answer
has body: The primary reason your code is not working the way you expect is that the function returns as soon as any one of the skip_words are not in a line of text. You need help with fundamentals more than an answer to this question. Try pasting your code into pythontutor.com and watching execution line by line. Your code is not using (nor needing) an object-oriented approach. The self parameter is used when your function def is a method defined within a class. The fact that you never use self in your function definition is a sign that you proabably can just write a regular function definition, outside of a class definition. Remove the self parameter. You are not comparing lower case to lower case. Your code transforms the hard-coded list's items to lower case, but the text parameter remains with case as-is. Use lower case in your skip_words constant and call lower on the text passed to the function rather than calling lower on the constant. Python code is generally more readable if you iterate across list elements themselves. Use a variable to represent each element rather than a counter to access list elements. This would also eliminate the need for the if statement you use to check for existence of the first four lines. It's usually best to use only one return statement in a function. break will exit the for loop, and I think you intend continue which will skip the rest of the for loop and advance to the next iteration. def name_extractor(text): skip_words = ['curriculum', 'vitae', 'resume'] text_lines = text.split('\n') for line in text_lines[:4]: line_words = set(line.lower().split(' ')) if not line_words.intersection(skip_words): return line return ''

http://stackoverflow.com/a/46904875
downvote count: 1
type: Answer
has body: As jonsharpe mentioned, bcrypt is not in standard python library, but it can be easily installed and used in python 2.7 From terminal, just try sudo pip install bcrypt And you should be able to do import bcrypt without issue.
has comment: http://stackoverflow.com/comment/80756547
has comment: http://stackoverflow.com/comment/80756447
answers question: http://stackoverflow.com/q/46904783
score: 0
upvote count: 1

http://stackoverflow.com/a/46821533
downvote count: 0
has body: Yes, you can. MarkerCluster is what you're after Give this a whirl import folium from folium.plugins import MarkerCluster map1 = folium.Map(location=[80., -180], zoom_start=1) def color(magnitude): if magnitude&lt;6: col='green' elif [(magnitude&gt;6)&amp;(magnitude&lt;7.5)]: col='yellow' else: col='red' return col map1.add_child(MarkerCluster(locations=list(zip(earthquakes['Latitude'], earthquakes['Longitude'])), popups=earthquakes['Magnitude'].astype(str), icons=[color(m) for m in earthquakes['Magnitude']])) map1
accepted answer of: http://stackoverflow.com/q/46796795
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46796795
type: AcceptedAnswer

http://stackoverflow.com/a/46849429
upvote count: 11
has comment: http://stackoverflow.com/comment/80646625
has comment: http://stackoverflow.com/comment/80646534
has comment: http://stackoverflow.com/comment/80646495
has body: Sure, you need to explicitly set a default value to the serializer's related field: class MarketingPlanSerializer(serializers.ModelSerializer): promotion = serializers.CharField( source='fk_promotion.id', read_only=False, allow_null=True, default=None) class Meta: model = MarketingPlan fields = ('promotion',)
accepted answer of: http://stackoverflow.com/q/46849343
has comment: http://stackoverflow.com/comment/80646555
answers question: http://stackoverflow.com/q/46849343
has comment: http://stackoverflow.com/comment/80647002
has comment: http://stackoverflow.com/comment/80646261
score: 11
has comment: http://stackoverflow.com/comment/80662833
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80646753
has comment: http://stackoverflow.com/comment/80652557
type: Answer

http://stackoverflow.com/q/46779116
tagged with: lemmatization
answer count: 3
downvote count: 0
has body: I am trying to preprocess a string using lemmatizer and then remove the punctuation and digits. I am using the code below to do this. I am not getting any error but the text is not preprocessed appropriately. Only the stop words are removed but the lemmatizing does not work and punctuation and digits also remain. from nltk.stem import WordNetLemmatizer import string import nltk tweets = "This is a beautiful day16~. I am; working on an exercise45.^^^45 text34." lemmatizer = WordNetLemmatizer() tweets = lemmatizer.lemmatize(tweets) data=[] stop_words = set(nltk.corpus.stopwords.words('english')) words = nltk.word_tokenize(tweets) words = [i for i in words if i not in stop_words] data.append(' '.join(words)) corpus = " ".join(str(x) for x in data) p = string.punctuation d = string.digits table = str.maketrans(p, len(p) * " ") corpus.translate(table) table = str.maketrans(d, len(d) * " ") corpus.translate(table) print(corpus) The final output I get is: This beautiful day16~ . I ; working exercise45.^^^45 text34 . And expected output should look like: This beautiful day I work exercise text
favorite count: 0
accepted answer: http://stackoverflow.com/a/46779568
has comment: http://stackoverflow.com/comment/80504456
tagged with: python
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/46779486
has title: NLTK-based stemming and lemmatization
has answer: http://stackoverflow.com/a/46779486
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80504862
has answer: http://stackoverflow.com/a/46779568
tagged with: nltk
has answer: http://stackoverflow.com/a/61583928
tagged with: stemming

http://stackoverflow.com/a/46839211
answers question: http://stackoverflow.com/q/46838557
score: 2
downvote count: 0
has body: It's hard to tell from your question, but it sounds like you have a command line tool you run as my-tool &lt;function&gt; [options]. You could use importlib like this, avoiding most of the getattr calls: import importlib def run_function(name, args): module, function = name.rsplit('.', 1) module = importlib.import_module(module) function = getattr(module, function) function(*args) if __name__ == '__main__': # Elided: retrieve function name and args from command line run_function(name, args)
type: Answer
upvote count: 2

http://stackoverflow.com/a/46792604
has body: If you specify a From address it must correspond with your local machine. The sendmail handling function in the Mail Stub that google provides for its development server looks like: ... try: child.stdin.write(mime_message.as_string()) child.stdin.close() ... The problem is that the From address passed to the send_mail method is in mime_message headers. Adding the following line as the first line in the try block removes that header from the mime message. This allows sendmail to use a default From address: mime_message._headers = [x for x in mime_message._headers if x[0] != 'From'] The file with this function can be found at /path/to/google_cloud_sdk/platform/google_appengine/google/appengine/api/mail_stub.py
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46792603
type: Answer
accepted answer of: http://stackoverflow.com/q/46792603
score: 2
downvote count: 0

http://stackoverflow.com/q/46762582
has comment: http://stackoverflow.com/comment/80535987
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has body: The data: mydict = {'__weakref__': &lt;attribute '__weakref__' of 'Foo' objects&gt;,\ '__doc__': None, 'name': 'Guido'} I am attempting to make a copy: import copy copy_dict = copy.deepcopy(mydict) unexpected error reports: TypeError: can't pickle getset_descriptor objects if dict = {'name':'Guido'},it works &gt;&gt;&gt; copy.deepcopy(dict) {'name': 'Guido'} What's the problem?
answer count: 1
downvote count: 0
has title: How to copy a dictionary with a special value?
favorite count: 0
has answer: http://stackoverflow.com/a/46762610
has comment: http://stackoverflow.com/comment/80470701
tagged with: python

http://stackoverflow.com/a/75016078
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/133239113
has comment: http://stackoverflow.com/comment/137639852
answers question: http://stackoverflow.com/q/46840960
downvote count: 0
has body: You should be able to do wb.save("filename.xlsx") rather than use excelwriter at all. writer.save is an excelwriter method while openpyxl has its own save method that takes a filename after you opened a workbook. You can also use the wb.sheetnames and wb.create_sheet to navigate sheets. from openpyxl import Workbook, load_workbook from openpyxl.utils.dataframe import dataframe_to_rows wb = load_workbook(PATH + "yourfile.xlsx") #writer = pd.ExcelWriter(PATH + "yourfile.xlsx", engine='openpyxl') wb2 = [] if "MySheetName" in wb.sheetnames: wb2 = wb["MySheetName"] else: wb2 = wb.create_sheet("MySheetName",-1) #Auto add at the end #wb2 is now the active sheet for wb for r in dataframe_to_rows(df, index=True, header=True): wb2.append(r) wb.save(PATH + "yourfile.xlsx") Hope it helps
type: Answer

http://stackoverflow.com/a/46769350
type: Answer
accepted answer of: http://stackoverflow.com/q/46769280
score: 0
has body: you're not getting any result because of this line: ['grep','-i', '"rtp1-vif"'] this is passing "rtp1-vif" literally with quotes: no match. note that the whole piping process is overkill. No need to use cat as the first grep can take the file as input. And to go further, it's really easy to perform that task in pure python. Something like: with open("text.txt",'w') as op: file="rtp-gw1" for line in file: line = line.lower() if "rtp1-vif" in line and "fcid" in line: op.write(line) now your code can run on any platform, without the need to issue external commands. It's probably faster too.
answers question: http://stackoverflow.com/q/46769280
type: AcceptedAnswer

http://stackoverflow.com/comment/80539107
type: Comment
type: QuestionComment
has text: `biomes` imports `animals`, as shown in your code example. You also commented that `animals` imports another module which itself imports `biomes`. That's circular. (It doesn't matter that you're only importing a single function.)
comment on: http://stackoverflow.com/q/46796023
score: 0

http://stackoverflow.com/comment/80562840
score: 1
has text: I deleted my comment because I realized your solution gave me exactly what I needed.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46806997

http://stackoverflow.com/comment/80723286
score: 0
type: Comment
has text: Yes, maybe it is the designer's desired behaviour but not my algorithm expected.
type: AnswerComment
comment on: http://stackoverflow.com/a/46886348

http://stackoverflow.com/a/46852348
type: Answer
accepted answer of: http://stackoverflow.com/q/46852296
has body: Use filter In [4934]: df.groupby('Animal').filter(lambda x: 'brown' in x['couleur'].values) Out[4934]: Animal localisation couleur 0 dog France white 1 dog Japon brown Or In [4935]: df.groupby('Animal').filter(lambda x: x['couleur'].eq('brown').any()) Out[4935]: Animal localisation couleur 0 dog France white 1 dog Japon brown
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/46852296

http://stackoverflow.com/a/46901419
answers question: http://stackoverflow.com/q/46866862
has body: A group ID is a unique ID to each consumer. If you are subscribing to a same topic with multiple consumers, you must have different group ID's or else only one of those consumers will get the messages.
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/46870621
type: Question
tagged with: numpy
has body: My environment is Python 3.6 64bit with 64bit win 10 16GB ram. I have a ndarray with shape (260923,). I want to find index of all elements that's greater than a threshold. I am using this code but it gives a Memory error. And in the task manager, I can see all my ram used up. x_selected = x[:,x_attr] index_right = (x_selected &gt;thres).nonzero()[0] I have 16GB of ram and changed my PyCharm heap memory to 6GB and the problem persists. This is how the ndarray looks like in debugger. This is the complete error: what should I do to get all the index? Clarification: x is another ndarray with shape (260923,225). x_attr is just an integer. So "x_selected = x[:,x_attr]" is just selecting a column from x (2d array). This is how x looks like in debugger: The MemoreyError happens when I try to find the index (the codes I wrote above) And if I shrink the rows of x_selected, the code works. #This does NOT work index_left = (x_selected &lt;= thres).nonzero()[0] #This works however index_left = (x_selected[0:1000] &lt;= thres).nonzero()[0] #This does NOT work Error: "Comparing a sparse matrix with a scalar " #error: " raise NotImplementedError(" &gt;= and &lt;= don't work with 0.")" test = list(x[:,x_attr]) if test[1]&lt;=thres: a=1
accepted answer: http://stackoverflow.com/a/46871637
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/80689188
has comment: http://stackoverflow.com/comment/80688813
tagged with: python
has title: Finding all indices of elements satisfying a certain condition in a large matrix gives MemoryError
score: 2
has answer: http://stackoverflow.com/a/46871637
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80688656
has comment: http://stackoverflow.com/comment/80689176
has comment: http://stackoverflow.com/comment/80688596

http://stackoverflow.com/comment/80539157
comment on: http://stackoverflow.com/a/46794762
score: 0
type: Comment
has text: I see what you did with index_cols=0, but I basically want to make the x-axis index_rows=0. I know index_rows isnt valid but is there anyways to do that? I want the first row of the excel file to be my x-axis
type: AnswerComment

http://stackoverflow.com/comment/80880430
type: Comment
comment on: http://stackoverflow.com/q/46893080
has text: yea. it worked! thanks!
score: 0
type: QuestionComment

http://stackoverflow.com/q/46799261
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I am trying the create an eval_metric_op function that will display the proportion of exact matches at a given threshold for a multi-label classification problem. The following function returns 0 (no exact match) or 1 (exact match) based on the threshold given. def exact_match(y_true, y_logits, threshold): y_pred = np.round(y_logits-threshold+0.5) return int(np.array_equal(y_true, y_pred)) y_true = np.array([1,1,0]) y_logits = np.array([0.67, 0.9, 0.55]) print(exact_match(y_true, y_logits, 0.5)) print(exact_match(y_true, y_logits, 0.6)) A threshold of 0.5 yields a prediction of [1,1,1] which is incorrect so the function returns 0. A threshold of 0.6 yields a prediction of [1,1,0] which is correct so the function returns 1. I would like to turn this function into a tensorflow eval metric op -- can anybody advise the best way to do this? I can get to the same logic using tensorflow ops below, but I'm not entirely sure how to make this into a custom eval_metric_op: import tensorflow as tf def exact_match_fn(y_true, y_logits, threshold): #pred = tf.equal(tf.round(y_logits), tf.round(y_true)) predictions = tf.to_float(tf.greater_equal(y_logits, threshold)) pred_match = tf.equal(predictions, tf.round(y_true)) exact_match = tf.reduce_min(tf.to_float(pred_match)) return exact_match graph = tf.Graph() with graph.as_default(): y_true = tf.constant([1,1,0], dtype=tf.float32) y_logits = tf.constant([0.67,0.9,0.55], dtype=tf.float32) exact_match_50 = exact_match_fn(y_true, y_logits, 0.5) exact_match_60 = exact_match_fn(y_true, y_logits, 0.6) sess = tf.InteractiveSession(graph=graph) print(sess.run([exact_match_50, exact_match_60])) The above code will result in exact_match_50 of 0 (at least 1 prediction incorrect) and exact_match_60 of 1 (all labels correct). Is it sufficient to simply use tf.contrib.metrics.streaming_mean() or is there a better alternative? I would implement this as: tf.contrib.metrics.streaming_mean(exact_match(y_true, y_logits, threshold))
tagged with: google-cloud-ml-engine
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/46800986
has title: How to create an "exact match" eval_metric_op for TensorFlow?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46800986

http://stackoverflow.com/a/46854360
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
has body: Python's Counter should do the trick: from collections import Counter result = dict(Counter(word for word in words_split if word not in stopset))
score: 3
accepted answer of: http://stackoverflow.com/q/46854243
has comment: http://stackoverflow.com/comment/80656207
has comment: http://stackoverflow.com/comment/80669863
answers question: http://stackoverflow.com/q/46854243
has comment: http://stackoverflow.com/comment/80656264

http://stackoverflow.com/comment/80699469
score: 0
comment on: http://stackoverflow.com/q/46875777
has text: it worked. thanks @ArpitGoyal
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80525574
type: Comment
type: QuestionComment
has text: How can i do this? I am new here. How can i see the with Python kewword and looping techniques?
comment on: http://stackoverflow.com/q/46788611
score: 0

http://stackoverflow.com/q/46833644
accepted answer: http://stackoverflow.com/a/46833805
tagged with: azure
type: AnsweredQuestion
tagged with: jupyter
score: 1
has answer: http://stackoverflow.com/a/52154118
possible better answer: http://stackoverflow.com/a/46833768
favorite count: 0
has answer: http://stackoverflow.com/a/46833768
type: Question
upvote count: 1
tagged with: python
has title: Trouble defining user inputs in functions
answer count: 3
has body: I'm following the Microsoft introduction to Python course for beginners on edX, I'm having trouble in their second module where they ask you to create function that adds the "Doctor" title to a user inputted name. This is the advice they provide: Define function make_doctor() that takes a parameter name get user input for variable full_name call the function using full_name as argument print the return value create and call make_doctor() with full_name argument from user input - then print the return value This is what I have so far: def make_doctor(name): full_name = print("Doctor" + input().title()) return full_name print(name) Would appreciate any help.
has answer: http://stackoverflow.com/a/46833805
downvote count: 0

http://stackoverflow.com/q/46804954
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46823866
has body: I have this sample code for opencv in c++: flann::KDTreeIndexParams indexParams; flann::Index kdtree(Mat(cloud2d).reshape(1), indexParams); vector&lt;float&gt; query; query.push_back(370); query.push_back(464); vector&lt;int&gt; indices; vector&lt;float&gt; dists; kdtree.knnSearch(query, indices, dists, 3); how can I do the same in python ? Tried, but can't create kdtree or KDTreeIndexParams with cv2.
tagged with: kdtree
favorite count: 0
has comment: http://stackoverflow.com/comment/80594952
upvote count: 1
tagged with: python
tagged with: nearest-neighbor
tagged with: opencv
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/46823866
has title: knn search with opencv in python
tagged with: image-processing
type: Question

http://stackoverflow.com/a/46776422
answers question: http://stackoverflow.com/q/46772093
score: 0
has comment: http://stackoverflow.com/comment/80498864
has body: I'm sure there's a more succinct way to do this, but if you're alright doing a few merges, you can do it one step at a time: In [1]: df Out[1]: Id Date Value 0 1 2017-04-08 1 1 1 2017-04-08 1 2 1 2017-04-09 2 3 2 2017-04-08 3 4 2 2017-04-09 6 5 2 2017-04-09 4 6 3 2017-04-09 10 7 3 2017-04-09 11 8 3 2017-04-11 12 In [2]: min_dates = df.groupby('Id', as_index=False).Date.min() ...: df = pd.merge(df, min_dates, on='Id', suffixes=('', '_min')) ...: df['Date'] = ((df['Date'] - df['Date_min']) / pd.Timedelta('1 day')).apply(int) ...: df.groupby('Date').Value.sum() ...: Out[2]: Date 0 26 1 12 2 12 Name: Value, dtype: int64
type: Answer
has comment: http://stackoverflow.com/comment/80500116

http://stackoverflow.com/comment/80449900
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46751455
type: Comment
has text: Thank you for the answer. Additionally I was hoping to get rid of the old installation of python 3.5.2 => found help at http://www.onurguzel.com/uninstall-python-package-from-os-x/

http://stackoverflow.com/q/46755095
has comment: http://stackoverflow.com/comment/80455664
upvote count: 4
has comment: http://stackoverflow.com/comment/80456001
has body: Here I have a list a = [1, 2, 1, 4, 5, 7, 8, 4, 6] Now I want a following output but without for loop. Remove all the duplicate from the list. [2, 5, 7, 8, 6] output list contain only single occurrence number
has answer: http://stackoverflow.com/a/46755252
has answer: http://stackoverflow.com/a/72872548
has title: I want to remove duplicate from list (without for loop)
favorite count: 0
has answer: http://stackoverflow.com/a/46755123
score: -3
tagged with: python
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80455653
possible better answer: http://stackoverflow.com/a/46755128
downvote count: 7
type: Question
has answer: http://stackoverflow.com/a/46755128
accepted answer: http://stackoverflow.com/a/46755123

http://stackoverflow.com/q/46872034
type: Question
has comment: http://stackoverflow.com/comment/93955196
downvote count: 0
score: 4
tagged with: flask
favorite count: 0
has title: Google App engine deploy python project 502 bad gateway error
upvote count: 4
has body: I've created a virtualenv in GAE, and setup the Flask project When I execute "python3 main.py", the default route works fine, but when I execute "gcloud app deploy" and browse the page, 502 Bad Gateway shows. I try to find the error log by execute "gcloud app logs read" 2017-10-22 08:21:53 default[XXXXXXXXXX] "GET /" 502 2017-10-22 08:21:54 default[XXXXXXXXXX] "GET /favicon.ico" 502 Only these message is shown This is the app.yaml: runtime: python env: flex entrypoint: gunicorn -b :$PORT main:app runtime_config: python_version: 3
answer count: 0
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python

http://stackoverflow.com/comment/80734961
type: Comment
has text: this is the code i wrote as an exam, but for homework he wants us to write it up in pseudocode. it had to be a procedural program so while true loops is the one we had to do. i just need help in a few lines thats all. i understand everything i wrote its just the pseudocode im having trouble writing.
score: 0
comment on: http://stackoverflow.com/a/46891423
type: AnswerComment

http://stackoverflow.com/comment/80597777
comment on: http://stackoverflow.com/a/46820133
type: AnswerComment
score: 0
type: Comment
has text: thanks for this. The last command to create new_list complains about list index being out of range. I think this is because `temp_list` contains mostly empty elements. I can see that you wanted `temp_list` to pick up elements asis from `mylist` but this hasn't happened and I think this causes the error.

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/46833364
tags question: http://stackoverflow.com/q/46825656
tags question: http://stackoverflow.com/q/46800479
tags question: http://stackoverflow.com/q/46800257
tag name: c
tags question: http://stackoverflow.com/q/46815599
type: Tag
tags question: http://stackoverflow.com/q/46795446
tags question: http://stackoverflow.com/q/46778979
tags question: http://stackoverflow.com/q/46761159
tags question: http://stackoverflow.com/q/46881057
tags question: http://stackoverflow.com/q/46788470
tags question: http://stackoverflow.com/q/46805263
tags question: http://stackoverflow.com/q/46831085
tags question: http://stackoverflow.com/q/46796126
tags question: http://stackoverflow.com/q/46782505
tags question: http://stackoverflow.com/q/46780638
tags question: http://stackoverflow.com/q/46858668
tags question: http://stackoverflow.com/q/46808459

http://stackoverflow.com/comment/80515246
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46783395
has text: Gives me `DatetimeIndex([], dtype='datetime64[ns]', name='Date', freq='T')`
type: AnswerComment

http://stackoverflow.com/q/46879611
tagged with: postgresql
has comment: http://stackoverflow.com/comment/80742815
tagged with: python
has body: I have a PostgreSQL database in which I am collecting reports from 4 different producers. Back when I wrote this I defined 4 different schemas (one per producer) and since the reports are similar in structure each schema has exactly the same tables inside. I'd like to combine the schemas into one and add an extra column with the producer id to the tables. At the moment I have 4 python processes running - one per producer. A process collects a report and inserts it in the DB. My very simple code has been running without crashing for the past few months. The current design makes it impossible for 2 processes to want to insert data into the DB at the same time. If I made the DB changes (single schema with single table) several processes might want to insert data simultaneously. For the moment, I will exclude combining the processes into a single one, please assume I don't do this. I am unsure if I need to worry about any special code to handle the case of more than one process inserting data into the DB? I am using python3 + SQLAlchemy + Flask. I would imagine the ACID properties of a DB should automatically handle the case of 2 or more processes wanting to insert data simultaneously (data in report is small and insertion will take less than 1s). Can I combine the schemas without worrying about processes insert collisions?
has comment: http://stackoverflow.com/comment/80744828
score: 2
has answer: http://stackoverflow.com/a/46879647
upvote count: 2
type: AnsweredQuestion
has title: Can I safely combine my schemas
possible better answer: http://stackoverflow.com/a/46879648
has answer: http://stackoverflow.com/a/46879648
has comment: http://stackoverflow.com/comment/80706430
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/46879647
type: Question
has comment: http://stackoverflow.com/comment/80706457
answer count: 2
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0

http://stackoverflow.com/q/46859257
has comment: http://stackoverflow.com/comment/80666328
has comment: http://stackoverflow.com/comment/80666240
type: Question
answer count: 2
tagged with: random
score: 5
linked to: http://stackoverflow.com/q/12884428
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/46859315
has answer: http://stackoverflow.com/a/46861846
has answer: http://stackoverflow.com/a/46859315
tagged with: python
upvote count: 6
has title: Shuffle a long list an even longer number of times in Python
tagged with: montecarlo
downvote count: 1
accepted answer: http://stackoverflow.com/a/46861846
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80676147
has comment: http://stackoverflow.com/comment/80666190
tagged with: algorithm
has body: I want to shuffle a long sequence (say it is has more than 10000 elements)a lot of times (say 10000). When reading Python Random documentation, I found the following: Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator I have two groups (could be more) and each has many values. The sequence I want to shuffle is the list of all values available regardless of the group. My concern is that the note implies that the shuffle I need may not be provided by the random.shuffle() function. I have thought about some workarounds: Initialize the random number generator (with random.seed()) several in certain iterations. That way, it does not matter if the permutations are more than the period because different seeds will get different results. Use sample(range(length of sequence), k=size of a group) to get random indices an then use those to index within each group. That way I may not run out of permutations due to the period of the random number generator. Would any of my alternatives help? Thanks a lot!

http://stackoverflow.com/comment/80471054
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46761148
has text: Can you explain better? Do you mean for example using JSON or inside the web through forms?
score: 0

http://stackoverflow.com/comment/80639074
type: Comment
score: 2
has text: @cᴏʟᴅsᴘᴇᴇᴅ: Thanks. Updated
comment on: http://stackoverflow.com/a/46845731
type: AnswerComment

http://stackoverflow.com/comment/80720031
has text: so skill_metrics is '1.1.4' and matplotlib is '1.5.1'.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46886226

http://stackoverflow.com/a/46882029
accepted answer of: http://stackoverflow.com/q/46880930
score: 1
answers question: http://stackoverflow.com/q/46880930
has comment: http://stackoverflow.com/comment/80711528
has comment: http://stackoverflow.com/comment/80711493
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80711402
type: Answer
has body: np.sum((data_file==subset[0]).any(axis=1) &amp; (data_file==subset[1]).any(axis=1))

http://stackoverflow.com/a/46773664
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46758865
has body: Try not to use shell=True if you can avoid it. better to tokenize the command yourself to help sh. subprocess.call(["psql", "-U", "{user}", "-h", "{ip}", "-d", "{db}", "-w", "{pw}", "-c", "{copy statement}"]) In this case then your copy statement could be as it is passed to psql verbatim, because there are no shell quoting issues to take into account. (N.B. still have to quote this for python, so the string would remain as is). If you still want to use shell=True then you have to escape the string literal for both python and shell "\"\copy table (col1, col2) FROM file_location CSV HEADER QUOTE '\\\"' NULL ''\"" will create a string in python which will be "\copy table (col1, col2) FROM file_location CSV HEADER QUOTE '\"' NULL ''\" Which is what we found out we needed on our shell in the first place! Edit (clarifying something from the comments): subprocess.call, when not using shell=True, takes an iterable of arguments. So you could have psql_command = "\"\copy table (col1, col2) FROM file_location CSV HEADER QUOTE '\\\"' NULL ''\"" # user, hostname, password, dbname all defined elsewhere above. command = ["psql", "-U", user, "-h", hostname, "-d", dbname, "-w", password, "-c", psql_command, ] subprocess.call(command) See https://docs.python.org/2/library/subprocess.html#subprocess.call or https://docs.python.org/3/library/subprocess.html#subprocess.call extra edit :- Please note that to avoid shell injection, you should be using the method described here. See the warning section of https://docs.python.org/2/library/subprocess.html#frequently-used-arguments
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/80493437
score: 3
accepted answer of: http://stackoverflow.com/q/46758865
has comment: http://stackoverflow.com/comment/80493745

http://stackoverflow.com/comment/80749355
score: 0
type: Comment
has text: Thanks for the suggestions and response. In fact, the work in different processes do NOT need to talk to each other all i.e. once they access the shared list of data `shared_inputs`, everything inside unit of work is independent of others.
comment on: http://stackoverflow.com/a/46900727
type: AnswerComment

http://stackoverflow.com/q/46847282
has comment: http://stackoverflow.com/comment/80641984
downvote count: 0
has answer: http://stackoverflow.com/a/47216653
accepted answer: http://stackoverflow.com/a/47216653
score: 6
tagged with: django
type: Question
type: AnsweredQuestion
has body: Here's my template code for my comment queryset: {% block comments %} {% load el_pagination_tags %} {% paginate 10 comment_list %} {% for i in comment_list %} &lt;div class='comment_div'&gt; &lt;div class="left_comment_div"&gt; &lt;p&gt;{{ i.comment_text }}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; {% include 'comment/comments.html' with comment_list=i.replies.all %} &lt;/div&gt; {% endfor %} {% show_more %} {% endblock %} I'm using django el pagination to implement ajax pagination. On the 3rd line you can see I initially load 10 comments. With this package, comes a {% show_more %} element I can add which, when clicked, will load the rest of the comments. However, this {% show_more %}element disapears for some reason when I add {% include 'comment/comments.html' with comment_list=i.replies.all %}. For context, this include tag shows the replies for the current comment in the for loop. Does anyone have any idea why this include tag affects the {% show_more %} element? EDIT: Below is the relevent code for displaying show_more Github Source el_pagination_tags.py # show the template only if there is a next page if page.has_next(): print('Has next') #doesn't print request = context['request'] page_number = page.next_page_number() # Generate the querystring. querystring_key = data['querystring_key'] querystring = utils.get_querystring_for_page( request, page_number, querystring_key, default_number=data['default_number']) return { 'label': label, 'loading': loading, 'class_name': class_name, 'path': iri_to_uri(data['override_path'] or request.path), 'querystring': querystring, 'querystring_key': querystring_key, 'request': request, } # No next page, nothing to see. print('No next') #prints for every comment (e.g. 20 times when 20 comments) return {} Can I change something in the above code to possibly make it work, or atleast debug further to help me find more about the problem? Help appreciated.
has title: Element disappears when I add an {% include %} tag inside my for loop
has comment: http://stackoverflow.com/comment/80642269
possible better answer: http://stackoverflow.com/a/46847857
answer count: 3
has answer: http://stackoverflow.com/a/46847589
upvote count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/80642997
has answer: http://stackoverflow.com/a/46847857
tagged with: python

http://stackoverflow.com/comment/80682348
has text: Do you mind sending me a csv or a pickle? Pickle would be better. By send I mean something like sharing it on google drive...
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46867312

http://stackoverflow.com/q/46842279
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: &gt; import image &gt; import pytesseract as pya &gt; &gt; pya.tesseract_cmd = r'C:\Users\Euphz\Documents\Artworks\PSD\Speaking of Dogs\201710' &gt; print(pya.image_to_string(image.open('doggieville.png'))) Traceback (most recent call last): File "C:\PythonProjects\pytesseract.py", line 2, in import pytesseract as pya File "C:\PythonProjects\pytesseract.py", line 5, in print(pya.image_to_string(image.open('doggieville.png'))) AttributeError: module 'pytesseract' has no attribute 'image_to_string' Why is it happening???
tagged with: python-tesseract
score: 1
has answer: http://stackoverflow.com/a/50772830
has title: AttributeError: module 'pytesseract' has no attribute 'image_to_string'
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/46842296
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/80693139
type: Comment
has text: @Kris: `eval` should only be used as a last resort. The `globals()` dictionary gives you a direct mapping from a string value to the object. If all you have is a string name in the variable `name`, then `globals()[name]` gives you the object.
comment on: http://stackoverflow.com/a/46864922
type: AnswerComment
score: 0

http://stackoverflow.com/a/46867292
has comment: http://stackoverflow.com/comment/80682867
type: Answer
has body: You might be better off with a generator expression to avoid the list comprehension getting too big just to iterate over it once. Then you can append to list which is pretty cheap. l = [] for x in (np.linspace(start=min(a1[i],a2[i]), stop=max(a1[i],a2[i]), num=30).tolist() for i in range(len(a1))): l += x
has comment: http://stackoverflow.com/comment/80694342
has comment: http://stackoverflow.com/comment/80682701
has comment: http://stackoverflow.com/comment/80684915
has comment: http://stackoverflow.com/comment/80683148
score: 0
answers question: http://stackoverflow.com/q/46865573

http://stackoverflow.com/q/46856937
tagged with: kafka-python
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/46857016
has body: I have topic with 3 partitions and I'm trying to read from each specific partition using following code from kafka import KafkaConsumer, TopicPartition brokers = 'localhost:9092' topic = 'b3' m = KafkaConsumer(topic, bootstrap_servers=['localhost:9092']) par = TopicPartition(topic=topic, partition=1) m.assign(par) but I am getting this error: raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE) kafka.errors.IllegalStateError: IllegalStateError: You must choose only one way to configure your consumer: (1) subscribe to specific topics by name, (2) subscribe to topics matching a regex pattern, (3) assign itself specific topic-partitions. Can somebody help me with this?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Read from specific Kafka topic using Python
upvote count: 2
type: Question
tagged with: apache-kafka

http://stackoverflow.com/comment/80622725
score: 0
has text: Thanks for looking at it. Unfortunately, these were copied directly from a file that I tested before my original post. I’m running this in PyCharm, could that be the problem?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46834347

http://stackoverflow.com/comment/80551946
has text: Hey, just wanted to say thank you again. Found out I can use CalledErrorProcess and it does exactly what I need it to.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46801877

http://stackoverflow.com/q/46761495
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46761698
has comment: http://stackoverflow.com/comment/80468439
has comment: http://stackoverflow.com/comment/80468595
has title: Add the empty space in the string
has body: I am working on the code to input the numbers in the string self.EPG_DIGIT_NUMBER when I'm pressing on the keyboard number buttons. I would like to add the empty string like this in each time when I press on the keyboard number buttons. DIGIT_BUTTONS = range(58, 68) if action.getId() in DIGIT_BUTTONS: EPG_DIGIT_NUMBER = len(self.EPG_DIGIT) if EPG_DIGIT_NUMBER &lt;= 2: self.EPG_DIGIT_NUMBER += str(action.getId() - 58) self.EPG_DIGIT += 1 self.getControl(413).setLabel('[B]' + self.EPG_DIGIT_NUMBER + '[/B]') When I press on the keyboard numbers 1,0,3, it will show 103 in the string. What I want to achieve is when I press on the keyboard number buttons 1,0,3, I want to make the string to show something is like: 1 0 3. How I can do that?
has comment: http://stackoverflow.com/comment/80468449
has comment: http://stackoverflow.com/comment/80468304
possible better answer: http://stackoverflow.com/a/46761585
has comment: http://stackoverflow.com/comment/80468374
has answer: http://stackoverflow.com/a/46761585
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/80468628
has comment: http://stackoverflow.com/comment/80468386
favorite count: 0
has comment: http://stackoverflow.com/comment/80468538
has comment: http://stackoverflow.com/comment/80468467
has comment: http://stackoverflow.com/comment/80468504
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46761698

http://stackoverflow.com/comment/80636101
score: 0
comment on: http://stackoverflow.com/q/46832969
type: QuestionComment
type: Comment
has text: Since you have not tagged a specific language, you could try using the `read.fwf` function of R. It can handle something like this easily.

http://stackoverflow.com/q/46808877
has title: Python Socketserver client timeout
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80565545
answer count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
linked to: http://stackoverflow.com/q/34371096
has body: I have a socketserver in Python which has to handle multiple clients using the select.select method, as seen in the code below: import socket import select class Server: def __init__(self): self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(('localhost', 2000)) self.socket_list = [self.server] self.addresses = ['localhost'] self.commands = [""] self.running = True self.server.listen(10) def listen(self): while self.running: read, write, error = select.select(self.socket_list, [], self.socket_list, 0) for sock in read: if sock == self.server and self.running: try: conn, address = self.server.accept() conn.settimeout(30) self.socket_list.append(conn) self.addresses.append(address[0]) self.commands.append("") except: self.shutdown() break elif self.running: try: packet = sock.recv(60) if not packet: self.close_conn(sock) index = self.socket_list.index(sock) self.commands[index] += packet if '\n' in self.commands[index]: #handle command except: self.close_conn(sock) def close_conn(self, conn): #close client conn def shutdown(self): #shutdown server if __name__ == "__main__": Server().listen() The problem i currently have is that the client's connection should be closed after 30 seconds, but that doesn't happen, even though i declared that by using conn.settimeout(30). I haven't found any explanation yet as to why this happens. Note: comments were used to replace parts of the code that didn't mater to the problem.
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/a/67403469
answers question: http://stackoverflow.com/q/46884238
score: 0
type: Answer
has body: This worked for me: python setup.py py2app --packages=PyQt5

http://stackoverflow.com/comment/80559759
score: 1
has text: It is not Python that is designed this way. The Windows APIs themselves accept paths with forward slashes. Python just accommodates for that reality.
type: AnswerComment
comment on: http://stackoverflow.com/a/46805565
type: Comment

http://stackoverflow.com/comment/80491129
type: AnswerComment
score: 0
type: Comment
has text: Jezrael, I was examining my solution, and where mine differed with yours was that you had used `['var']` before `.unstack()`. Can you please explain the reasoning behind that? I don't understand this part.
comment on: http://stackoverflow.com/a/46771104

http://stackoverflow.com/comment/80634177
score: 0
type: Comment
type: QuestionComment
has text: So the second to last line: `print (c_df.dtypes)` doesn't print either? That's bizarre. I recommend using ipython/jupyter and the `%debug` magic function, that way you can step through these kind of errors.
comment on: http://stackoverflow.com/q/46843224

http://stackoverflow.com/q/46754144
tagged with: types
score: 2
has answer: http://stackoverflow.com/a/46754359
downvote count: 0
type: UnansweredQuestion
tagged with: python
has title: Most appropriate variable types to deal with coordinates in python
has body: I am writing python code that uses Cartesian methods and trigonometry to move, resize and rotate shapes on a plane, and to track and report these shenanigans. It will not be computationally intensive - typically a user-instruction would lead to a single move/rotate/resize operation. I would like to know what is the most appropriate variable type to use for the shape coordinate and dimension pairs, and why. The types I have considered are x = 10 y = -15 list_coords = [x, y] tuple_coords = (x, y) import numpy as np array_coords = np.array([x, y]) import cmath as cm complex_coords = x + j*y If you know of other good options, please also tell me about it. Thanks!
linked to: http://stackoverflow.com/q/626759
has answer: http://stackoverflow.com/a/46754536
tagged with: complex-numbers
tagged with: coordinates
type: Question
upvote count: 2
tagged with: numpy
answer count: 2
favorite count: 0

http://stackoverflow.com/comment/80556503
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46804696
has text: What is `xls_list`? `list`s have no `.add()` method.
score: 0

http://stackoverflow.com/comment/80645123
score: 0
comment on: http://stackoverflow.com/q/46848908
type: QuestionComment
type: Comment
has text: Ever heard of `pack`. I do not really see what numpy has to do with binary files.

http://stackoverflow.com/q/46819088
tagged with: python
accepted answer: http://stackoverflow.com/a/46820757
has body: I've referred to this question, but I don't quite understand the second method provided by Mr.mrry. overcome Graphdef cannot be larger than 2GB in tensorflow Basically, I'm trying to use tf's built in image transformation methods on images. I'm running into the error provided in the title. Also, do I need to keep creating a new session for each iteration? Currently, this process is a little slow and am not sure how to speed it up. import tensorflow as tf import os from scipy.ndimage import imread from scipy.misc import imresize, imshow import matplotlib.pyplot as plt for fish in Fishes: fish_images = os.listdir(os.path.join('C:\\Users\\Moondra\\Desktop\\Fishes', fish)) # get the image files os.makedirs(SAVE_DIR + fish, exist_ok = True) for num, fish_image in enumerate(fish_images): image =imread(os.path.join('C:\\Users\\Moondra\\Desktop\\Fishes', fish, fish_image)) new_img =tf.image.adjust_brightness(image, .4) #image transformation with tf.Session() as sess: new_image =sess.run(new_img) imsave(os.path.join(SAVE_DIR, fish, fish +str(num)+'.jpg'), new_image)
tagged with: tensorflow
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/46820757
score: 0
tagged with: deep-learning
answer count: 1
linked to: http://stackoverflow.com/q/36349049
has title: overcome Graphdef cannot be larger than 2GB in tensorflow -- Image transformations with tf

http://stackoverflow.com/comment/80567592
comment on: http://stackoverflow.com/q/46810255
type: Comment
type: QuestionComment
has text: maybe saving an array could be done as binary format instead, even if it's a bigger effort. have you an example of `array` (small one please?) I'm not sure of the type.
score: 0

parsing
tags question: http://stackoverflow.com/q/46805610
tags question: http://stackoverflow.com/q/46891300
tags question: http://stackoverflow.com/q/46800307
tags question: http://stackoverflow.com/q/46777128
tags question: http://stackoverflow.com/q/46792667
tag name: parsing
tags question: http://stackoverflow.com/q/46761691
tags question: http://stackoverflow.com/q/46808322
tags question: http://stackoverflow.com/q/46768151
tags question: http://stackoverflow.com/q/46750834
tags question: http://stackoverflow.com/q/46834364
tags question: http://stackoverflow.com/q/46768870
tags question: http://stackoverflow.com/q/46869581
tags question: http://stackoverflow.com/q/46771437
tags question: http://stackoverflow.com/q/46801252
tags question: http://stackoverflow.com/q/46855255
tags question: http://stackoverflow.com/q/46759956
type: Tag
tags question: http://stackoverflow.com/q/46774868
tags question: http://stackoverflow.com/q/46865983
tags question: http://stackoverflow.com/q/46839909
tags question: http://stackoverflow.com/q/46806711
tags question: http://stackoverflow.com/q/46866327
tags question: http://stackoverflow.com/q/46901178

http://stackoverflow.com/comment/80589566
type: Comment
has text: Your answer is very helpful and appreciated.
comment on: http://stackoverflow.com/a/46820924
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80531804
has text: Congratulations, you just reinvented the builtin `zip()` function <g>
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46792333

http://stackoverflow.com/a/46777729
upvote count: 1
downvote count: 0
has body: You can simply do this &gt;&gt;&gt; def get_status(user_id, date): for rec in RECORDS: if rec['user_id'] == user_id and rec['created_at'] == date: return rec['status'] &gt;&gt;&gt; get_status(1, '2017-01-01T10:00:00') 'paying' &gt;&gt;&gt;
type: Answer
score: 1
answers question: http://stackoverflow.com/q/46777349

http://stackoverflow.com/comment/80614881
comment on: http://stackoverflow.com/a/46832462
score: 0
type: Comment
has text: so you made encoding="cp437" is it ?
type: AnswerComment

http://stackoverflow.com/q/46759151
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46759582
score: 1
upvote count: 1
tagged with: machine-learning
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/46759582
has body: I'm experimenting with TensorFlow (which seems amazing so far!) and I'm playing around with a toy example a 1 class classification problem. I'm generating some features and if the first feature is above a threshold then the example is "positive" Full code here: https://gist.github.com/tnbredillet/f136c2bc40815517e0aa1139bd2060ee The problem is that it seems that the model is unable to capture that simple relationship. Of course I'm missing a lot of stuff (CV, regularization, batch normalization, hyperparameter tuning) to name a few. But still I would expect the model to manage to figure that one out right ? Maybe there's simply a bug in my code? Would welcome any insights :-) EDIT: Data generating code: num_examples = 100000 split = 0.2 num_features = 1 def generate_input_data(num_examples, num_features): features = [] labels = [] for i in xrange(num_examples): features.append(np.random.rand(num_features) * np.random.randint(1, 10) + np.random.rand(num_features)) if np.random.randint(101) &gt; 90: features[i-1][np.random.randint(num_features)] = 0 hard = ceil(np.sum(features[i-1])) % 2 easy = 0 if features[i-1][0] &gt; 3: easy = 1 labels.append(easy) df = pd.concat( [ pd.DataFrame(features), pd.Series(labels).rename('labels') ], axis=1, ) return df def one_hot_encoding(train_df): #TODO: handle categorical feature one hot encoding. return 0, 0 def scale_data(train_df, test_df): categorical_columns, encoding = one_hot_encoding(train_df) scaler = MinMaxScaler(feature_range=(0,1)) scaler.fit(train_df.drop(['labels'], axis=1)) train_df = pd.concat( [ pd.DataFrame(scaler.transform(train_df.drop('labels', axis=1))), train_df['labels'] ], axis=1, ) test_df = pd.concat( [ pd.DataFrame(scaler.transform(test_df.drop('labels', axis=1))), test_df['labels'] ], axis=1, ) return train_df, test_df def preprocess_data(train_df, test_df): all_dfs = [train_df, test_df] features = set() for df in all_dfs: features |= set(df.columns) for df in all_dfs: for f in features: if f not in df.c…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has title: Neural network can't seem to learn a simple relationship TensorFlow

http://stackoverflow.com/q/46838487
has comment: http://stackoverflow.com/comment/80624863
favorite count: 0
has answer: http://stackoverflow.com/a/46839279
has answer: http://stackoverflow.com/a/46839182
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/80626171
has comment: http://stackoverflow.com/comment/80624797
has comment: http://stackoverflow.com/comment/80625953
has comment: http://stackoverflow.com/comment/80624774
answer count: 4
has comment: http://stackoverflow.com/comment/80626149
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/46838777
has comment: http://stackoverflow.com/comment/80624926
has comment: http://stackoverflow.com/comment/80624942
type: Question
linked to: http://stackoverflow.com/q/46820152
has comment: http://stackoverflow.com/comment/80625890
has comment: http://stackoverflow.com/comment/80625941
has answer: http://stackoverflow.com/a/46839418
has comment: http://stackoverflow.com/comment/80625981
accepted answer: http://stackoverflow.com/a/46839418
possible better answer: http://stackoverflow.com/a/46838777
has body: Given two lists with suffixes: l1 = ['C_1', 'B_1', 'A'] l2 = ['B_2', 'C_2', 'D'] I want to combine them like this: ['C_1', 'C_2', 'B_1', 'B_2', 'A', 'D'] Elements are to be combined with l1 as the anchor. This means, if C_* comes before B_* in l1, the same ordering will be preserved in the output. Furthermore, elements with the same prefix C_* will be grouped together, in increasing order of suffix. Elements with a suffix are placed in the order in which they appear, as you see above. You can assume that all elements in l1 have suffix _1, and all elements in l2 have suffix _2. I've tried this: from collections import OrderedDict from itertools import chain o = OrderedDict() for x in l1 + l2: o.setdefault(x.split('_')[0], []).append(x) result = list(chain.from_iterable(o.values())) Which works, but was wondering if there were any more succinct ways of doing this. Edit: The suffix is just a stand in for which list that element appears in. Say I have C_1 from l1, and C_2 from l2, then C_* elements appear based on which was in l1 and which was in l2, in the final list (so, it'd be ... C_1, C_2...). Furthermore, all elements in l1 and l2 are unique wrt each other and themselves. Hope that helps.
has title: Combine list elements by suffix
downvote count: 1

http://stackoverflow.com/comment/80650847
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46851689
has text: Try adding `allow_soft_placement = True` to `ConfigProto`'s argument list
score: 0

http://stackoverflow.com/comment/134703882
comment on: http://stackoverflow.com/a/46757067
type: Comment
has text: just wanted point out how TERRIBLE DRF documentation was when you posted this comment, and how terrible still is today 6 years later. The "ManyToManyFields with a Through Model" is a 4 lines paragraph with not a single example. Deplorable
score: 1
type: AnswerComment

google-apps-script
tags question: http://stackoverflow.com/q/46792942
tags question: http://stackoverflow.com/q/46773093
type: Tag
tag name: google-apps-script

http://stackoverflow.com/comment/80615767
comment on: http://stackoverflow.com/a/46832956
score: 0
type: AnswerComment
type: Comment
has text: Thank you for all this information! I've already accepted your answer. However, if you feel like you want to and you have the time, would you be able to implement some of those mechanisms in the TensorFlow code? I know very little about NN in general, so I am not sure I know what you mean by built-in normalizing mechanisms. If you don't have the time, don't worry!

http://stackoverflow.com/q/46886937
linked to: http://stackoverflow.com/q/11951546
tagged with: python
type: AnsweredQuestion
has title: SVN SSL Certificate Untrusted via Python Script
tagged with: svn
type: Question
tagged with: ssl
tagged with: python-2.7
has body: I have a strange scenario going on at the moment. When I issue an svn info TXN REPO command on our build server (separate from the SVN server), it works as expected and displays the relevant information to the console. However when I script it using Python, and specifically, Popen from the subprocess module, it prints a message svn: E230001: Server SSL certificate untrusted to the standard error (console). What I've tried: Using --non-interactive and --trust-server-cert flags within the script call. Passing a username/password within the svn info call via the script. The above two don't seem to take effect, and the same error as above is spat out. However, manually running the same command from the command prompt succeeds with no problems. I assume it might be something to do with python opening up a new session to the SVN server, and that session isn't a "trusted" connection? But I can't be sure. Our SVN server is on a windows machine and is version 1.8.0 Our build server is a windows machine running Jenkins version 2.84. Jenkins executes a batch script which kicks off the Python script, performing the above task. Command: svn_session = Popen("svn info --non-interactive --trust-server-cert --no-auth-cache -r %s %s" % (TXN, REPOS), stdout=PIPE, stderr=PIPE, shell=True) ** Edit ** When I copy and paste the python line from the script into the interactive python shell on the same server, the command works as expected also. So the issue is how the script is executing the command, rather than the command itself or how Python runs that command. ** Has anyone come across this before?
score: 0
has answer: http://stackoverflow.com/a/46913533
accepted answer: http://stackoverflow.com/a/46913533
answer count: 1

http://stackoverflow.com/a/46892341
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/46892046
accepted answer of: http://stackoverflow.com/q/46892046
has comment: http://stackoverflow.com/comment/80732087
type: AcceptedAnswer
downvote count: 0
has body: Your scale column must be a categorical dtype. After filtering, you need to call remove_unused_categories(): df = df[['scale'] == 'weak'] df.scale.cat.remove_unused_categories(inplace=True)
type: Answer

http://stackoverflow.com/a/46827602
score: 1
upvote count: 1
has body: Can you use Pool.apply_async() instead of Pool.map()? Apply_async does not block and would allow your main program to keep processing for more rows. It also does not require your main program to have all the data ready to be mapped. You would just pass one chunk as a parameter to apply_async().
answers question: http://stackoverflow.com/q/46827515
downvote count: 0
type: Answer

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/46802931
tags question: http://stackoverflow.com/q/46767114
tags question: http://stackoverflow.com/q/46758107
tags question: http://stackoverflow.com/q/46756434
tags question: http://stackoverflow.com/q/46777910
tags question: http://stackoverflow.com/q/46872527

http://stackoverflow.com/q/46816894
tagged with: keras
score: 4
has comment: http://stackoverflow.com/comment/80581211
has comment: http://stackoverflow.com/comment/80582077
has body: I'm running a keras model for binary classification on two separate computers; the first is running python 2.7.5 with Tensorflow 1.0.1 and keras 2.0.2 and cpu computations; the second is running python 2.7.5 with Tensorflow 1.2.1 and keras 2.0.6 and uses the gpu. My model is modified from the siamese network model at https://gist.github.com/mmmikael/0a3d4fae965bdbec1f9d. I added regularization (activity_regularizer=keras.regularizers.l1 in the Dense layers), but for everything else I'm using the same structure as the mnist example. I use the exact same code and training data on both computers, but the first one gives me a classification accuracy 86% and recall 88% on the test set, and the other gives me accuracy 52% and recall 100% (it classifies every test sample as "positive"). These results are reproducible with separate initializations. I'm not even sure where to start looking for why the performance is so vastly different. I've been reading through the keras/tensorflow release notes to see if any of the changes pertain to something in my model, but I don't see anything that looks helpful. It doesn't make sense that a version change in tensorflow/keras would cause that much of a difference in the performance. Any sort of help figuring this out would be greatly appreciated.
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: Keras model behaves very differently between two computers
has comment: http://stackoverflow.com/comment/124012651
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/80649875
downvote count: 0

http://stackoverflow.com/q/46774551
has body: I'm trying to plot a rectangle with python. Something is going wrong, but I can't figure out what. Here's the code: import matplotlib.pyplot as plt import matplotlib.patches as patches box=[1,3,5] box_pos=[0,30,4] fig, ax = plt.subplots() ax.add_patch( patches.Rectangle( (box_pos[0], box_pos[1]), # (x,y) box[0], # width box[1], # height ) ) ax.set_aspect(aspect='equal', adjustable='box') plt.show() Do you have any idea what I could do to fix it?
type: UnansweredQuestion
downvote count: 2
type: Question
score: -2
tagged with: matplotlib
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80495195
favorite count: 0
has title: python matplotlib patch plot going wrong
tagged with: python
has answer: http://stackoverflow.com/a/46788139

http://stackoverflow.com/comment/80457236
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46755940
has text: @EdvardHaugland Do keep in mind however, that the extraction will be `O(1)` because you know exactly where it is.
type: Comment

http://stackoverflow.com/q/46752253
upvote count: 3
has answer: http://stackoverflow.com/a/46815873
type: Question
answer count: 2
tagged with: group-by
downvote count: 0
tagged with: pandas
favorite count: 0
has body: I want to do something that seems pretty easy in a spreadsheet but I can't figure the syntax in pandas. I have a data set that can be grouped. I want to determine the aggregate stats for each of the groups, but then use the aggregates to create a new column back in the original data frame. For example, if my data frame looks like this: d = pandas.dataframe({'class', : ['f1', 'f2', 'f3', 'f1'], 'user': ['jack', 'jen', 'joe', 'jan'], 'screen': [12, 23, 13, 15] }) yes its much smaller than my data set I would like to do something like d['gp'] = d['screen'].apply(d.groupby('class').stdev()) and assure that the d.groupby().stdev() is actually the stdev for that class for the row. In other words I don't want the stdev for class f1 to be used when calculating the gp for class f2, etc. My brain is thinking in spreadsheet mode, or in a python for loop. I know there must be a simple pandas syntax to do this -- but so far I haven't found anything in my searches that seem to fit my use case.
type: UnansweredQuestion
tagged with: python
has title: Using Pandas to apply a groupby aggregate to the original data frame
score: 3
has answer: http://stackoverflow.com/a/46752260

http://stackoverflow.com/q/46881358
type: UnansweredQuestion
tagged with: sql-server
type: Question
has title: Capture STATISTICS IO output from ADODBAPI in Python
tagged with: adodbapi
tagged with: python
has body: I have the following demonstration code that works just fine but I want to capture the output of STATISTICS IO. I cannot find the proper way to capture this. import adodbapi server = 'MYCOMPUTER\SQLEXPRESS' database = 'mytest' connString = 'Provider=SQLOLEDB;Server=' + server + ';Database=' + database + ';Integrated Security=SSPI;' print(connString) myConn = adodbapi.connect(connString) cursor = myConn.cursor() cursor.execute('SET STATISTICS IO ON; SELECT * FROM dbo.mytab') results = cursor.fetchall() for i in results: print("First value: {} and Second value: {}".format(i[0],i[1])) I tried this code which is a is pulled from a another stackoverflow answer with no success: import adodbapi import win32com import pythoncom ##from win32com.client import gencache ##gencache.EnsureModule('{2A75196C-D9EB-4129-B803-931327F72D5C}', 0, 2, 8) defaultNamedOptArg=pythoncom.Empty defaultNamedNotOptArg=pythoncom.Empty defaultUnnamedArg=pythoncom.Empty class events(): def OnInfoMessage(self, pError, adStatus, pConnection): print('Info Message') a = pError.QueryInterface(pythoncom.IID_IDispatch) a = win32com.client.Dispatch(a) print(a.Description) print(a.Number) print(a.Source) #print 'B', adStatus c = pConnection.QueryInterface(pythoncom.IID_IDispatch) c = win32com.client.Dispatch(c) print(c.Errors.Count) print(c.Errors.Item(0).Description) print(c.Errors.Clear()) print('c', adStatus) if __name__ == '__main__': server = 'mybox\SQLEXPRESS' database = 'mytest' username = 'testusr' password = 'password' connString = 'Provider=SQLOLEDB;Server=' + server + ';Database=' + database + ';Integrated Security=SSPI;' print(connString) myConn = win32com.client.DispatchWithEvents("ADODB.Connection", events) myConn.ConnectionString = connString myConn.Open() con = adodbapi.cursor(myConn) cursor = con.cursor() cursor.execute('SET STATISTICS IO ON; SELECT * FROM dbo.mytab') results = cursor.fetchall() for i in results: print("First value: {} and Second value: {}".format(i[0],i[1])) I get this erro…
score: 0
has comment: http://stackoverflow.com/comment/81001938
has comment: http://stackoverflow.com/comment/80717960
answer count: 0

http://stackoverflow.com/a/46786570
type: Answer
upvote count: 6
score: 6
has body: The worst case running time of quick sort is O(n^2). The worst case depends on pivot selection strategy, usually it occurs for a already sorted array (which your array is). Also, for small data set, bubble sort or other simple sorting algorithm usually works faster than more complex algorithms. The reason is, for each iteration, simple algorithms does less calculation than complex algorithms. For example, say bubble sort takes 3ms per iteration while quicksort takes 20ms. So for an array with 10 items. In this case bubble sort takes 10*10*3 = 300ms. And quicksort takes 10*log2(10)*20 = 664ms. (Considering the average case) So bubble sort is faster here. But as we take larger dataset, quicksort becomes increasingly efficient due to lower run-time complexity.
answers question: http://stackoverflow.com/q/46786327
downvote count: 0

http://stackoverflow.com/q/46878575
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46878888
type: Question
tagged with: html-table
has title: Open url when certain conditions are met
has body: I am a newbie in Python. I am building a web scraping tool that could open a URL in an HTML cell after criteria have been fulfilled. Any kind of help would be useful. Thanks! This is the HMTL code that I am working on: A2 16% I want to open the URL in data-href if the value in div class="inline-block" is greater than 16%. I am aware that I have to convert the percentage into a floating number first in order to do that. The thing that I want to know is just how to open the URL. I am using selenium and beautifulsoup until now to build by script. This is a snapshot of how I built my project. chromedriver = 'C:\\chromedriver.exe' browser = webdriver.Chrome(chromedriver) .... html = browser.page_source soup = BeautifulSoup(html, "lxml") tags = soup('td') urllist = list() for tag in tags: z = tag.get('data-href','abcde') if z not in urllist: urllist.append(z)
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/80577240
has text: @NynkeLys To run the code, title and content have to be string. :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46814676

http://stackoverflow.com/a/46906443
answers question: http://stackoverflow.com/q/46904273
type: Answer
has comment: http://stackoverflow.com/comment/80791914
has comment: http://stackoverflow.com/comment/80792038
has comment: http://stackoverflow.com/comment/80760233
has body: ''' Created on 2017年10月24日 @author: leemengwei ''' from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column,Integer,String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Anwendung(Base): __tablename__ = 'tab1' id = Column(Integer, primary_key=True) name = Column(String) def delete_anw(): session = Session() f = session.query(Anwendung).filter_by(name="Max").delete() print('records deleted:',f) session.commit() session.close() def query_anw(): session = Session() f = session.query(Anwendung).filter_by(name="Max").all() print('records matched:',len(f)) session.close() if __name__=='__main__': engine = create_engine("mysql+pymysql://root@localhost/test",echo=True) Session = sessionmaker(bind=engine) query_anw() delete_anw() query_anw() The code above works fine for me.The records are found and deleted.
score: -1
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/80656968
comment on: http://stackoverflow.com/q/46854753
has text: you can use caching. Redis/Memcache.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80708020
type: Comment
has text: Only `root` can use ports under 1024
type: QuestionComment
comment on: http://stackoverflow.com/q/46880362
score: 0

http://stackoverflow.com/a/46750392
answers question: http://stackoverflow.com/q/46750355
type: Answer
accepted answer of: http://stackoverflow.com/q/46750355
score: 2
upvote count: 2
has body: Have a look at the code here: def _init_coef(self, fan_in, fan_out): if self.activation == 'logistic': # Use the initialization method recommended by # Glorot et al. init_bound = np.sqrt(2. / (fan_in + fan_out)) elif self.activation in ('identity', 'tanh', 'relu'): init_bound = np.sqrt(6. / (fan_in + fan_out)) else: # this was caught earlier, just to make sure raise ValueError("Unknown activation function %s" % self.activation) coef_init = self._random_state.uniform(-init_bound, init_bound, (fan_in, fan_out)) intercept_init = self._random_state.uniform(-init_bound, init_bound, fan_out) return coef_init, intercept_init The mentioned method is described in the paper: Glorot, X. &amp; Bengio, Y.. (2010). Understanding the difficulty of training deep feedforward neural networks. Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics, in PMLR 9:249-256
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/46878258
answers question: http://stackoverflow.com/q/46878153
has comment: http://stackoverflow.com/comment/80706038
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/80703743
has body: Your should loop over your iterable, producing the arrays one by one. That is, do something like def interpolation(xs, paths): iterable = read_data_from_disc(paths) splines = [interpolator(xs, array, axis=0) for array in iterable] return splines Now the interpolation function will return a list of all the splines, which is what I suspect is your intent with your example code. If the interpolator function does not store the array data after the creation of the spline object, you will have completed your goal of not keeping all the arrays in memory simultaneously.
has comment: http://stackoverflow.com/comment/80708338

http://stackoverflow.com/comment/80582869
comment on: http://stackoverflow.com/q/46815492
type: Comment
type: QuestionComment
has text: some times opencv don't destroy the window so i m using in loop.... to get into safe side
score: 0

http://stackoverflow.com/q/46866525
answer count: 1
accepted answer: http://stackoverflow.com/a/46868162
has title: unable to remove stopwords;NLP
favorite count: 0
tagged with: multiclass-classification
has comment: http://stackoverflow.com/comment/80683495
tagged with: python
tagged with: nlp
tagged with: stop-words
has comment: http://stackoverflow.com/comment/80682122
type: AnsweredQuestion
upvote count: 2
score: 1
has body: I have csv file which contains 2 column 'Complaint Details' and 'DispositionCode'.I want to classify the complaintDetails into 8 different classes of dispostionCode such as 'Door locked from inside','Vendor error','Missing key or lock'... The dataset is shown in the image. enter image description here What would be good method to classify and find accuracy. Initially I am trying with removing stopwords from the ComplaintDetails and then use naivebayes classifier The code is as follows: import csv from nltk.corpus import stopwords from nltk.tokenize import word_tokenize your_list=[] with open('H:/Project/rash.csv', 'r') as f: reader = csv.reader(f) your_list = list(reader) print(your_list) stop_words=set(stopwords.words("english")) words= word_tokenize(your_list) filteredSent=[] for w in words: if w not in stop_words: filteredSent.append() print(filteredSent) But I am getting following error:- for match in self._lang_vars.period_context_re().finditer(text): TypeError: expected string or bytes-like object
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46868162
tagged with: nltk

http://stackoverflow.com/comment/80504187
type: QuestionComment
has text: I posted the wrong code. sorry for that. the call for shell() was pure desperation; in desperation i tested to open a shell by just calling the function shell(); this also gives me a user shell only, even if the binary's owner is root and has the s flag set. in the current seen code the function vuln() contains the vulnerability.
score: 0
comment on: http://stackoverflow.com/q/46778979
type: Comment

http://stackoverflow.com/comment/80688662
type: QuestionComment
has text: Well in that case, have a look at this answer: https://stackoverflow.com/a/17292194/4822566
comment on: http://stackoverflow.com/q/46859511
score: 0
type: Comment

http://stackoverflow.com/a/46918644
score: 4
type: AcceptedAnswer
has body: Couldn't have figured this out without Martineau! Posting answer in case anyone has a similar (seemingly) mysterious error. First, I logged the error, as Martineau suggested: import logging logging.basicConfig(filename='C:/MyLog.log',level=logging.DEBUG) try: [all my code] except Exception as e: logging.info(e) This recorded the error: "charmap' codec can't encode character '\u2013' in position 448: character maps to undefined". For some reason that's beyond my pay grade, IDLE and python.exe (in Python 3.4) don't handle encoding in the same way. That was causing the problem (and only when special characters were appearing, which is why it didn't break down every time). I looked for the solution to the encoding problem and found it here. Basically, I upgraded from Python 3.4 to Python 3.6, and the encoding problem disappeared.
type: Answer
accepted answer of: http://stackoverflow.com/q/46866268
upvote count: 4
answers question: http://stackoverflow.com/q/46866268
downvote count: 0

http://stackoverflow.com/comment/80700607
comment on: http://stackoverflow.com/a/46856186
has text: Connect vs emit are 2 complementary things, when you use connect is to create the connection between the signal and the slot, instead when the signal executes emit you are telling the PyQt that you have to call all the slots that were previously connected to the signal. Therefore there is no versus between connect and emit.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/46770281
upvote count: 1
answers question: http://stackoverflow.com/q/46770171
downvote count: 0
type: Answer
has body: Try this: result = {} for i in dict1: result[i['date']] = result.setdefault(i["date"], 0) + i["cost"]
score: 1

http://stackoverflow.com/a/46903686
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46903330
has body: Along the lines of @juanpa.arrivillaga lookup version 1 df1.stack().pipe( lambda x: pd.Series( df2.lookup(x.index.get_level_values(0), x.values), x.index )).unstack() col1 col2 Day0 1.0 NaN Day1 7.0 6.0 Day2 10.0 5.0 lookup version 2 df1.apply( lambda y: ( lambda x: pd.Series( df2.lookup(x.index, x.values), x.index ))(y.dropna())) col1 col2 Day0 1 NaN Day1 7 6.0 Day2 10 5.0 Comprehension pd.DataFrame({ c: { r: df2.stack().get((r, v), None) for r, v in df1[c].items() } for c in df1 }) col1 col2 Day0 1 NaN Day1 7 6.0 Day2 10 5.0
type: Answer

http://stackoverflow.com/q/46826501
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/46833211
has body: I am fairly new to Django and REST APIs in general. I am exposing a data import URL using Django REST framework i.e. /api/data/import. I currently have an associated APIView that implements a POST method, but returns 405 - Bad Request on a GET as that is the default framework behaviour when GET has not been explicitly implemented. This MDN article strongly suggests GET should always be implemented, so should I just return an empty 200 response? This also smells a little bit like I am using REST incorrectly. Thanks
has comment: http://stackoverflow.com/comment/80602850
score: 0
has comment: http://stackoverflow.com/comment/80602771
answer count: 1
has comment: http://stackoverflow.com/comment/80600939
tagged with: django-rest-framework
tagged with: rest
has answer: http://stackoverflow.com/a/46833211
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80603572
has title: In Django REST API, should a POST only APIView define a GET method?

http://stackoverflow.com/comment/80538012
type: AnswerComment
comment on: http://stackoverflow.com/a/46795581
type: Comment
has text: It says to use "the file object input", but the only method that returns a file object is `open()`
score: 0

http://stackoverflow.com/q/46873911
has title: Python OpenCV imwrite 0 bytes image depends on execution dir
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/46874011
score: 0
has body: I have written a small script to convert a RGB image to grey. When I run the script in terminal form current dir (python3 image.py), it works perfectly fine. But when I rum it from a dir lower like python3 proc/image.py it creates a result image with 0 bytes size. here is the code of image.py import os import numpy as np import cv2 def sw(name): dir_path = os.path.dirname(os.path.realpath(__file__)) img_path = os.path.join(dir_path, name) print(img_path) img = cv2.imread(name, 0) rslt_path = os.path.join(dir_path, "schwarn_g.jpeg") print(rslt_path) cv2.imwrite(rslt_path, img) return img if __name__ == "__main__": sw('schwarn.jpeg') Can somebody explain this behavior? Thanks a lot!
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/46874011
tagged with: python

http://stackoverflow.com/q/46879491
type: AnsweredQuestion
score: 1
tagged with: image
tagged with: coordinates
has title: pygame issue with placing the image on screen
downvote count: 0
answer count: 1
favorite count: 0
tagged with: position
has answer: http://stackoverflow.com/a/46879574
accepted answer: http://stackoverflow.com/a/46879574
tagged with: python
tagged with: pygame
upvote count: 1
has body: Im doing a book course where I have to place an image of alien ship in the top left corner. I followed the guidance used the same code but my image is placed too low. I can not figure out what is the source of the problem , I'm using transparent png image. Here is the code I have for Alien , Settings and main classes.Many thanks for assistance. Alien class: import pygame from pygame.sprite import Sprite class Alien(Sprite): """A class to represent a single alien in the fleet.""" def __init__(self, ai_settings, screen): """Initialize the alien and set its starting position.""" super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings # Load the alien image and set its rect attribute. self.image = pygame.image.load('Images/alien.png') self.rect = self.image.get_rect() # Start each new alien near the top left of the screen. self.rect.x = self.rect.width self.rect.y = self.rect.height # Store the alien's exact position. self.x = float(self.rect.x) def blitme(self): """Draw the alien at its current location.""" self.screen.blit(self.image, self.rect) Settings class: class Settings(): """A class to store all settings for Alien Invasion.""" def __init__(self): """Initialize the game's settings.""" # Screen settings self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) #Ship setting self.ship_speed_factor = 1.5 # Bullet settings self.bullet_speed_factor =1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60 ,60, 60 self.bullets_allowed = 3 main class: from settings import Settings import pygame from ship import Ship from alien import Alien from pygame.sprite import Group import game_functions as gf def run_game(): # Initialize game and create a screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make a ship ship = Ship( ai_settings, screen) # Make a group to store bullets…
type: Question

http://stackoverflow.com/q/46872471
tagged with: dataset
linked to: http://stackoverflow.com/q/14313510
downvote count: 1
has body: I have a dataset and I want to enrich it. I need to calculate some new dataset column which is some function of previous N rows of another column. As an example, given I want to calculate binary column which shows if current day temperature is higher than average in previous N days. At the moment I just iterate through all the pandas dataset values using df.iterrows() and do appropriate calculations. This takes some time. Is there any better option?
favorite count: 0
tagged with: pandas
has title: Numpy, Pandas: what is the fastest way to calculate dataset row value basing on previous N values?
tagged with: python
type: Question
possible better answer: http://stackoverflow.com/a/46874736
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46872475
accepted answer: http://stackoverflow.com/a/46872475
score: 1
has answer: http://stackoverflow.com/a/46874736
upvote count: 2
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/80755398
comment on: http://stackoverflow.com/a/46904075
score: 0
type: Comment
has text: Thank you, jezrael! This time your first answer works! I'll use it.
type: AnswerComment

http://stackoverflow.com/comment/80516115
score: 0
type: Comment
has text: I'm happy with the comprehension answer "a"
comment on: http://stackoverflow.com/a/46784213
type: AnswerComment

http://stackoverflow.com/comment/103195729
has text: @NikhilParashar don't understand what you want to do. I thought you just wanted to get rid of the extra fading arrows. You should probably ask a separate question giving more details.
comment on: http://stackoverflow.com/a/46791360
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/80505554
type: QuestionComment
has text: Possible duplicate of [How to install lxml on Windows](https://stackoverflow.com/questions/29440482/how-to-install-lxml-on-windows)
score: 1
comment on: http://stackoverflow.com/q/46753431
type: Comment

http://stackoverflow.com/comment/80628107
comment on: http://stackoverflow.com/a/46839655
score: 0
type: Comment
has text: @TomKarzes Nice catch. From 400ms to 300ms. :)
type: AnswerComment

http://stackoverflow.com/a/73029575
score: 0
type: Answer
has body: One option is with pivot_longer from pyjanitor: # pip install pyjanitor import pandas as pd import janitor df.pivot_longer(index = slice('ID','Task'), names_to = ('Experience', 'Condition', '.value'), names_sep = '_') ID Equipment Function Task Experience Condition time freq 0 0 eq_type_1 Fxn_a task_1 exprt cond1 12 0.031 1 1 eq_type_1 Fxn_a task_2 exprt cond1 10 0.028 2 2 eq_type_1 Fxn_b task_3 exprt cond1 13 0.033 3 3 eq_type_1 Fxn_b task_4 exprt cond1 9 0.027 4 4 eq_type_2 Fxn_a task_1 exprt cond1 14 0.036 5 5 eq_type_2 Fxn_a task_2 exprt cond1 11 0.030 6 0 eq_type_1 Fxn_a task_1 exprt cond2 24 0.055 7 1 eq_type_1 Fxn_a task_2 exprt cond2 22 0.052 8 2 eq_type_1 Fxn_b task_3 exprt cond2 25 0.057 9 3 eq_type_1 Fxn_b task_4 exprt cond2 19 0.051 10 4 eq_type_2 Fxn_a task_1 exprt cond2 27 0.056 11 5 eq_type_2 Fxn_a task_2 exprt cond2 26 0.054 12 0 eq_type_1 Fxn_a task_1 novce cond1 15 0.042 13 1 eq_type_1 Fxn_a task_2 novce cond1 12 0.039 14 2 eq_type_1 Fxn_b task_3 novce cond1 18 0.047 15 3 eq_type_1 Fxn_b task_4 novce cond1 10 0.038 16 4 eq_type_2 Fxn_a task_1 novce cond1 16 0.043 17 5 eq_type_2 Fxn_a task_2 novce cond1 14 0.041 18 0 eq_type_1 Fxn_a task_1 novce cond2 31 0.059 19 1 eq_type_1 Fxn_a task_2 novce cond2 29 0.055 20 2 eq_type_1 Fxn_b task_3 novce cond2 34 0.062 21 3 eq_type_1 Fxn_b task_4 novce cond2 28 0.054 22 4 eq_type_2 Fxn_a task_1 novce cond2 32 0.061 23 5 eq_type_2 Fxn_a task_2 novce cond2 30 0.058 The .value in names_to determines which parts of the column labels stay as headers, while the others are collated into Experience and Condition columns.
answers question: http://stackoverflow.com/q/46818223

http://stackoverflow.com/a/46897114
score: 3
answers question: http://stackoverflow.com/q/46896502
upvote count: 3
downvote count: 0
type: Answer
has body: There may be something wrong with your HDFS installation, try giving the full path to hdfs in your command. /path/to/dir/hdfs namenode -format the path depends on your OS and hadoop distribution you're using etc. Use locate or find for it. If it works with full path, its probably a PATH issue, export the path in your .bashrc and then try. Cheers.

http://stackoverflow.com/q/46887157
tagged with: arrays
score: 0
has body: In the REPL, I can do the following with numpy.random.choice(): &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; results = ["a", "b", "c"] &gt;&gt;&gt; probabilities = [0.5, 0.25, 0.25] &gt;&gt;&gt; choice = np.random.choice(results, 1, p=probabilities) &gt;&gt;&gt; choice array(['a'], dtype='&lt;U1') &gt;&gt;&gt; choice = np.random.choice(results, 1, p=probabilities) &gt;&gt;&gt; choice array(['c'], dtype='&lt;U1') &gt;&gt;&gt; choice = np.random.choice(results, 1, p=probabilities) &gt;&gt;&gt; choice array(['b'], dtype='&lt;U1') As you can see, np.random.choice() returns something different every time it is called. In my code, I have something like this: # We start with a 2D array called areaMap # It is already filled up to be a grid of None # I want each square to change to a different biome instance based on its neighbours # Our parameters are yMax and xMax, which are the maximum coordinates in each direction yCounter = yMax for yi in areaMap: xCounter = 0 for xi in yi: biomeList = [woodsBiome(), desertBiome(), fieldBiome()] biomeProbabilities = np.array([0.1, 0.1, 0.1]) # (perform some operations to change the probabilities) biomeProbabilities = biomeProbabilities / biomeProbabilities.sum() # it should always sum to 1 choice = np.random.choice(biomeList, 1, p=biomeProbabilities)[0] # here we make a choice from biomeList based on biomeProbabilities areaMap[yCounter - 1][xCounter - 1] = choice # set the correct area to choice xCounter += 1 # increment yCounter -= 1 # decrement (because of some other code, it can't increment) This is part of a function to generate a 2D array containing different biomes. Later on in my code, after having run it, I get a result like this: ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ ^~~__^_~_^~^^~^^^__~ where each character (^, ~, _) represents a different biome. The map comes up with the same r…
linked to: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/80721367
answer count: 1
favorite count: 0
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
has title: Why is np.random.choice giving the same result every time?
upvote count: 1
has comment: http://stackoverflow.com/comment/80722327
downvote count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/46888584

http://stackoverflow.com/q/46876324
has title: Adding values to new column based on predicate
tagged with: pandas
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/80700474
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/46876341
has comment: http://stackoverflow.com/comment/80699508
type: Question
upvote count: 1
has body: Say I have a dataframe with a bunch of people and the company, they're affiliated with: Id|Name |Company 1 |Hanzo |Bank of America 2 |Bertha|Disney 3 |Bob |Swiss Bank Now I'd like to add a new column with the type of company, they belong to: Id|Name |Company |Type 1 |Hanzo |Bank of America|Bank 2 |Bertha|Disney |Entertainment 3 |Bob |Swiss Bank |Bank How would I go through the dataframe, filter the company column and extract the values into a new column? Something like this: for i in range(len(dataset)): if dataset[['Company'].str.contains('BANK')][i]: dataset['Type'] = 'Bank' else: dataset['Type'] = 'Unknown'
has comment: http://stackoverflow.com/comment/80699898
has answer: http://stackoverflow.com/a/46876341

http://stackoverflow.com/q/46812867
tagged with: api
has comment: http://stackoverflow.com/comment/80573962
has title: YouTube API: Not getting all videos of the given channel
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: youtube-data-api
upvote count: 1
tagged with: youtube-api
type: Question
has comment: http://stackoverflow.com/comment/80574265
has answer: http://stackoverflow.com/a/46869240
answer count: 2
linked to: http://stackoverflow.com/q/18953499
has answer: http://stackoverflow.com/a/56198807
downvote count: 0
has body: I have been trying to get all videos of a given channel ID. But I am not getting all videos code I tried to retrive all the videos of the channel: api_key = API_KEY base_video_url = 'https://www.youtube.com/watch?v=' base_search_url = 'https://www.googleapis.com/youtube/v3/search?' raw_url = 'https://www.googleapis.com/youtube/v3/' \ 'channels?key={}&amp;forUsername={}&amp;part=id' def getChannelID(username): ''' returns the channel ID ''' r=requests.get(raw_url.format(api_key,username)) json=r.json() print(json['items'][0]['id']) return json['items'][0]['id'] def getchannelVideos(): ''' returns list of all videos of a given channel ''' chanId=getChannelID('tseries') first_url = base_search_url + \ 'order=date&amp;part=snippet&amp;channelId={}&amp;maxResults=50&amp;key={}'\ .format(chanId,api_key) video_links = [] url = first_url while True: inp = requests.get(url) resp = inp.json() for i in resp['items']: if i['id']['kind'] == "youtube#video": video_links.append(base_video_url + i['id']['videoId']) try: next_page_token = resp['nextPageToken'] url = first_url + '&amp;pageToken={}'.format(next_page_token) except: break print('working') #used this to count repetitions of while loop return video_links here the given channel is T-Series which has 11,537 videos so far [ click to see the image of the channel showing the count ] But I received 589 videos only I used this line to count the no. of iterations while loop would do print('working') for this I observed that the while loop ends after 19 iterations ( I have tried on many channels But same is repeating ) the is last (19th iteration) Json data I was provided {'etag': "cbz3lIQ2N25AfwNr-BdxUVxJ_QY/7SEM6nSU4tBD7ZsR5Abt5L-uqAE", 'items': [], 'kind': 'youtube#searchListResponse', 'pageInfo': {'resultsPerPage': 50, 'totalResults': 15008}, 'prevPageToken': 'CLYHEAE', 'regionCode': 'IN'} why API not providing nextpageID though totalResults are 15008 ??

http://stackoverflow.com/comment/80691754
has text: @RajuSingh How did you define `soup`?
type: AnswerComment
comment on: http://stackoverflow.com/a/46871822
score: 0
type: Comment

http://stackoverflow.com/comment/80622866
type: Comment
type: QuestionComment
has text: @MauricioCortazar The first one: I want to get one by category and another by pk in the same query.
comment on: http://stackoverflow.com/q/46825382
score: 0

http://stackoverflow.com/a/46890922
has comment: http://stackoverflow.com/comment/80731218
answers question: http://stackoverflow.com/q/46890665
downvote count: 0
has body: Try to uninstall both bson and pymongo: sudo pip uninstall bson sudo pip uninstall pymongo and then reinstall pymongo using pip: sudo pip install pymongo
type: Answer
upvote count: 7
has comment: http://stackoverflow.com/comment/105526866
has comment: http://stackoverflow.com/comment/80738892
score: 7

http://stackoverflow.com/comment/80547542
type: Comment
type: QuestionComment
has text: You can pass arguments to `split` to limit how much splitting it actually does. In your case, you might be better off using `rsplit` which will split from the right side of the string instead. That could leave you with `a = line.rsplit(None, 7)[-7]`. Does that help performance?
comment on: http://stackoverflow.com/q/46800307
score: 0

http://stackoverflow.com/q/46856005
has comment: http://stackoverflow.com/comment/80659764
has title: How to use Flask to Display Data From Print
upvote count: 1
has comment: http://stackoverflow.com/comment/80660832
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80660945
has comment: http://stackoverflow.com/comment/80660419
has comment: http://stackoverflow.com/comment/80660747
has answer: http://stackoverflow.com/a/46856752
has comment: http://stackoverflow.com/comment/80660855
has comment: http://stackoverflow.com/comment/80660534
type: Question
downvote count: 2
score: -1
tagged with: flask
has body: I have this python code that I am trying to display data on static page using flask instead of console. from __future__ import print_function from private import private, private, private optimizeit = get_optimizeit(web.site, private.private) optimizeit.load_data_from_CSV("/path.../to..cvs.csv") data = optimizeit.get_data_by_name('somename') data = optimizeit.data[0] data.max_exposure = 0.5 generatedata = optimizeit.optimizeit(4) for datafield in generatedata: print (datafield) Where print I want to print this to simple flask page. I tried few things and I just can't think of way of doing it best way. EDIT: What I tried from __future__ import print_function import flask from private import private, private, private import time app = flask.Flask(__name__) @app.route('/sitea') def index(): def inner(): optimizeit = get_optimizit(website.site12, private.someprivate) optimizer.load_players_from_CSV("/mypath to csv.../.csv") #import csv data = optimizeit.datas[0] #optimize that data data.max_exposure = 0.5 #set some exposure to that data data_generator = optimizeit.optimizeit(4) for datalive in datalive_generator: return datalive return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show the partial page immediately app.run(debug=True) EDIT 2: THIS WORKED! from __future__ import print_function import flask from private import private, private, private import time app = flask.Flask(__name__) @app.route('/sitea') def index(): def inner(): optimizeit = get_optimizit(website.site12, private.someprivate) optimizer.load_players_from_CSV("/mypath to csv.../.csv") #import csv data = optimizeit.datas[0] #optimize that data data.max_exposure = 0.5 #set some exposure to that data data_generator = optimizeit.optimizeit(4) for datalive in datalive_generator: yield '%s&lt;br/&gt;\n' % datalive return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show the partial page immediately

http://stackoverflow.com/comment/80745936
comment on: http://stackoverflow.com/q/46899190
has text: I got it! Thanks guys =)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80662126
comment on: http://stackoverflow.com/a/46855910
type: Comment
has text: I mean get all images from `data-image-large` just one single page.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80605985
comment on: http://stackoverflow.com/q/46829313
type: Comment
score: 0
has text: Did you just forget the indentation in the post or also in the real code? If so the function returns None every time and the code below is not executed by the function.
type: QuestionComment

http://stackoverflow.com/comment/80725194
type: QuestionComment
has text: Assume I have 100 different dfs for the 100 consecutive date, I want to find the one which have the maximum number of rows. I don't think you need any data to implement such thing. You just need to assume that each `df` exist and have a certain number of rows.
comment on: http://stackoverflow.com/q/46888883
score: 0
type: Comment

http://stackoverflow.com/comment/80693152
score: 0
type: Comment
type: QuestionComment
has text: if you mean modifying line 35 to: line = stdout.read().splitlines(4096) it returns: AttributeError: 'list' object has no attribute 'strip'
comment on: http://stackoverflow.com/q/46872668

http://stackoverflow.com/q/46880999
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46881466
type: Question
has title: DJango CreateView not setting DB Key with Class-Based Views
has body: I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL: url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(), name='owner-contact-details'), Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model) from the models.py file class Mstrstoreheadcontact(models.Model): tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True) contactid = models.BigIntegerField(primary_key=True, default=0) genderid = models.BigIntegerField(blank=True, null=True, default=0) firstname = models.CharField(max_length=20, blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) officephoneno = models.CharField(max_length=20, blank=True, null=True) cellphoneno = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrStoreHeadContact' def get_absolute_url(self): return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid}) For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB. The problem When the code above is executed, the variable self.contactid is set to 0. See below: This results in the following URL to be placed in the address bar: http://127.0.0.1:8000/masterdata/owner/0/contact/details Because of the "0", this leads to a 404 error. In the DB, the value is set - for example to 10. Again, the data saves to …
accepted answer: http://stackoverflow.com/a/46881466
score: 0
answer count: 1
tagged with: django
tagged with: python

http://stackoverflow.com/a/46769876
has comment: http://stackoverflow.com/comment/80485564
answers question: http://stackoverflow.com/q/46769786
has comment: http://stackoverflow.com/comment/80490024
type: Answer
has comment: http://stackoverflow.com/comment/80490260
has comment: http://stackoverflow.com/comment/80489806
has comment: http://stackoverflow.com/comment/80485493
has comment: http://stackoverflow.com/comment/80485786
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80485694
has body: Use custom function with idxmax for return index of values by condition, add 1 for not lost b row: def f(x): m = x['status'].eq('b') b = m.idxmax() if m.any(): x = x.loc[:b] else: x return x a = df.groupby('id', group_keys=False).apply(f) print (a) id counter status additional_data 0 1 1 a 12 1 1 2 b 35 4 2 1 a 6 5 2 2 a 12 6 2 3 a 6 7 3 1 a 1 8 3 2 a 46 9 3 3 b 236
has comment: http://stackoverflow.com/comment/80489838
has comment: http://stackoverflow.com/comment/80485469
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46769786
type: AcceptedAnswer

http://stackoverflow.com/comment/80529997
comment on: http://stackoverflow.com/q/46790396
has text: also don't forget your import : `from django.core.exceptions import ValidationError`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80510718
score: 1
comment on: http://stackoverflow.com/q/46782017
has text: Maybe you should list the stuff you are allowed to use. It's hard to answer this type of question when we don't know what the rules are.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80686358
type: Comment
score: 0
has text: Be wary of replacing standard output like this. The whole point is that it is a file handle specified by the *user* of your program; you are just writing to the file requested by the user. If you want to write to a different file, be explicit: use the `file` argument to `print` to direct output to a specific file.
comment on: http://stackoverflow.com/q/46869520
type: QuestionComment

machine-learning
tags question: http://stackoverflow.com/q/46819664
tags question: http://stackoverflow.com/q/46807403
tags question: http://stackoverflow.com/q/46774412
tags question: http://stackoverflow.com/q/46806127
tags question: http://stackoverflow.com/q/46857596
tags question: http://stackoverflow.com/q/46759741
tags question: http://stackoverflow.com/q/46803764
tags question: http://stackoverflow.com/q/46796566
tags question: http://stackoverflow.com/q/46759376
tags question: http://stackoverflow.com/q/46770088
tags question: http://stackoverflow.com/q/46814984
tags question: http://stackoverflow.com/q/46793190
tags question: http://stackoverflow.com/q/46833744
tags question: http://stackoverflow.com/q/46822679
tags question: http://stackoverflow.com/q/46832637
tags question: http://stackoverflow.com/q/46863124
tags question: http://stackoverflow.com/q/46888842
tags question: http://stackoverflow.com/q/46871302
tags question: http://stackoverflow.com/q/46827580
tags question: http://stackoverflow.com/q/46842321
tags question: http://stackoverflow.com/q/46901740
tag name: machine-learning
tags question: http://stackoverflow.com/q/46835602
tags question: http://stackoverflow.com/q/46832151
tags question: http://stackoverflow.com/q/46774735
tags question: http://stackoverflow.com/q/46835428
tags question: http://stackoverflow.com/q/46872980
tags question: http://stackoverflow.com/q/46768519
tags question: http://stackoverflow.com/q/46846081
tags question: http://stackoverflow.com/q/46775155
tags question: http://stackoverflow.com/q/46864926
tags question: http://stackoverflow.com/q/46820500
tags question: http://stackoverflow.com/q/46845480
tags question: http://stackoverflow.com/q/46884841
tags question: http://stackoverflow.com/q/46875847
tags question: http://stackoverflow.com/q/46752650
tags question: http://stackoverflow.com/q/46886329
tags question: http://stackoverflow.com/q/46828118
type: Tag
tags question: http://stackoverflow.com/q/46836499
tags question: http://stackoverflow.com/q/46904972
tags question: http://stackoverflow.com/q/46816301
tags question: http://stackoverflow.com/q/46880576
tags question: http://stackoverflow.com/q/46894615
tags question: http://stackoverflow.com/q/46820609
tags question: http://stackoverflow.com/q/46752281
tags question: http://stackoverflow.com/q/46823526
tags question: http://stackoverflow.com/q/46790654
tags question: http://stackoverflow.com/q/46781448
tags question: http://stackoverflow.com/q/46857382
tags question: http://stackoverflow.com/q/46770457
tags question: http://stackoverflow.com/q/46793110
tags question: http://stackoverflow.com/q/46806540
tags question: http://stackoverflow.com/q/46888984
tags question: http://stackoverflow.com/q/46894375
tags question: http://stackoverflow.com/q/46757973
tags question: http://stackoverflow.com/q/46756606
tags question: http://stackoverflow.com/q/46757220
tags question: http://stackoverflow.com/q/46785025
tags question: http://stackoverflow.com/q/46897386
tags question: http://stackoverflow.com/q/46827434
tags question: http://stackoverflow.com/q/46838739
tags question: http://stackoverflow.com/q/46775723
tags question: http://stackoverflow.com/q/46843430
tags question: http://stackoverflow.com/q/46762083
tags question: http://stackoverflow.com/q/46882307
tags question: http://stackoverflow.com/q/46860617
tags question: http://stackoverflow.com/q/46792252
tags question: http://stackoverflow.com/q/46836848
tags question: http://stackoverflow.com/q/46753234
tags question: http://stackoverflow.com/q/46803880
tags question: http://stackoverflow.com/q/46841795
tags question: http://stackoverflow.com/q/46902362
tags question: http://stackoverflow.com/q/46784184
tags question: http://stackoverflow.com/q/46786036
tags question: http://stackoverflow.com/q/46892880
tags question: http://stackoverflow.com/q/46818376
tags question: http://stackoverflow.com/q/46755168
tags question: http://stackoverflow.com/q/46759151
tags question: http://stackoverflow.com/q/46850111

http://stackoverflow.com/comment/80720279
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/46885591
has text: @snowflake: that's still not an objective criteria.

http://stackoverflow.com/comment/80496621
type: AnswerComment
score: 0
type: Comment
has text: this is how the parenthesis have to be print (n, n**2, n**3, "\n")? for me to print it, because is telling me that I need the parenthesis to print it.
comment on: http://stackoverflow.com/a/46775491

http://stackoverflow.com/comment/80658725
type: QuestionComment
type: Comment
has text: Could always do it in base asyncio the intention is to learn the low level
comment on: http://stackoverflow.com/q/46788964
score: 0

http://stackoverflow.com/comment/80585018
score: 0
comment on: http://stackoverflow.com/q/46818471
type: Comment
type: QuestionComment
has text: Please use Anaconda instead of WinPython. Anaconda is better maintained and has more support.

http://stackoverflow.com/q/46826035
favorite count: 0
has title: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46826703
accepted answer: http://stackoverflow.com/a/46826703
upvote count: 0
has body: I'm working with flask for past few days. I get deprecation error in flask_whooshalchemy. 1. I Installed 'flask_whooshalchemy' with pip. pip install flask_whooshalchemy 2. And on python interpreter I tried to import flask_whooshalchemy by using import flask_whooshalchemy I get the below error, &gt;&gt;&gt; import flask_whooshalchemy /usr/local/lib/python2.7/dist-packages/flask_whooshalchemy.py:18: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead. import flask.ext.sqlalchemy as flask_sqlalchemy what might went wrong and how to fix the issue? Note: I use python 2.x
duplicate of: http://stackoverflow.com/q/38079200
score: -1
tagged with: flask
tagged with: flask-sqlalchemy
tagged with: python-2.7
linked to: http://stackoverflow.com/q/38079200
answer count: 1

http://stackoverflow.com/q/46842063
has answer: http://stackoverflow.com/a/59017243
answer count: 3
has answer: http://stackoverflow.com/a/46842109
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: encryption
upvote count: 1
tagged with: python
has title: Writing a beginner level encryption program on Python 3 (From Think Python)
score: 1
has answer: http://stackoverflow.com/a/59017121
type: Question
has body: def doppelt(word): word = word.lower() encoded = '' for c in word: new_ord = word new_ord = 96 + (new_ord - 121) % 26 encoded += chr(new_ord) return encoded TypeError Traceback (most recent call last) in () ----> 1 doppelt('string') in doppelt(word) 4 new_ord = word 5 for c in word: ----> 6 new_ord = 96 + (new_ord - 121) % 26 7 encoded += chr(new_ord) 8 return encoded TypeError: unsupported operand type(s) for -: 'str' and 'int'
downvote count: 0

http://stackoverflow.com/q/46868534
has comment: http://stackoverflow.com/comment/80684351
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46868704
has body: Im currently writing a program that needs to figure out the lengths of words in a sublist of a list and then add them together. Currently the code i have can either break out the list that is a sentence into individual words and now i need to find the lengths of the individual words in the sublist. Whenever i use counter_split_list, it counts the words in the sentence. here is my code: def split_by_whitespace (['It', 'is', 'a', 'truth', 'universally', 'acknowledged'], ['that', 'a', 'single', 'man', 'in', 'possession', 'of', 'a', 'good', 'fortune', 'must', 'be', 'in', 'want', 'of', 'a', 'wife']): l = my_string split_list =[i.split() for i in l] #counter_split_list=[len(i) for i in split_list] return(split_list) Words in Sublists
has comment: http://stackoverflow.com/comment/80684619
score: 0
has comment: http://stackoverflow.com/comment/80684330
answer count: 1
has comment: http://stackoverflow.com/comment/80684417
accepted answer: http://stackoverflow.com/a/46868704
favorite count: 0
has comment: http://stackoverflow.com/comment/80684462
has comment: http://stackoverflow.com/comment/80684702
has comment: http://stackoverflow.com/comment/80684295
tagged with: python
has comment: http://stackoverflow.com/comment/80684466
has comment: http://stackoverflow.com/comment/80684501
type: AnsweredQuestion
has title: Find a length of a sub list of a list Python
tagged with: list

http://stackoverflow.com/q/46805462
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46805565
accepted answer: http://stackoverflow.com/a/46805565
has comment: http://stackoverflow.com/comment/80558387
has body: I am using python v3.6 on Windows 10. When specifying a string to represent a directory location, what is the difference between the 2 approaches below? folder_location = 'C:\\Users\\username\\Dropbox\\Inv' folder_location = 'C:/Users/username/Dropbox/Inv' This is a follow-up question to another question I just posted. My problem was solved when I used \\ instead of /. What is wrong with this selenium firefox profile to download file into customized folder?
has answer: http://stackoverflow.com/a/46805713
type: Question
has comment: http://stackoverflow.com/comment/80558017
score: 5
has answer: http://stackoverflow.com/a/46805655
has comment: http://stackoverflow.com/comment/80558839
downvote count: 2
has comment: http://stackoverflow.com/comment/80558006
upvote count: 7
has answer: http://stackoverflow.com/a/46805631
tagged with: directory
has comment: http://stackoverflow.com/comment/80558081
favorite count: 0
has comment: http://stackoverflow.com/comment/80558029
has answer: http://stackoverflow.com/a/46805596
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80558056
linked to: http://stackoverflow.com/q/46803702
linked to: http://stackoverflow.com/q/16333569
answer count: 5
possible better answer: http://stackoverflow.com/a/46805655
tagged with: python
has title: What is the difference between using / and \\ in specifying folder location in python?

http://stackoverflow.com/comment/80589555
score: 0
has text: Do not know much about Redshift. But from the URL, the database is `sample_database`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46820932

http://stackoverflow.com/a/46820074
score: 1
upvote count: 1
has body: One way might be instead of using lists. Use generators. They are iterable too. See: http://letstalkdata.com/2015/05/how-to-use-python-generators-to-save-memory/
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/46820001

http://stackoverflow.com/q/46851689
has comment: http://stackoverflow.com/comment/80650847
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46851808
tagged with: python
has body: I have the sample tensorflow code below import tensorflow as tf with tf.device('/cpu:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) print(sess) print(sess.run(c)) explicitly i have given tf.device('/cpu:0') but it is giving the following error : InvalidArgumentError (see above for traceback): Cannot assign a device for operation 'MatMul_5': Operation was explicitly assigned to /device:GPU:0 but available devices are [ /job:localhost/replica:0/task:0/cpu:0 ]. Make sure the device specification refers to a valid device. [[Node: MatMul_5 = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/device:GPU:0"](a_5, b_5)]] Tensorflow version : 1.3.0, python version : 3.6.1 with Anaconda Distribution
has title: Python-Tensorflow running on GPU instead of CPU
tagged with: tensorflow
type: Question
score: 0
answer count: 1

http://stackoverflow.com/comment/80542968
type: QuestionComment
comment on: http://stackoverflow.com/q/46798067
has text: Are you using `pandas`?
score: 1
type: Comment

http://stackoverflow.com/q/46849588
has comment: http://stackoverflow.com/comment/80650116
has title: Ajax filter in django not showing in HTML
has answer: http://stackoverflow.com/a/46852085
accepted answer: http://stackoverflow.com/a/46852085
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80646767
type: Question
tagged with: javascript
tagged with: jquery
has comment: http://stackoverflow.com/comment/80647005
tagged with: ajax
has comment: http://stackoverflow.com/comment/80646456
score: 0
has body: I'm not sure if my Ajax implementation is right. Using Django built in tags, the objects I am passing using Ajax is not showing up on my template HTML page. view_results.html {% if results|length %} {% for r in results %} {{ r.trail_id }} {{ r.trail_long }} {% endfor %} {% else %} Not found {% endif %} Javascript $(function() { $('#search').keyup(function() { $.ajax({ type: "GET", url: "/search/get_trail/", data: { 'search_text' : $('#search').val() }, success: function(data){console.log(data)}, dataType: 'html' }); }); }); views.py def trails_view(request): trails = Trail.objects.all() trails_json = serialize('geojson' , trails, fields=('trails_type', 'trails_id', 'wkb_geometry',)) trails_geojson = json.loads(trails_json) trails_geojson.pop('crs', None) trails_geojson = json.dumps(trails_geojson) return render(request, '/view_trails.html', {'trails':trails, 'trails_geojson':trails_geojson}) def get_trails(request): if request.method == "GET": search_text = request.GET['search_text'] if search_text is not None and search_text != u"": search_text = request.GET['search_text'] results = Trail.objects.filter(trails_id__contains=search_text) else: results = [] return render(request, '/view_trails.html', {'results': results}) urls.py url(r'^view/', views.trails_view, name='trails_view'), url(r'^search/get_trails/', views.get_trails, name='get_trails'), I am wondering if trails_view and get_trails is the reason of the function not showing up the results upon ajax call. I tried printing out the contents of results in views.py and it does filter out according to the search_text. The problem is the contents not showing up in the template tags. I wanted to do something like this: Simple Ajax Search What am I doing wrong?
answer count: 1
has comment: http://stackoverflow.com/comment/80646720

http://stackoverflow.com/a/46771534
score: 0
has comment: http://stackoverflow.com/comment/80489503
has comment: http://stackoverflow.com/comment/80489027
has comment: http://stackoverflow.com/comment/80489085
type: Answer
has comment: http://stackoverflow.com/comment/80489018
has comment: http://stackoverflow.com/comment/80489809
has comment: http://stackoverflow.com/comment/80488647
has comment: http://stackoverflow.com/comment/80488958
has comment: http://stackoverflow.com/comment/80489636
has comment: http://stackoverflow.com/comment/80490312
has body: I'm assuming mycsvfile.csv file have SPLE column. from elasticsearch import Elasticsearch es = Elasticsearch(["9200"]) res = es.search(index="search", body= { "_source": ["DTDT", "TRDT", "SPLE", "RPLE"], "query": { "bool": { "should": [ {"wildcard": {"CN": "TEST*"}} ] } } }, size=10) import pandas as pd SPLE = {0:'true',1:'false',50:'pending'} saved_csv = pd.read_csv('mycsvfile.csv',sep='\t') saved_csv['SPLE'] = saved_csv['SPLE'].map(lambda x: SPLE[int(x)]) saved_csv.to_csv('edited_csv.csv', index=False)
answers question: http://stackoverflow.com/q/46770939
has comment: http://stackoverflow.com/comment/80489355
has comment: http://stackoverflow.com/comment/80489379
has comment: http://stackoverflow.com/comment/80488877

http://stackoverflow.com/comment/80548127
has text: @ReblochonMasque, I misunderstood. I thought you meant a loop inside __enter__ phase of the CM. Simple `with cm(): for x in iter: block(x)` does not work because when block raises an exception to be caught by `cm` it exits the loop.
comment on: http://stackoverflow.com/q/46800458
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46835539
answers question: http://stackoverflow.com/q/46834421
upvote count: 1
has body: perhaps with eval: exp = 'direct.pivot_table(index=\'Code\', columns=\'Period\', values=agg, aggfunc=sum' marg = 'margins=True, margins_name=\'Year to date\')' datak = eval(exp + ', ' + marg) if ytd is not None else eval(exp + ')')
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/80546855
type: AnswerComment
has text: If your data is sorted and you know the divisions then you can easily call set_index. You might want to learn more about divisions: http://dask.pydata.org/en/latest/dataframe-design.html#partitions
comment on: http://stackoverflow.com/a/46798024
type: Comment
score: 0

http://stackoverflow.com/a/46903291
score: 0
type: Answer
has body: Hi try splitting the text in to a list: import pickle text= "hello this is a unique line. and it will end with // this should be the other line and it also ends with // a third line just for good mesure//" pickle.dump(text, open("text.txt","wb")) page = pickle.load(open("text.txt","rb")).split("//")[0] print(page) and then just index the page you want in this line: page = pickle.load(open("text.txt","rb")).split("//")[0]
answers question: http://stackoverflow.com/q/46903114

http://stackoverflow.com/comment/80825204
type: QuestionComment
has text: @RobinDunn I'll work on that, thanks. It's a bit of a pain, but hopefully worth the effort.
comment on: http://stackoverflow.com/q/46836281
score: 0
type: Comment

http://stackoverflow.com/q/46872032
has title: Check that FTP connection opened successfully and files have been uploaded to FTP in Python
has body: I'm building a remote time-lapse camera that takes pictures every half hour and sends them via FTP to my server. A Raspberry Pi will control the camera, gather the files and send them over, via a Python script like so: while true captureImages() renameFiles(picID) upload() #uploads any files and folders in the selected path delete () #deletes the uploaded files from the pi My question has to do with this upload function (which works ok) and the subsequent delete function def upload():#sends the file to server print ("connecting") #ftp connection (server, user,pass) ftp = ftplib.FTP('server','user','pass') #folder from which to upload template_dir = '/home/pi/captures/' print ("uploading") #iterate through dirs and files for root, dirs, files in os.walk(template_dir, topdown=True): relative = root[len(template_dir):].lstrip(os.sep) #enters dirs for d in dirs: ftp.mkd(os.path.join(relative, d)) #uploads files for f in files: ftp.cwd(relative) ftp.storbinary('STOR ' + f, open(os.path.join(template_dir, relative, f), 'rb')) ftp.cwd('/') What I need here are two things: a way to confirm that the files have been uploaded successfully, like a bool 'uploaded(true/false)' to trigger or not the 'remove' function. a way to skip the upload process and NOT REMOVE files if the connection cannot be established for whatever reason. Like a timeout, a window of 10 seconds in which it tries to establish the connection and if it cannot it skips both 'upload' and 'remove' and therefore stores the files locally and try again at the next iteration of the while loop. Thank you in advance for your help!
has answer: http://stackoverflow.com/a/46887716
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80713158
has comment: http://stackoverflow.com/comment/80714459
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: ftp
tagged with: ftplib
upvote count: 2
has comment: http://stackoverflow.com/comment/80714366
tagged with: error-handling
has comment: http://stackoverflow.com/comment/80721636
type: Question

http://stackoverflow.com/comment/80498319
has text: @sascha I am very sorry for this, but the problem is of this kind itself
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46774779
score: 0

http://stackoverflow.com/comment/80632684
type: AnswerComment
has text: I'm confused. Isn't that just going to return `color`, rather than the index where `color` appears?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46839203

http://stackoverflow.com/q/46751267
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80448676
type: Question
has comment: http://stackoverflow.com/comment/80448907
has body: So I want my database to contain the datatype Item I defined in python: class Item: Name = str L = Location #An Array Quantity = int Description = str I made a table with that as a datatype, the GUI that I use says that column is the Item type: def CreateTable(DatabaseName ,TableName): conn = s.connect(DatabaseName) print ("Opened database successfully") conn.execute('CREATE TABLE ' + TableName + ' (id integer, Items Item);') print ("Table created successfully") conn.close() Now that I have that I want to insert values, so I defined the following function: def AddItemToTable(DatabaseName, TableName, Items): conn = s.connect(DatabaseName) c = conn.cursor() c.execute('INSERT INTO '+TableName + '(id, Items) \ VALUES(1,'+Items+')') conn.commit conn.close() I execute these functions: I = Item CreateTable('HelloWorld.db', 'again1') AddItemToTable('HelloWorld.db', 'again1', 'I') The Database is made, the Table is made, it has the two columns, each column has the right type, but it says theres no column I. If I leave I out of quotes, it tells me it requires an str not type.
has title: Insert user defined datatype into SQLite Database using python function
score: 0
tagged with: sql
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/46751499

http://stackoverflow.com/a/46762900
upvote count: 2
answers question: http://stackoverflow.com/q/46762597
has comment: http://stackoverflow.com/comment/80472387
downvote count: 0
has body: First, turn df.id into a an array of single digit integers. a = np.array(list(map(list, map(str, df.id))), dtype=int) Then check to see if one digit is one less than the next digit... twice first = a[:, :-2] == a[:, 1:-1] - 1 second = a[:, 1:-1] == a[:, 2:] - 1 Create a mask for when we have this happen more than once mask = np.count_nonzero(first &amp; second, axis=1) &lt; 2 df[mask] id 1 632746378456 2 378256364036 3 159204652855
type: Answer
score: 2

http://stackoverflow.com/comment/80532157
type: AnswerComment
has text: Thank you this worked exactly like i wanted it to thank you
type: Comment
score: 0
comment on: http://stackoverflow.com/a/46792720

http://stackoverflow.com/q/46762265
accepted answer: http://stackoverflow.com/a/46762317
type: Question
tagged with: attributeerror
tagged with: dataframe
has answer: http://stackoverflow.com/a/46762302
has body: I have the following data frame: df1 NumOfTransactions ComissionDeduction 2011-01-10 2 19.90 2011-01-13 2 19.90 2011-01-26 1 9.95 df2 ['2011-01-10'] I need to join the two so I remain with the row in df1 for when that date is also in df2. NumOfTransactions ComissionDeduction 2011-01-10 2 19.90 I'm trying to achieve that functionality using: impact = trades.index[trades.zero == total_columns].astype(str).tolist() trades_impact = transactions.join(impact) However, I'm receiving the following error;AttributeError: 'builtin_function_or_method' object has no attribute 'is_unique'
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/46762302
downvote count: 0
favorite count: 0
has title: AttributeError: 'builtin_function_or_method' object has no attribute 'is_unique'
tagged with: python
linked to: http://stackoverflow.com/q/27702727
tagged with: indexing
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46762317
has comment: http://stackoverflow.com/comment/80469885
upvote count: 3

http://stackoverflow.com/comment/80590572
type: QuestionComment
comment on: http://stackoverflow.com/q/46821562
has text: Isn't that just `{ x for x,y in a }` ?
score: 0
type: Comment

http://stackoverflow.com/q/46830120
has comment: http://stackoverflow.com/comment/80607726
has comment: http://stackoverflow.com/comment/80607633
type: UnansweredQuestion
tagged with: django
downvote count: 1
type: Question
score: -1
answer count: 2
upvote count: 0
has body: i'd like to check if data exists in all my fields and if there is None in one field return False for all the rest otherwise return True if all the fields are filled up. It's only returning True. Can Anyone help ret = {'complete': False} try: company_director = CompanyDirector.objects.filter(company__token=token).values( 'username','directorTitle','directorInitials', 'directorName','administrativeOrder', 'directorSurname','directorId','directorQualification', 'releventExperiance','education','directorInsolvent', 'directorProffesionalAssociation','profileImage','profileImageThumbNail', 'directorProffesionalAssociationList','releventExperiance','shareInBusiness', 'profileImage','qualifications','criminalOffence','capInBuss','spSkill').first() if company_director: ret['complete'] = True for field, value in company_director.items(): if (type(value) in [str, unicode] is None and len(value)) == "": ret['complete'] = False break; if str(exclude_items) in field: if (type(value) in [str, unicode] and len(value) &gt; 0 and value is not None) or type(value) in \ [int]: ret['complete'] = True except ValueError as e: print (e) return Response(ret)
has answer: http://stackoverflow.com/a/46830606
has answer: http://stackoverflow.com/a/46830352
favorite count: 0
has comment: http://stackoverflow.com/comment/80607735
has comment: http://stackoverflow.com/comment/80607826
has title: checking if data existing in my array of dict
tagged with: python

http://stackoverflow.com/a/46835592
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80627022
downvote count: 0
has comment: http://stackoverflow.com/comment/80623240
has body: This could partially be explained by the method-call / function-call overhead. Your dictionary-search function merely does a single operation, indexing, which is translated into a call to my_dict.__getitem__(key), whereas your array-based implementation ultimately calls 3 methods, .searchsorted and __getitem__ twice. Python is a dynamic language, function-calls and, especially, method calls (because of method resolution) are expensive. But fundamentally, your dict-based implementation should scale better. Python dict objects are highly optimized hash-maps with constant-time search, usually. Your array based implementation is binary search, so it is O(log(n)). You'll see this with a test-case where you select the worst-case, i.e., searching for an element not in the array. Given that searchsorted scales logarithmically, you might have to increase the size of your array dramatically (e.g.100x, 1000x) before you see notable runtime effects. There is absolutely no chance you'll implement a faster look-up than the built-in dict in Python.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/80621607
has comment: http://stackoverflow.com/comment/80623124
has comment: http://stackoverflow.com/comment/80626991
answers question: http://stackoverflow.com/q/46835263
score: 1
has comment: http://stackoverflow.com/comment/80626822
accepted answer of: http://stackoverflow.com/q/46835263
has comment: http://stackoverflow.com/comment/80621456

google-cloud-dataflow
tags question: http://stackoverflow.com/q/46854167
tags question: http://stackoverflow.com/q/46840828
tag name: google-cloud-dataflow
tags question: http://stackoverflow.com/q/46764974
tags question: http://stackoverflow.com/q/46775671
tags question: http://stackoverflow.com/q/46807209
tags question: http://stackoverflow.com/q/46753904
tags question: http://stackoverflow.com/q/46898800
tags question: http://stackoverflow.com/q/46794351
type: Tag

http://stackoverflow.com/q/46846828
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46847177
downvote count: 0
score: 1
type: Question
has title: How to insert multiple IDs into a sql statement?
tagged with: pandas
upvote count: 1
answer count: 1
has body: New to python and pandas, Im facing the following issue: I would like to pass multiple string into a sql query and struggle to insert the delimiter ',' : Example data import pandas as pd data = [['Alex',10],['Bob',12],['Clarke',13]] df = pd.DataFrame(data,columns=['Name','Age']) print (df) # Remove header (Not sure whether that is necessary) df.columns = df.iloc[0] pd.read_sql( """ SELECT * FROM emptable WHERE empID IN ('{}',) """.format(df.ix[:, 0]), # Which corresponds to 'Alex','Bob','Clarke' con = connection) I tried different combinations, however None of them have worked out.
favorite count: 0

http://stackoverflow.com/comment/80707410
type: Comment
type: QuestionComment
has text: Now I get this error ValueError: malformed node or string: <_ast.Call object at 0x124af56d8>
score: 0
comment on: http://stackoverflow.com/q/46879936

angularjs
tags question: http://stackoverflow.com/q/46762014
type: Tag
tag name: angularjs
tags question: http://stackoverflow.com/q/46777222
tags question: http://stackoverflow.com/q/46871459

http://stackoverflow.com/comment/80664886
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46858541
has text: Are your ports open on your nginx server? If you're not seeing anything in the nginx logs, that'd leave me to believe something is amiss just before the connection gets to nginx.

http://stackoverflow.com/comment/80540357
comment on: http://stackoverflow.com/q/46796126
has text: "consider using Java".. Horrible answer to an issue involving cross-platform implementation to EMBEDDED.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80555008
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46792969
has text: Thanks for taking the time to look into this. Well, plotting 2 surface plots for each height is not what I want; this is easy using contourf(). I have done a 3D representation of an iso-surface concentration in the past using a software [see here](https://folk.nilu.no/~nikolaos/6.Photos_videos/21.mov), but I was wondering if it is possible to do the same in Python.
type: Comment

http://stackoverflow.com/comment/80692406
type: AnswerComment
comment on: http://stackoverflow.com/a/46872296
score: 0
type: Comment
has text: @wxvxw take a look at the edits - does it answer your question?

http://stackoverflow.com/comment/80536107
comment on: http://stackoverflow.com/q/46783245
type: QuestionComment
has text: this works for me, what is your environment?
score: 0
type: Comment

http://stackoverflow.com/q/46863036
answer count: 0
has comment: http://stackoverflow.com/comment/80681603
type: Question
has comment: http://stackoverflow.com/comment/80703877
has comment: http://stackoverflow.com/comment/80680925
tagged with: transformation
has title: Pyspark Dataframe subsetting
tagged with: pyspark
has comment: http://stackoverflow.com/comment/80712631
tagged with: hadoop
score: 0
has comment: http://stackoverflow.com/comment/80706946
has body: Below is my dataframe id name categroy 1 naveen a 2 sriknat b 3 raghu c 4 ramya d 5 nagraj e 6 Tina a 7 George a Now I need to divide the dataframe into parts based on id column My output should be as 1,2,3 rows in one dataframe and 4,5,6,7 in one more dataframe I tried below logic didn't work df_test=eres_bkp.registerTempTable("df") test=sqlCtx.sql("select * from eres_bkp where id between 0 and 3") train=sqlCtx.sql("select * from eres_bkp where id between 5 and 7") Please help on same.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80452699
score: 0
type: Comment
has text: @ray You have to import the [`logging`](https://docs.python.org/3.6/howto/logging.html) module to use it.
type: AnswerComment
comment on: http://stackoverflow.com/a/46753192

http://stackoverflow.com/q/46778712
type: Question
tagged with: mutex
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46779756
tagged with: multithreading
tagged with: python
has title: python xdata and ydata must be the same length
type: AnsweredQuestion
tagged with: matplotlib
has body: I think this is an interesting problem. I'd like to read in data from a server so that I can plot data live using matplotlib. Currently I'm testing values that would be read in by simulating using random, and I've found that I'm getting this error: File "/usr/lib/python2.7/dist-packages/matplotlib/lines.py", line 632, in recache raise RuntimeError('xdata and ydata must be the same length') RuntimeError: xdata and ydata must be the same length What I don't understand is how the size of xdata and ydata could possibly mismatch if I'm using a mutex to protect the data from being read and updated at the same time. You can take a look at the seriously simple code below: import matplotlib.pyplot as plt import time from threading import Thread, Lock import random data = [] mutex = Lock() # This just simulates reading from a socket. def data_listener(): while True: with mutex: data.append(random.random()) if __name__ == '__main__': t = Thread(target=data_listener) t.daemon = True t.start() # initialize figure plt.figure() ln, = plt.plot([]) plt.ion() plt.show() plt.axis([0, 100, 0, 1]) while True: plt.pause(0.1) with mutex: ln.set_xdata(range(len(data))) ln.set_ydata(data) plt.draw() As you can see, I am assuring that when appending to the data or adding data to update the plot, you must acquire the mutex, which means len(xdata)==len(ydata). Any ideas with where I've made an assumption would be helpful. You can copy and run the code yourself.
accepted answer: http://stackoverflow.com/a/46779756

http://stackoverflow.com/comment/80664302
score: 0
type: Comment
type: QuestionComment
has text: See [signet](http://jamercee.github.io/signet/).
comment on: http://stackoverflow.com/q/46857639

http://stackoverflow.com/comment/80510040
has text: Have you never seen a vector with more than 3 dimensions?
comment on: http://stackoverflow.com/a/46781488
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/46783339
has body: I have recently started learning PYTHON and I am facing some difficulty. I am trying to extract data from excel sheet with and without def statement . So without def, I am getting valid output but when I extract data using def statement, I am getting "NONE" as output. Please help me to resolve this. book=xlrd.open_workbook("E:\\Email.xlsx") print(book.nsheets) SheetName =book.sheet_by_name("gmail") rows=SheetName.nrows cols=SheetName.ncols print(rows) print(cols) ##### WITHOUT DEFINING ANY FUNCTION #### table=list() record=list() for x in range(rows): for y in range(cols): record.append(SheetName.cell(x,y).value) table.append(record) record=[] rows=rows+1 print(table) O/P:[['Email ID:'], ['AVVC.com'], ['Password'], ['abcdefg']] WITH DEF def getcell(rows,cols): table=list() record=list() for x in range(rows): for y in range(cols): record.append(SheetName.cell(x,y).value) table.append(record) record=[] rows=rows+1 return; v= getcell(0,1) print(v) O/P:NONE
tagged with: excel
type: Question
has title: I am trying to extract data from excel sheet with and without def statement (functions) in python
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/80513336
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/80513376
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46783852
tagged with: selenium

http://stackoverflow.com/comment/80568932
type: Comment
comment on: http://stackoverflow.com/q/46810479
has text: do you understand what my post is for? i think you are mistaking what i have asked for. When there is no data for VT the query fails to run and does not create the CSV or carries on grabbing the data for the rest of the headers.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80758921
has text: Why not 6:30? That is more than 1h difference
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46905576

http://stackoverflow.com/a/59017121
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46842063
has body: Addition of an Integer with a String or Char raises the TypeError exception in Python. So you first need to convert your new_ord to a integer first, before adding. You, can do this by the ord() function.

http://stackoverflow.com/q/46749867
has title: Can't import functions from Python file in the same directory
has answer: http://stackoverflow.com/a/46749916
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has body: I created two Python scripts and put them in the same directory: myfunctions.py def f(x): return x**2 def g(x): return x**3 mytest.py from myfunctions import f, g print f(2) print g(3) This isn't working, how do I get this to work? It works when the files are in my home directory, but I don't know how to make it work when they're in some other directory.
upvote count: 1
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80445781
has comment: http://stackoverflow.com/comment/80445817

nltk
tags question: http://stackoverflow.com/q/46900082
tags question: http://stackoverflow.com/q/46835712
tags question: http://stackoverflow.com/q/46760371
tags question: http://stackoverflow.com/q/46792595
tags question: http://stackoverflow.com/q/46852316
tags question: http://stackoverflow.com/q/46826139
tags question: http://stackoverflow.com/q/46765067
tags question: http://stackoverflow.com/q/46877535
tags question: http://stackoverflow.com/q/46786211
tags question: http://stackoverflow.com/q/46762796
tags question: http://stackoverflow.com/q/46901511
tags question: http://stackoverflow.com/q/46775092
tags question: http://stackoverflow.com/q/46806912
tags question: http://stackoverflow.com/q/46779116
tag name: nltk
tags question: http://stackoverflow.com/q/46872083
tags question: http://stackoverflow.com/q/46812096
tags question: http://stackoverflow.com/q/46842463
tags question: http://stackoverflow.com/q/46866525
type: Tag

http://stackoverflow.com/comment/80516484
comment on: http://stackoverflow.com/q/46784976
has text: @ZoharPeled No it will send JSON object with several fields.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80674824
comment on: http://stackoverflow.com/q/46863047
has text: @YvesDaoust area seen in the image
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80509466
has text: @cricket_007 Yes, you're right. The initial list is not modified, I construct a new list.
comment on: http://stackoverflow.com/q/46781420
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80687724
score: 0
comment on: http://stackoverflow.com/a/46869944
type: AnswerComment
has text: What does XXX mean?
type: Comment

http://stackoverflow.com/comment/92694710
has text: People who come here might be affected by [spulec/moto/issues/1793](https://github.com/spulec/moto/issues/1793)
comment on: http://stackoverflow.com/q/46835804
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80794608
type: Comment
comment on: http://stackoverflow.com/a/46904608
type: AnswerComment
score: 0
has text: Could you upload your project's settings? maybe there's a miss configuration.

http://stackoverflow.com/comment/80705253
type: QuestionComment
has text: Actually that was intentional. But it's entirely possible that that's a mistake because i'm a total machine learning novice.
comment on: http://stackoverflow.com/q/46876614
score: 0
type: Comment

http://stackoverflow.com/q/46814679
upvote count: 1
has body: I tried to import SMOTE from imblearn this way: from imblearn.over_sampling import SMOTE I'm using Jupyter Notebooks but because I have Windows I cannot use the terminal that came with Jupyter. I have anaconda so on the anaconda prompt I wrote: "pip install imblearn" Afterwards, I upgraded sklearn (because I've got an error of that): "pip install --upgrade sklearn" The upgrade and the install ran well in Anaconda prompt. But then I've got another error on my notebook: "ImportError: cannot import name '_LearntSelectorMixin'" Which, I think, is an element from sklearn that couldn't be imported I don't know if i'm doing something wrong... or what I can do. Thanks!
tagged with: anaconda
linked to: http://stackoverflow.com/q/41843007
has comment: http://stackoverflow.com/comment/80589605
score: 1
has title: Error importing imblearn in Jupyter and from commandline
type: Question
downvote count: 0
tagged with: imblearn
favorite count: 0
tagged with: importerror
tagged with: python
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/46898667
type: Answer
accepted answer of: http://stackoverflow.com/q/46898498
answers question: http://stackoverflow.com/q/46898498
score: 0
type: AcceptedAnswer
has body: You have to pass the function as success argument. Currently in r=try_except(get_address(-33.865, 151.2094),"") you are passing result value of get_address(-33.865, 151.2094) which is 'Sydney'. The actual error is raised on trying to call success() which translates to 'Sydney'() - something like str object is not callable Proper call would be r=try_except(lambda: get_address(-33.865, 151.2094), '')

http://stackoverflow.com/q/46868630
has title: Python: How to download Excel file from page
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80684897
score: 1
linked to: http://stackoverflow.com/q/13137817
has comment: http://stackoverflow.com/comment/80684596
tagged with: excel
has answer: http://stackoverflow.com/a/46870106
type: Question
has answer: http://stackoverflow.com/a/46870164
has body: Go to this url https://www.horseracebase.com/horse-racing-results.php?year=2005&amp;month=3&amp;day=15 (username = TrickyBen | password = TrickyBen123) Notice that there is a Download Excel button (in Red) I want to download the excel file and turn it into a pandas dataframe. I want to do it programatically (ie. from the script, not by manually clicking around the website). How would I do this? This code will get you logged in as TrickyBen, and make a request to the website API... import requests from lxml import html from requests import Session import pandas as pd import shutil raceSession = Session() LoginDetails = {'login': 'TrickyBen', 'password': 'TrickyBen123'} LoginUrl = 'https://www.horseracebase.com/horse-racing-results.php?year=2005&amp;month=3&amp;day=15/horsebase1.php' LoginPost = raceSession.post(LoginUrl, data=LoginDetails) RaceUrl = 'https://www.horseracebase.com/excelresults.php' RaceDataDetails = {"user": "41495", "racedate": "2005-3-15", "downloadbutton": "Excel"} PostHeaders = {"Content-Type": "application/x-www-form-urlencoded"} Response = raceSession.post(RaceUrl, data=RaceDataDetails, headers=PostHeaders) Table = pd.read_table(Response.text) Table.to_csv('blahblah.csv') If you inspect element, you'll notice that the relevant element looks like this... &lt;form action="excelresults.php" method="post"&gt; &lt;input type="hidden" name="user" value="41495"&gt; &lt;input type="hidden" name="racedate" value="2005-3-15"&gt; &lt;input type="submit" class="downloadbutton" value="Excel"&gt; &lt;/form&gt; I get this error message... Traceback (most recent call last): File "/Users/Alex/Desktop/DateTest/hrpull.py", line 20, in &lt;module&gt; Table = pd.read_table(Response.text) File "/Library/Python/2.7/site-packages/pandas/io/parsers.py", line 562, in parser_f return _read(filepath_or_buffer, kwds) File "/Library/Python/2.7/site-packages/pandas/io/parsers.py", line 315, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/Library/Python/2.7…
answer count: 2
upvote count: 1

http://stackoverflow.com/q/46789803
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/46789877
tagged with: dictionary
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1247486
tagged with: loops
has answer: http://stackoverflow.com/a/46789877
has comment: http://stackoverflow.com/comment/80526051
has comment: http://stackoverflow.com/comment/80527948
type: Question
has body: I came across a few articles and StackOverflow discussions where it is usually recommended to use list comprehension while dealing with lists. I usually come across a common loop structure where I have a list and I have to process it and store the results in a new list. So something like (For the sake of an example): 1) create a big list of strings for playing around purpose from random import choice from string import ascii_uppercase import time oldlist = ([''.join(choice(ascii_uppercase) for i in range(10)) for x in range(1000000)]) 2) process it using loop, list comprehension, and maps loop variant 1: start_time = time.time() newlist = [] for word in oldlist: newlist.append(word.lower()) print(time.time()-start_time) # 0.1368732452392578 loop variant 2: start_time = time.time() newlist = [] append = newlist.append for word in oldlist: append(word.lower()) print(time.time()-start_time)# 0.1112520694732666 list comp: start_time = time.time() newlist = [word.lower() for word in oldlist] print(time.time()-start_time) # 0.07511067390441895 map: start_time = time.time() newlist = map(str.lower, oldlist) print(time.time()-start_time) # 3.0994415283203125e-06 Can I assume that in such situation map should always be used as its faster than the rest? List comprehension is considered more readable according to various articles but should readability be the first priority or a significant amount of speed? Note: I just took an average of five iterations so these times values might change a bit. However, it gives us an indication. Python version: 3
has title: why not always use map if its faster than the rest (list comprehension, loop (various variants))?
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/80527023
duplicate of: http://stackoverflow.com/q/1247486
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80530276
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/46835565
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52742453
has title: Using matrices as input for Platypus MOEA
type: UnansweredQuestion
has body: I am new to Object-Oriented Programming and Optimisation and due to the lack of proper documentation for Platypus, I am forced to ask this question. I am trying to use NSGAII on Platypus for a maximisation problem for airfoil optimisation. My initial population is an array (say [100 x 13]). I need to evaluate every row of the array with my evaluation function. Any leads on finding useful documentation or a solution for this is appreciated. Thanks in advance.
tagged with: python
score: 3
downvote count: 0
tagged with: genetic-algorithm
type: Question
tagged with: platypus-optimizer
tagged with: optimization
upvote count: 3

http://stackoverflow.com/a/46868856
score: 1
has comment: http://stackoverflow.com/comment/80687739
has comment: http://stackoverflow.com/comment/80685109
downvote count: 0
has comment: http://stackoverflow.com/comment/80685140
has body: I will comment it so you can understand it: def find_positive(lst): for index, item in enumerate(lst): # Loop that tracks index and item value if item &gt; 0: # If the item is bigger than 0... return index # Return the index of that item return None # Returns None otherwise The instructions are a bit unclear as if you need to return the index or the value of the first positive item. If you want to return the value instead and not the index, then you should change the found = index and set it to found = item. Here is the documentation for Enumerate and how it works. Update after comments: This is an example of how returning None could be useful. my_variable_name = find_positive([-4, -2, 0, 1, 2, 3, 4]) # Call the function if my_variable_name is None: # Check if None was returned print("hey, no positives found") else: print("I found {} as first positive".format(my_variable_name)) Before you ask, {} is a placeholder to format strings. That way we can build more readable strings than if you insert code in the middle of a string.
has comment: http://stackoverflow.com/comment/80684913
type: Answer
has comment: http://stackoverflow.com/comment/80684904
upvote count: 1
answers question: http://stackoverflow.com/q/46868826
has comment: http://stackoverflow.com/comment/80685496

http://stackoverflow.com/q/46851971
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80652714
tagged with: qtextbrowser
score: 1
has body: I am building a grid of QTextEdit with HTML Subset to show some data within an interface in PyQt. At the moment I get the GridLayout and the QFrame that contains it doing whatever they want and there is no way for me to make them fit the QTextEdit size. I plaid with SizePolicy but does not work. see from the image how extra space appears on the side of each QText and how the GridLayout cuts the QTextEdit in height. The only way to make it work is if I set the correct QFrame size to make everything fit, but being that the size of the QTextEdit is customizable, I would like the QFrame to simply fit whatever it has to contain instead of getting free will +_+ Notice that the GridLayout is usually bigger than the mainwindow so it will not need to fit the window hence why need a scrollArea. What I do not want: As it should be: notice that the image I want has been obtained adding this line (in MainFrame()): container.resize(1100,1360) As I said I want to obtain the same behaviour but without specifying the dimension for QFrame, this should fit the content (the subset HTML tables) import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from random import * class Box(QTextBrowser): def __init__(self): super().__init__() self.setText(''' &lt;table border="0" cellspacing="0" cellpadding="5" style="background-color: rgba(119, 212, 212, 0.7);"&gt; &lt;tr&gt; &lt;td width="100"&gt; bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla &lt;/td&gt; &lt;tr&gt; &lt;tr&gt; &lt;td&gt; bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla &lt;/td&gt; &lt;tr&gt; &lt;/table&gt; ''') self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setContentsMargins(0,0,0,0) cstring =""" QTextBrowser { border: 0; background-color: #&lt;----&gt;; margin: 0px; padding-left:0; padding-top:0; padding-bottom:0; padding-right:0; } """ ncol = randi…
has comment: http://stackoverflow.com/comment/80652775
tagged with: pyqt5
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46854113
has comment: http://stackoverflow.com/comment/80653644
has comment: http://stackoverflow.com/comment/80653726
has comment: http://stackoverflow.com/comment/80655040
has comment: http://stackoverflow.com/comment/80652454
tagged with: pyqt
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80655653
has title: How to Pack with PyQt - how to make QFrame/Layout adapt to content
favorite count: 0
has comment: http://stackoverflow.com/comment/80655171
has comment: http://stackoverflow.com/comment/80652566
has comment: http://stackoverflow.com/comment/80652131
has answer: http://stackoverflow.com/a/46854113
tagged with: qgridlayout
tagged with: python
has comment: http://stackoverflow.com/comment/80652866

http://stackoverflow.com/a/46880416
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46880365
has body: You can try this: number=list(input("Print number")) final_list = ' '.join(a+''.join("0" for b in range(len(number)-i-1)) for i, a in enumerate(number)) print(new_list) Output: '100 20 3'

http://stackoverflow.com/comment/80482827
type: QuestionComment
has text: @EamonnKenny I edited my post for you it's just another row of numbers.
comment on: http://stackoverflow.com/q/46768660
score: 0
type: Comment

user-interface
tags question: http://stackoverflow.com/q/46789053
tags question: http://stackoverflow.com/q/46857880
type: Tag
tags question: http://stackoverflow.com/q/46758698
tags question: http://stackoverflow.com/q/46762061
tags question: http://stackoverflow.com/q/46839394
tags question: http://stackoverflow.com/q/46888362
tag name: user-interface
tags question: http://stackoverflow.com/q/46876072

http://stackoverflow.com/q/46863602
answer count: 4
score: 2
downvote count: 0
tagged with: pivot-table
tagged with: python
has body: I want to get the frequency count of strings within a column. One one hand, this is similar to collapsing a dataframe to a set of rows that only reflects the strings in the column. I was able to solve this with a loop, but know there is a better solution. Example df: 2017-08-09 2017-08-10 id 0 pre pre 2 active_1-3 active_1 3 active_1 active_1 4 active_3-7 active_3-7 5 active_1 active_1 And want to get out: 2017-08-09 2017-08-10 pre 1 1 active_1 2 3 active_1-3 3 0 active_3-7 1 1 I searched a lot of forums but couldnt' find a good answer. I'm assuming a pivot_table approach is the right one, but couldn't get the right arguments to collapse a table that didn't have an obvious index for the output df. I was able to get this to work by iterating over each column, using value_counts(), and appending each value count series into a new dataframe, but I know there is a better solution. for i in range(len(date_cols)): new_values = df[date_cols[i]].value_counts() output_df = pd.concat([output_df , new_values], axis=1) Thanks!
has answer: http://stackoverflow.com/a/46863741
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46863931
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/46864423
has answer: http://stackoverflow.com/a/46863713
accepted answer: http://stackoverflow.com/a/46863713
has answer: http://stackoverflow.com/a/46864423
favorite count: 0
tagged with: pandas
has title: Find value counts within a pandas dataframe of strings

http://stackoverflow.com/comment/80558167
comment on: http://stackoverflow.com/q/46805254
has text: This is actually due to the fact that the original REPL does not require additional libraries to work (for example it does not use `GNU readline`) while other REPL contains additional libraries to support that "simple" feature (`ipython` runs with `prompt_toolkit`, a pure python replacement for `readline`). This is not a bug nor a feature, I think it is simply the result of the decision of limiting the number of dependencies for the compilation of the python interpreter.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46853192
answers question: http://stackoverflow.com/q/46852887
has comment: http://stackoverflow.com/comment/80653851
has comment: http://stackoverflow.com/comment/80654883
has comment: http://stackoverflow.com/comment/80654006
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/80654164
type: Answer
has comment: http://stackoverflow.com/comment/80653858
has body: The truth value of an array with more than one element is ambiguous looks like a numpy error message. If a is a numpy ndarray and b contains the values you are testing for, you can do it like this. import numpy as np a = np.arange(6) b = np.array([6,2,9]) if np.any(a == b[:, None]): ... or np.any(a[:,None] == b) Which makes use of broadcasting. Your exception can be reproduced using my arrays ... &gt;&gt;&gt; if a == b[:, None]: pass Traceback (most recent call last): File "&lt;pyshell#281&gt;", line 1, in &lt;module&gt; if a == b[:, None]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() &gt;&gt;&gt;
upvote count: 1
has comment: http://stackoverflow.com/comment/80664175

http://stackoverflow.com/q/46843833
has body: I am new of python. i want to read a value from the text file. for example my text fileis textfile host="host" dbname="dbname" uname="uname" pwd="pwd" now i want to read these values from the file like below and use in the python script host_name=host(host valuefrom text file ) same for all values. how can we read a file and how to read value alone from the text file. Thanks in advance
accepted answer: http://stackoverflow.com/a/46843922
has comment: http://stackoverflow.com/comment/80635283
has answer: http://stackoverflow.com/a/46843922
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/80635180
tagged with: python-3.x
has title: how to read a value from text HI file using python?
tagged with: python
type: AnsweredQuestion
tagged with: file
type: Question

http://stackoverflow.com/q/46868866
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/46868914
has body: I am trying to create a simple logistic regression model in tensorflow with only one class. However, for some reason, the tf.sigmoid function is returning an array type rather than a scalar. The type of value returned from the cost function is an np.ndarray() The shape is (3390,2) I can't figure out why the tf.sigmoid function would return an array type rather than a scalar... any help appreciated. Here is my code: #!/usr/bin/env python3 import tensorflow as tf import numpy as np import pandas as pd from sklearn import preprocessing from sklearn import model_selection import matplotlib.pyplot as plt import seaborn as sns import sys sns.set(style='white') sns.set(style='whitegrid',color_codes=True) bank_data = pd.read_csv('data/bank.csv',header=0,delimiter = ';') bank_data = bank_data.dropna() bank_data.drop(bank_data.columns[[0,3,8,9,10,11,12,13]],axis=1,inplace=True) data_set = pd.get_dummies(bank_data,columns = ['job','marital','default','housing','loan','poutcome']) data_set.drop(data_set.columns[[14,27]],axis=1,inplace=True) data_set_y = data_set['y'] data_set_y = data_set_y.replace(('yes','no'),(1.0,0.0)) data_set_X = data_set.drop(['y'],axis=1) num_samples = data_set.shape[0] num_features = data_set_X.shape[1] num_labels = 1 X = tf.placeholder('float',[None,num_features]) y = tf.placeholder('float',[None,num_labels]) W = tf.Variable(tf.zeros([num_features,2]),dtype=tf.float32) b = tf.Variable(tf.zeros([1]),dtype=tf.float32) train_X,test_X,train_y,test_y = model_selection.train_test_split(data_set_X,data_set_y,random_state=0) train_y = np.reshape(train_y,(-1,1)) prediction = tf.add(tf.matmul(X,W),b) cost = tf.sigmoid(prediction) optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(cost) num_epochs = 1000 print ('Shape of train_y is: ',train_y.shape) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(num_epochs): _,l = sess.run([optimizer,cost],feed_dict = {X: train_X, y: train_y}) if epoch % 50 == 0: print (type(l…
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/46868909
type: UnansweredQuestion
tagged with: python
has title: Tensorflow tf.sigmoid() returning an array rather than a scalar
has answer: http://stackoverflow.com/a/50006400

http://stackoverflow.com/comment/80591427
comment on: http://stackoverflow.com/q/46821634
has text: No it doesn't..
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80598017
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46817456
has text: When styling multiple cells I'd advise using Named Styles. Also, try and avoid things like `ws['"%d:%d" % (i, i)]` and use `ws.iter_rows()` or `ws.iter_cols()` instead.

http://stackoverflow.com/a/53491715
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/93853958
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/46890665
has body: @bauman.space provided the most informative and useful explanation of this bson/ pymongo import issue in this thread: pymongo>=2.7.1 directive overwrites your bson installation from https://github.com/mongodb/mongo-python-driver Do not install the "bson" package from pypi. PyMongo comes with its own bson package; doing easy_install bson or pip install bson installs a third-party package that is incompatible with PyMongo. assuming you really want to use the 3rd party bson, you'll need to pip uninstall bson (removes the overwritten bson that landed via pymongo package) pip install bson (reinstalls the py-bson package) or you could patch the pymongo install to remove the collections.abc line (evidently you don't really need it?), but messing with production packaged code is questionable. pymongo module https://github.com/mongodb/mongo-python-driver/blob/master/bson/py3compat.py#L22-L25 py-bson module you are trying to use. https://github.com/py-bson/bson/blob/master/bson/py3compat.py#L22-L24

http://stackoverflow.com/q/46762708
tagged with: python
tagged with: bottle
has body: I'd like to check the operation of 'Web Scraping with Pytho code' with a web browser. In the for statement, I was able to get the expected results. But the while statement, I can't able to get the expected results. scrape by tracing the url of wikipedia environment ・Python 3.6.0 ・bottle 0.13-dev ・mod_wsgi-4.5.15 Apache error log No output ERR_EMPTY_RESPONSE. Scraping does not finish processing index.py from urllib.request import urlopen from bs4 import BeautifulSoup from bottle import route, view import datetime import random import re @route('/') @view("index_template") def index(): random.seed(datetime.datetime.now()) html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon") internalLinks=[] links = getLinks("/wiki/Kevin_Bacon") while len(links) > 0: newArticle = links[random.randint(0, len(links)-1)].attrs["href"] internalLinks.append(newArticle) links = getLinks(newArticle) return dict(internalLinks=internalLinks) def getLinks(articleUrl): html = urlopen("http://en.wikipedia.org"+articleUrl) bsObj = BeautifulSoup(html, "html.parser") return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$")) In the for statement, I was able to get the expected results. Result of web browser output ['/wiki/Michael_C._Hall', '/wiki/Elizabeth_Perkins', '/wiki/Paul_Erd%C5%91s', '/wiki/Geoffrey_Rush', '/wiki/Virtual_International_Authority_File'] index.py from urllib.request import urlopen from bs4 import BeautifulSoup from bottle import route, view import datetime import random import re @route('/') @view("index_template") def index(): random.seed(datetime.datetime.now()) html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon") internalLinks=[] links = getLinks("/wiki/Kevin_Bacon") for i in range(5): newArticle = links[random.randint(0, len(links)-1)].attrs["href"] internalLinks.append(newArticle) return dict(internalLinks=internalLinks) def getLinks(articleUrl): html = urlopen("http://en.wikipedia.org"+articleUrl) bsObj = BeautifulSoup(…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80511027
upvote count: 1
has title: In the for statement, I was able to get the expected results. But why can not I get the expected results with the while statement?
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/46782415
answer count: 1
has comment: http://stackoverflow.com/comment/80511051
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80550389
tagged with: beautifulsoup
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/46782415

http://stackoverflow.com/comment/80535946
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46790390
has text: @scnerd Yes, I tried but get the same error.Is it the json file inner mistakes?I just download the file from here to practice [link](https://www.yelp.com/dataset/documentation/json)

http://stackoverflow.com/comment/80553350
score: 0
comment on: http://stackoverflow.com/q/46803291
type: Comment
type: QuestionComment
has text: I'm kinda new to this website sorry

http://stackoverflow.com/comment/80756311
has text: It's not a standard lib in Python 2 nor 3 BTW.
comment on: http://stackoverflow.com/q/46904783
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46893307
tagged with: python
has answer: http://stackoverflow.com/a/46901057
score: 2
has comment: http://stackoverflow.com/comment/80734727
has answer: http://stackoverflow.com/a/46897554
type: Question
has comment: http://stackoverflow.com/comment/80734838
downvote count: 0
has comment: http://stackoverflow.com/comment/80744436
favorite count: 0
has comment: http://stackoverflow.com/comment/80744535
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/80878767
has title: flag and summarize gaps per month in visit logs (churns)
upvote count: 2
type: UnansweredQuestion
has body: I have a df that looks like this: visits ={'someID':[111,111,111,222,222,222,333,333], 'Month':[1,3,5,1,2,4,3,4], 'visits':[4,10,5,2,2,2,5,5]} df = pd.DataFrame.from_dict(visits) someID Month Visits 111 1 4 111 3 10 111 5 5 222 1 2 222 2 2 222 4 2 333 3 5 333 4 5 The data frame should be interpreted as: The user 111 visited the month 1 but churned on month 2 and returned on month 3, churned on month 4 and returned on 5. The user 222 visited the month 1 and 2, churned on month 3 and returned on month 4 THe user 333 first visited on month 3 ( he shouldn't appear as churn on month 1 and 2). What would be an efficient way of summarizing the number of churns per month and the number of new visits per month? churn = has visited before but didn't visit the current month new visit = first-time visit desired output:( Month Churns New_visits Totals 2 1 0 1 3 1 1 2 4 1 0 2 5 2 0 1
has answer: http://stackoverflow.com/a/46895733

http://stackoverflow.com/a/46813867
score: 0
type: Answer
has body: I am not a Python expert but if I were writing this in C# I would nest for's instead of using the while. In my experience you should use while only when it's appropriate and in this case we have a much easier way of looping this code. You've already determined the rows with your first loops so the next steps to display columns would be to search those rows for the columns. If you want to stick with the "i=0" then foreach column is the way to go. However, foreach is more taxing on your program than just using for and while isn't needed(for is twice as fast as foreach). You want to avoid the possibility of going into the infinite loop hell. Again not a python expert but using just a for statement to find the columns, as Daniel above suggested, seems like it would work great here.
answers question: http://stackoverflow.com/q/46813432

http://stackoverflow.com/a/46752610
score: 0
has comment: http://stackoverflow.com/comment/80488650
has comment: http://stackoverflow.com/comment/80451157
has comment: http://stackoverflow.com/comment/80454287
has body: You can configure python interpreter for PyCharm in Settings > Project Interpreter. Or to reconfigure default interpreter Settings > Default Project > Project Interpreter.
has comment: http://stackoverflow.com/comment/86788437
type: Answer
answers question: http://stackoverflow.com/q/46752540

http://stackoverflow.com/comment/80592621
comment on: http://stackoverflow.com/a/46803941
score: 0
type: Comment
has text: Thanks @StuartBuckingham. TkInter script I came across has helped tremendously. Appreciate the answers of course. What a collaborative community. I will continue to search for more material instead.
type: AnswerComment

http://stackoverflow.com/a/67883521
has body: I had the same problem and change my directory as follow: import os os.chdir('Your Path (GitHub project, ...)') !pip install -r requirements.txt instead of cd path pip install -r requirements.txt
downvote count: 1
has comment: http://stackoverflow.com/comment/126299960
has comment: http://stackoverflow.com/comment/119992348
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/46854451
type: Answer

http://stackoverflow.com/comment/80638122
score: 0
comment on: http://stackoverflow.com/q/46844803
type: Comment
type: QuestionComment
has text: Why do you want to create a dictionary anew every time you call `getMyDict`? If you want to encapsulate the dict, you can use a closure. Is that what you want?

http://stackoverflow.com/a/46833192
answers question: http://stackoverflow.com/q/46832485
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: To generate date ranges like the ones you describe in your explanation (rather than the ones shown in your sample output), you could use Pandas functionality like so: import pandas as pd months = pd.Series([ '201401','201402','201403','201404','201405','201406', '201407','201408','201409','201410','201411','201412', '201501','201502','201503','201504','201505','201506', '201507','201508','201509','201510','201511','201512' ]) # this function converts strings like "201401" # to datetime objects, and then uses DateOffset # and date_range to generate a sequence of months def date_range(month): date = pd.to_datetime(month, format="%Y%m") return pd.date_range(date, date + pd.DateOffset(months=11), freq='MS') # apply function to original Series # and then apply pd.Series to expand resulting arrays # into DataFrame columns month_ranges = months.apply(date_range).apply(pd.Series) # sample of output: # 0 1 2 3 4 5 \ # 0 2014-01-01 2014-02-01 2014-03-01 2014-04-01 2014-05-01 2014-06-01 # 1 2014-02-01 2014-03-01 2014-04-01 2014-05-01 2014-06-01 2014-07-01 # 2 2014-03-01 2014-04-01 2014-05-01 2014-06-01 2014-07-01 2014-08-01 # 3 2014-04-01 2014-05-01 2014-06-01 2014-07-01 2014-08-01 2014-09-01
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46832485
has comment: http://stackoverflow.com/comment/80614336

http://stackoverflow.com/comment/130795718
has text: You can use the subprocess module (https://docs.python.org/3/library/subprocess.html) to execute shell commands.
comment on: http://stackoverflow.com/q/46824143
score: 0
type: Comment
type: QuestionComment

portforwarding
tags question: http://stackoverflow.com/q/46898941
type: Tag
tag name: portforwarding

http://stackoverflow.com/comment/80694807
type: Comment
has text: @cclsr The reason you you *can remove* is that a dictionary is mutable (can be changed). Again, when you run `d1.copy()` you are creating a `new, totally different` dictionary. Changes in one of them have nothing to do with the other. *BUT*, the list inside was not copied, it's just referenced by both! So here, you will change the `list`, which happens to be pointed to by both dicts.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46873806

http://stackoverflow.com/q/46878186
favorite count: 0
has answer: http://stackoverflow.com/a/46879838
has body: I am getting the following error when trying to run some code through Spark-Submit or Zeppelin: "_pickle.PicklingError: args[0] from __ newobj __ args has the wrong class" I have looked around at posts with the same problem and haven't much insight into this issue. The traceback (included below) points to one of the udfs I use: udf_stop_words = udf(stop_words, ArrayType(StringType())) def stop_words(words): return list(word.lower() for word in words if word.lower() not in stopwords.words("english")) Both the input and output of the function are lists of strings. These are 3 rows from the input: [Row(split_tokenized_activity_description=['A', 'delightful', '45', 'minute', 'Swedish', 'style', 'massage']), Row(split_tokenized_activity_description=['A', 'more', 'intense', '45', 'minute', 'version', 'of', 'a', 'Swedish', 'style', 'massage']), Row(split_tokenized_activity_description=['A', 'relaxing', '45', 'minute', 'Swedish', 'style', 'massage']) This is a snippet of the code I'm working with. def special_car(x): # remove the special character and replace them with the stop word " " (space) return [re.sub('[^A-Za-z0-9]+', ' ', x)] # Create UDF from function udf_special_car = udf(special_car, ArrayType(StringType())) # Function to remove stops words def stop_words(words): return list(word.lower() for word in words if word.lower() not in stopwords.words("english")) udf_stop_words = udf(stop_words, ArrayType(StringType())) # Load in data df_tags = spark.sql("select * from database") # Remove special Characters df1_tags = df_tags.withColumn('tokenized_name', udf_special_car(df_tags.name)) df2_tags = df1_tags.withColumn('tokenized_description', udf_special_car(df1_tags.description)) # Select only relevent columns df3_tags = df2_tags.select(['tag_id', 'tokenized_name', 'tokenized_description']) # Tokenize tag_name and tag_desc (Seperate on spaces) (This uses the pyspark.sql.split function) df4_tags = df3_tags.withColumn('split_tokenized_name', split(df3_tags['tokenized_name']…
upvote count: 2
type: UnansweredQuestion
tagged with: pickle
tagged with: python
downvote count: 1
tagged with: apache-zeppelin
score: 1
has title: Pickling Error with Spark-Submit "_pickle.PicklingError: args[0] from __newobj__ args has the wrong class"
has comment: http://stackoverflow.com/comment/80703856
type: Question
has answer: http://stackoverflow.com/a/46967956
tagged with: user-defined-functions
answer count: 2
tagged with: pyspark

http://stackoverflow.com/comment/112999735
has text: this is working and recommended way to stop the spider, it may be too late to tell you but definitely not for the people who want a proper solution to this problem.
comment on: http://stackoverflow.com/a/63871334
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46763300
has title: python - looping search from and to specific delimiting lines in a text file
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46766297
type: UnansweredQuestion
has body: I'm a newbie python learner and got stuck with this problem... I would appreciate any of your expert advice and help about doing a python script that could read and search thru a config file by looking on specific delimiters in a group/set of lines as below. start delimiter: ^vpls\s\d+ end delimiter: ^!$ ##This is an example subset of an Alcatel router config: ! vpls xxx sdp 1.1.1.1 backup lsp LSP-1 ... #some other settings here (not needed) exit sdp 2.2.2.2 lsp LSP-2 ... #some other settings here (not needed) exit ! vpls yyy sdp 1.1.1.1 backup lsp LSP-1 ... #some other settings here (not needed) exit sdp 2.2.2.2 lsp LSP-2 ... #some other settings here (not needed) exit ! what i wanted to achieve, please note that backup is transferred on the last item of the sequence for standard formatting after exporting to csv: vpls xxx : sdp 1.1.1.1 : lsp LSP-1 : backup vpls xxx : sdp 2.2.2.2 : lsp LSP-2 : vpls yyy : sdp 1.1.1.1 : lsp LSP-1 : backup vpls yyy : sdp 2.2.2.2 : lsp LSP-2 :
downvote count: 1
type: Question
score: -1

http://stackoverflow.com/a/46779142
accepted answer of: http://stackoverflow.com/q/46778655
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/46778655
has body: this /%3Fnext%3D/test/ is equal to /?next=/test/ you just need to pass the word test. In the return should be something like: return redirect_to_login('/test/') More information about redirect_to_login https://docs.djangoproject.com/en/1.11/topics/auth/default/#helper-functions
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/46774108
type: UnansweredQuestion
tagged with: python
tagged with: jinja2
type: Question
tagged with: tornado
has body: I'm running tornado on a simple web app. Currently, I'm trying to create a user module to display logged in user info on the navbar.html component which is included on base.html. I created a uimodules.py file, added my Menu class import tornado.web class Menu(tornado.web.UIModule): def render(self): return ' THE MODULE HAS ARRIVED ' Then imported this in my app.py from uimodules import Menu in my settings dict I have "ui_modules": {"Menu": Menu} My understanding is that now, the Menu module should be accessible to my entire app and I should be able to add ... {% module Menu() %} ... tag to include this module. When I run the app I get the following error. Traceback (most recent call last): File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/tornado/web.py", line 1509, in _execute result = method(*self.path_args, **self.path_kwargs) File "app.py", line 69, in get self.render_template("/pages/index.html", {"login": login, "user": user}) File "app.py", line 60, in render_template self.write(template.render(**context)) File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render return original_render(self, *args, **kwargs) File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render return self.environment.handle_exception(exc_info, True) File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise raise value.with_traceback(tb) File "/Users/devmode/Documents/projects/tornado_starter/myapp/templates/components/navbar.html", line 6, in template {% module Menu() %} File "/Users/devmode/.virtualenvs/tornado_starter/lib/python3.6/site-packages/jinja2/environment.py", line 1005, in render return concat(self.ro…
score: 0
answer count: 1
has title: python tornado.web.uimodules not rendering with jinja2
has answer: http://stackoverflow.com/a/46779493

http://stackoverflow.com/a/46869289
has comment: http://stackoverflow.com/comment/80686520
type: Answer
has comment: http://stackoverflow.com/comment/80685964
has body: Numpy can create vectorized functions for performing mapping operations on arrays. I'm not sure which method here is going to have the best performance, so I've timed my approach with timeit. I would recommend trying out a couple of the other approached provided if you want to figure out what has the best performance. # Function to be vectorized def map_func(val, dictionary): return dictionary[val] if val in dictionary else val # Vectorize map_func vfunc = np.vectorize(map_func) # Run print(vfunc(a, d)) You can time this by doing: from timeit import Timer t = Timer('vfunc(a, d)', 'from __main__ import a, d, vfunc') print(t.timeit(number=1000)) My result for this approach was about 0.014 s. Edit: For kicks, I tried this out on (1024, 2048) size numpy array of random numbers from -10 to 10, with your same dictionary. It took about a quarter of a second for a single array. Unless you are running a lot of these arrays, it may not really be worth optimizing if that's an acceptable level of performance.
answers question: http://stackoverflow.com/q/46868855
score: 0

http://stackoverflow.com/comment/80534408
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46793574
has text: I'm curious; does `apply` run at ~the same speed as a python `for` loop in this case (i.e. not vectorized)? I was under the impression that `apply` does, but cant test atm.

http://stackoverflow.com/a/46759148
score: 1
answers question: http://stackoverflow.com/q/46758894
has body: Either you import the list variable from the other module (from othermodule import list_var), or import the module and write the variable as othermodule.list_var. Either way, you can use it like any other list.
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/80464656
downvote count: 0

http://stackoverflow.com/a/53143332
answers question: http://stackoverflow.com/q/46902367
type: Answer
score: 23
has body: This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message: # incorrect weights = list(range(1, 129)) + list(range(128, 0, -1)) mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3] # TypeError: only integer scalar arrays can be converted to a scalar index It turns out I needed to turn weights, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works: # correct weights = np.array(list(range(1, 129)) + list(range(128, 0, -1))) mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
downvote count: 0
upvote count: 23

http://stackoverflow.com/a/46844497
has comment: http://stackoverflow.com/comment/80638894
type: AcceptedAnswer
downvote count: 1
has body: OpenCV uses NumPy arrays as the fundamental datatype to represent images. Indeed NumPy has a resize method to "resize" the data, but you're not using it properly. By consulting the documentation, the numpy.resize method requires you to reverse the order of your parameters. The input array goes first followed by the desired size. You have it almost correct - just swap the order of the arguments. However, I don't believe this is what you're looking for since numpy.resize fills in the output array with repeated copies of the input - especially since you're doing this for facial recognition. I believe you want to resize the contents of the image to fit the desired size, not fill in the array with repeated copies of the input with its original size intact. Therefore, cv2.resize is a better fit for you. You call it the same way as numpy.resize: resize_image = cv2.resize(img, (200,200)) Take note that the default method of resizing uses bilinear interpolation. If you want to use another method, you will have to provide an additional argument interpolation to do that. If you wanted to perform cubic interpolation, you would do: resize_image = cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC) Check the documentation on cv2.resize for more details: https://docs.opencv.org/3.0-beta/modules/imgproc/doc/geometric_transformations.html#resize
upvote count: 9
accepted answer of: http://stackoverflow.com/q/46844444
has comment: http://stackoverflow.com/comment/80662419
has comment: http://stackoverflow.com/comment/80663962
type: Answer
answers question: http://stackoverflow.com/q/46844444
score: 8
has comment: http://stackoverflow.com/comment/80638187

http://stackoverflow.com/a/46880729
upvote count: 3
accepted answer of: http://stackoverflow.com/q/46880709
score: 3
has body: Try changing: data = line.split(',') to: data = line.strip().split(',')
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46880709

http://stackoverflow.com/comment/80746330
has text: @JoeSmith: Yes! Complete your parallelization check: do you have the hardware resources to handle those file sets in parallel, or are they contending for I/O resources? Is "handling" a heavy processing load, where they'd compete for processor time?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46899206
type: Comment

http://stackoverflow.com/comment/80707983
has text: @Parfait makes sense. Floating point operations accumulate errors in their least significant bits on different architectures, which is why it's best practice to use `np.isclose()` and `np.allclose()` to compare floating point numbers instead of equality. I'll update my answer.
type: Comment
comment on: http://stackoverflow.com/a/46879774
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80529668
has text: basically for one Name I have 1 id only and for 1 id I can have 1 Name only
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46791400

http://stackoverflow.com/q/46881560
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/46882073
type: Question
has answer: http://stackoverflow.com/a/46882282
answer count: 2
has comment: http://stackoverflow.com/comment/80713110
tagged with: javascript
has body: I am trying to change the element using selenium using send keys but it is not changing. I also tried using execute_script, but the value is not changing. i am trying to change to value = R driver.find_element_by_name('wlw-select_key:{actionForm.terminal}').send_keys('R') ALL 1 2 3 4 5 6 7 8 9
score: 0
tagged with: python
has title: Trying to change the value of the element using selenium
tagged with: pycharm

http://stackoverflow.com/comment/80603216
type: QuestionComment
comment on: http://stackoverflow.com/q/46827988
score: 2
has text: where is your attempt, please?
type: Comment

http://stackoverflow.com/q/46822016
has title: How to get past hour results from google custom search api in Python?
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: Question
has body: I want to know how to tweak dateRestrict variable to find articles posted in last half an hour. However, I am unable to do so - any help would be appreciated. from googleapiclient.discovery import build import pprint my_api_key = "Google API key" my_cse_id = "Custom Search Engine ID" def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute() return res['items'] results = google_search( 'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id,dateRestrict=d1, num=10) for result in results: pprint.pprint(result)
downvote count: 0
tagged with: jquery

http://stackoverflow.com/q/46856314
has comment: http://stackoverflow.com/comment/80660442
tagged with: python
score: 2
type: AnsweredQuestion
has title: Using Mann Kendall in python with a lot of data
has answer: http://stackoverflow.com/a/68442829
downvote count: 0
has body: I have a set of 46 years worth of rainfall data. It's in the form of 46 numpy arrays each with a shape of 145, 192, so each year is a different array of maximum rainfall data at each lat and lon coordinate in the given model. I need to create a global map of tau values by doing an M-K test (Mann-Kendall) for each coordinate over the 46 years. I'm still learning python, so I've been having trouble finding a way to go through all the data in a simple way that doesn't involve me making 27840 new arrays for each coordinate. So far I've looked into how to use scipy.stats.kendalltau and using the definition from here: https://github.com/mps9506/Mann-Kendall-Trend EDIT: To clarify and add a little more detail, I need to perform a test on for each coordinate and not just each file individually. For example, for the first M-K test, I would want my x=46 and I would want y=data1[0,0],data2[0,0],data3[0,0]...data46[0,0]. Then to repeat this process for every single coordinate in each array. In total the M-K test would be done 27840 times and leave me with 27840 tau values that I can then plot on a global map. EDIT 2: I'm now running into a different problem. Going off of the suggested code, I have the following: for i in range(145): for j in range(192): out[i,j] = mk_test(yrmax[:,i,j],alpha=0.05) print out I used numpy.stack to stack all 46 arrays into a single array (yrmax) with shape: (46L, 145L, 192L) I've tested it out and it calculates p and tau correctly if I change the code from out[i,j] to just out. However, doing this messes up the for loop so it only takes the results from the last coordinate in stead of all of them. And if I leave the code as it is above, I get the error: TypeError: list indices must be integers, not tuple My first guess was that it has to do with mk_test and how the information is supposed to be returned in the definition. So I've tried altering the code from the link above to change how the data is returned, but I keep getting errors relating back …
type: Question
upvote count: 2
tagged with: numpy
tagged with: arrays
linked to: http://stackoverflow.com/q/24885092
has answer: http://stackoverflow.com/a/47190036
accepted answer: http://stackoverflow.com/a/47190036
tagged with: statistics
has answer: http://stackoverflow.com/a/46856902
possible better answer: http://stackoverflow.com/a/46856931
has answer: http://stackoverflow.com/a/46856931
answer count: 4
tagged with: jupyter-notebook
favorite count: 0
linked to: http://stackoverflow.com/q/16406814

http://stackoverflow.com/comment/80636384
type: AnswerComment
type: Comment
has text: OP posted some update. See OP.
score: 0
comment on: http://stackoverflow.com/a/46843533

http://stackoverflow.com/a/46821684
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/46821562
has comment: http://stackoverflow.com/comment/80605554
has body: You can use itertools.chain.from_iterable &gt;&gt;&gt; import itertools &gt;&gt;&gt; lst = [((1,2), 'a'), ((3,4), 'b')] &gt;&gt;&gt; s = set(itertools.chain.from_iterable(pair for pair, _ in lst)) &gt;&gt;&gt; s set([1, 2, 3, 4])
answers question: http://stackoverflow.com/q/46821562
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80644161
type: Answer
has comment: http://stackoverflow.com/comment/80591728

http://stackoverflow.com/a/46827030
answers question: http://stackoverflow.com/q/46826860
type: Answer
has body: I really believe that your function get_indices is already almost the answer to your problem - just when you find the element - change it! =) but as an answer - use recursion (as you probably used in find_indices) def set_element(lst, index, value): if(len(index)==1): lst[index[0]] = value else: set_element(lst[index[0]],index[1:],value)
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/80602439
downvote count: 0

http://stackoverflow.com/q/46839732
type: UnansweredQuestion
tagged with: qt-signals
type: Question
has title: Getting the emitted value by pyqtsignal in QThreads in PyQt
has comment: http://stackoverflow.com/comment/80627861
tagged with: pyqt
score: 0
tagged with: python
tagged with: qthread
has comment: http://stackoverflow.com/comment/80627731
has comment: http://stackoverflow.com/comment/80628935
has body: I am trying to get the value emitted by Class Qthread's signal without using the function I am calling alert box when the user chooses to exit and press [X] button on GUI so I called this alert box by the means of threading to ensure that my GUI doesn't freeze. Below is the code for that: class ABC: def __init__(self): self.close = CloseThread() # Creating instance of QThread Class ........ ........ ........ def closeEvent(self, event): button = self.close.CloseResult self.close.start() if button == 1: event.accept() else: event.ignore() class CloseThread(QThread): """Threading class which is emitting the return value according to the choice of the user(When the message appears, if the user chooses 'Ok' then return value is 1 and if the user chooses 'Cancel'return value is 2)""" CloseResult = QtCore.pyqtSignal(object) def __init__(self): QThread.__init__(self) def close(self): button = win32api.MessageBox(0, 'Do you want to Exit?', 'Message') self.CloseResult.emit(button) def run(self): self.close() I know I can get the emitted value by self.close.CloseResult.connect(self.fn_name) instead of using self.close.CloseResult but I don't want to call another function because here I am extending the scope of closeEvent function so I don't want to call another function.(Actually by calling another function things aren't working out as they are supposed to) Note: By using self.close.CLoseResult I am getting an object so is there any way to access this object's value or not? So is there any way I can get emitted value just in a variable without having to call any other function?
answer count: 0

http://stackoverflow.com/comment/80641984
has text: Is it there when you inspect the page ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46847282
score: 0

http://stackoverflow.com/a/69541372
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46896093
has body: From the directory where you have your virtual environment (e.g. myenv) you need to run the following command: .\myenv\Scripts\activate
score: 4
upvote count: 4

http://stackoverflow.com/comment/80753123
type: Comment
type: QuestionComment
has text: You are using a wrong data structure for whatever it is that you want to do. Dictionaries are more apt here
score: 1
comment on: http://stackoverflow.com/q/46903261

http://stackoverflow.com/a/46786277
upvote count: 100
has comment: http://stackoverflow.com/comment/80535993
has comment: http://stackoverflow.com/comment/101792996
has comment: http://stackoverflow.com/comment/92342109
has comment: http://stackoverflow.com/comment/104438519
score: 100
type: Answer
has comment: http://stackoverflow.com/comment/134631108
has comment: http://stackoverflow.com/comment/112144707
has comment: http://stackoverflow.com/comment/126684445
answers question: http://stackoverflow.com/q/46786211
accepted answer of: http://stackoverflow.com/q/46786211
has comment: http://stackoverflow.com/comment/111696921
has body: IIUIC, use value_counts() In [3361]: df.Firm_Name.str.split(expand=True).stack().value_counts() Out[3361]: Society 3 Ltd 2 James's 1 R.X. 1 Yah 1 Associates 1 St 1 Kensington 1 MMV 1 Big 1 &amp; 1 The 1 Co 1 Oil 1 Building 1 dtype: int64 Or, pd.Series(np.concatenate([x.split() for x in df.Firm_Name])).value_counts() Or, pd.Series(' '.join(df.Firm_Name).split()).value_counts() For top N, for example 3 In [3379]: pd.Series(' '.join(df.Firm_Name).split()).value_counts()[:3] Out[3379]: Society 3 Ltd 2 James's 1 dtype: int64 Details In [3380]: df Out[3380]: URN Firm_Name 0 104472 R.X. Yah &amp; Co 1 104873 Big Building Society 2 109986 St James's Society 3 114058 The Kensington Society Ltd 4 113438 MMV Oil Associates Ltd
has comment: http://stackoverflow.com/comment/84141110
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80620358
type: AnswerComment
type: Comment
has text: by the way, if i switch attack and defend for right and left, the first image doesnt change
comment on: http://stackoverflow.com/a/46815578
score: 0

http://stackoverflow.com/q/46896735
has comment: http://stackoverflow.com/comment/80744008
has comment: http://stackoverflow.com/comment/80740905
has comment: http://stackoverflow.com/comment/80741338
score: 0
has comment: http://stackoverflow.com/comment/80741290
has comment: http://stackoverflow.com/comment/80742462
tagged with: python
answer count: 0
tagged with: tensor
type: UnansweredQuestion
has title: Tensorflow, obtain new tensor from existing one
tagged with: reshape
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/80743846
has body: I have a tensor of this shape: [BATCH_SIZE, INPUT_SIZE] and I need to use it as input to a layer of lstm cells. In order to do that I need a tensor of this shape: [BATCH_SIZE, TIME_STEPS, INPUT_SIZE] but I can't simply reshape my first tensor, because in that way I'd "break" the input size. Am I right? How can I obtain the tensor I need?. EDIT: The tensor with shape [BATCH_SIZE, INPUT_SIZE] is the output of a maxpooling layer (after a reshape): convo_2 = convolutional_layer(convo_1_pooling, shape=[5, 5, 32, 64]) convo_2_pooling = max_pool_2by2(convo_2) conv_flat = tf.reshape(convo_2_pooling, shape=[-1, 64*25*50]) the conv_flat variable is the input the lstm layer.
has comment: http://stackoverflow.com/comment/80742406
has comment: http://stackoverflow.com/comment/80741117

http://stackoverflow.com/q/46776628
downvote count: 0
answer count: 1
has body: How to add SQL Server 2017 with the Machine Learning Services with Python and machine learning feature to existing sql server 2017.I had installed Sql Server 2017 without adding python features to it and now I need them? Can I add these features without reinstalling Sql Server?
tagged with: data-science
favorite count: 0
tagged with: sql-server
tagged with: python
has answer: http://stackoverflow.com/a/46777024
type: AnsweredQuestion
has title: Add Machine Learning Services with Python and machine learning feature to existing SQL Server 2017
upvote count: 2
tagged with: bigdata
tagged with: machine-learning
type: Question
accepted answer: http://stackoverflow.com/a/46777024
score: 2

http://stackoverflow.com/q/46903154
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/80783340
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80753310
has comment: http://stackoverflow.com/comment/80795194
has answer: http://stackoverflow.com/a/46924930
tagged with: python
has title: Concatenate Two RNN States in Tensorflow
tagged with: nlp
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46924930
has body: I am trying to concatenate two LSTM states together in tensor flow. Previously, this had been done with tf.concat, but this isn't working for me because I need to compute logits on the resulting state, and I am unable to iterate through the resulting state since the 'Tensor' object is not iterable. Here is what I am trying to do: outputs, fstate = tf.nn.dynamic_rnn(cell=lstm, inputs=rnn_inputs, sequence_length=lengths, dtype=tf.float32, time_major=False) outputs2, fstate2 = tf.nn.dynamic_rnn(cell=lstm2, inputs=rnn_inputs2, sequence_length=lengths2, dtype=tf.float32, time_major=False) newRnnState = tf.concat([fstate, fstate2], 1) logits = tf.matmul(tf.concat([f.h for f in newRnnState], 1), output_layer[0]) + output_bias[0] This returns an error: TypeError: 'Tensor' object is not iterable. Is there any way to do this so that I can concatenate two RNN states together and use them like this? Thanks
has comment: http://stackoverflow.com/comment/80796380
score: 1

http://stackoverflow.com/q/46783418
tagged with: sql-server
upvote count: 2
tagged with: google-maps
has title: Python update reverse geocoding data to sql table
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
answer count: 0
score: 1
tagged with: geojson
type: Question
has comment: http://stackoverflow.com/comment/80524487
has body: From this source I get to know to read lat long coordinate from a csv file and get the reverse geocoding done, but when I try to do the same but using source as sql table instead of csv file, it gives some syntactical error. reading data from sql table import pyodbc import urllib.request import urllib.parse import json cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=mydb;UID=test;PWD=abc@123;autocommit=True') cursor = cnxn.cursor() cursor.execute("select GEOCODE_ID, lat, longt from GEOCODE_TBL where JSON_str is NULL") ID=[] px_val=[] py_val=[] for row in cursor.fetchall(): ID.append(row[0]) px_val.append(row[1]) py_val.append(row[2]) #code to update the O/P from google reverse geocoding(JSON String) into table for i in range(1,len(px_val)): wp = urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&amp;sensor=false".format(px_val[i],py_val[i])) pw=wp.read().decode('utf-8') pw = json.loads(wp) cursor.execute("UPDATE GEOCODE_TBL SET JSON_str = ? WHERE GEOCODE_ID = ?", str(pw[i]),str(ID(i))) print('Done') cnxn.commit() Any help on this will be grateful. Thanks.

http://stackoverflow.com/comment/80791914
score: 0
type: AnswerComment
has text: sorry.since Blinxen said "This is the code I got so far",so I write a complete example that explains how to delete more than one record by sqlAlchemy.
type: Comment
comment on: http://stackoverflow.com/a/46906443

http://stackoverflow.com/comment/80695181
score: 0
type: Comment
has text: I know this already. But this problem is about the error I get,: AttributeError: '_io.TextIOWrapper' object has no attribute 'reversedString
type: AnswerComment
comment on: http://stackoverflow.com/a/46873848

http://stackoverflow.com/comment/80723931
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46888182
has text: I update the the question guys

http://stackoverflow.com/comment/80493395
type: AnswerComment
score: 0
type: Comment
has text: Thank you that worked! I was able to do json.loads(ast.literal_eval(line)) directly on my fp.readline(). Do you have an explanation for what was going on though? I still want to understand why/how the file i/o was changing my text lines.
comment on: http://stackoverflow.com/a/46761588

http://stackoverflow.com/a/46778571
score: 0
answers question: http://stackoverflow.com/q/46778437
type: Answer
has body: You could use .find with an index: s = 'azcbobobegghakl' needle = 'bob' idx = -1; cnt = 0 while True: idx = s.find(needle, idx+1) if idx &gt;= 0: cnt += 1 else: break print("{} was found {} times.".format(needle, cnt)) # bob was found 2 times.

http://stackoverflow.com/comment/80641251
type: QuestionComment
has text: @MartinPrikryl Appreciate the reply - I've had a look at that link but can't figure out where to find my key to put in the known_hosts file? I've reupdated to the latest version of pysftp because I need the security for this script when I've completed it.
comment on: http://stackoverflow.com/q/46838709
score: 0
type: Comment

http://stackoverflow.com/comment/80723373
score: 0
type: AnswerComment
has text: If you copy and paste the **exact** code above does this still produce a csv file with one column? This works for me in Python 2.7, although I am using windows 10.
type: Comment
comment on: http://stackoverflow.com/a/46887589

http://stackoverflow.com/q/46821785
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: dataframe
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: Python dataframe: Dropping rows subject to multiple conditions
has body: Suppose I have the following (example) dataframe: a b c d e 0 9 9 0 9 9 1 1 2 1 9 9 2 8 8 0 2 3 3 7 7 0 7 8 4 1 2 0 3 4 5 6 2 3 6 6 6 1 2 0 1 2 7 1 3 0 1 2 Also suppose I have generated an (arbitrary) list of indices, e.g. [3,4]. For each element in the list, I want to drop all rows from the data frame that have the same values in column 'a' and column 'b' as rows 3 and 4. Since row 3 has a=7 and b=7, and no other rows have a=7 and b=7, only row 3 is dropped. Since row 4 has a=1 and b=2, and rows 1 and 6 also have a=1 and b=2, I drop rows 4, 1, and 6. So the resulting dataframe would look like this: a b c d e 0 9 9 0 9 9 1 8 8 0 2 3 2 6 2 3 6 6 3 1 3 0 1 2 Does anyone know how to come up with a solution to do this quickly (for use in a much larger data frame)? Thank you.
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/46821876

http://stackoverflow.com/comment/80713284
type: QuestionComment
comment on: http://stackoverflow.com/q/46859115
type: Comment
has text: This looks like a gross implementation error, like wrong indexing or confusion between components. Can we see the original Bayer bitmap ? (uncompressed !)
score: 0

http://stackoverflow.com/comment/80496102
comment on: http://stackoverflow.com/q/46774696
has text: I think you've kind of misunderstood that. This task definitely involves *some sort* of loop (even if doesn't explicitly have to be a `for x in y` loop).
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/46842447
has title: How many tweets can be collected?
has answer: http://stackoverflow.com/a/46843561
downvote count: 2
tagged with: python
has body: I'm a beginner at Twitter API. I'm going to do sentiment analysis for my paper. So I need to data(user's comments) from Twitter as much as possible. However, I heard that Twitter's policy had changed last year. Its policy restrains that user collect a lot of data.. So I want to know how many tweets can be collected(ex. 5,000 data). Because if they restrain my access token, then I must change it. Also, I wonder it they restrict my access token or IP address. I use Python with Anaconda, and program will conduct on workstation. Thanks!
tagged with: tweepy
has comment: http://stackoverflow.com/comment/80634338
type: AnsweredQuestion
tagged with: twitter
type: Question
accepted answer: http://stackoverflow.com/a/46843561
upvote count: 0
score: -2
answer count: 1
tagged with: sentiment-analysis
favorite count: 0

http://stackoverflow.com/a/46841298
downvote count: 0
answers question: http://stackoverflow.com/q/46841178
has comment: http://stackoverflow.com/comment/80674154
accepted answer of: http://stackoverflow.com/q/46841178
type: Answer
has comment: http://stackoverflow.com/comment/80646879
upvote count: 2
has body: What was happening in your code: list_final = [x if [x,0] in list_two else [None,None] for x in list_one] Taking list_one and replace all its element with Either x (aka keep it intact) IF [x,0] exists in list_two (BUT, see below) ELSE replaces the current element with [None, None]. And as list_two doesn't contain any element matching [x,0] (whichever is x in your given example), all your values are replaced with [None, None]. Working solution list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] list_two = [['seven','7'], ['five','5'], ['four','4'], ['three','3'], ['one','1']] # Turns list_two into a nice and convenient dict much easier to work with # (Could be inline, but best do it once and for all) list_two = dict(list_two) # {'one': '1', 'three': '3', etc} list_final = [[k, list_two[k]] if k in list_two else [None, None] for k in list_one] Mine, in the other hand: Gets you exactly what you want, aka [k, dict(list_two)[k]] But only tries to do so IF k in list_two ELSE replaces this entry with [None, None].
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/80711850
has text: I noticed there is a pattern in the index associated with the x,y values and I tried creating a function to represent the index, and then shift that value, however I am not sure where to begin and I believe there is a simpler way to proceed.
score: 0
comment on: http://stackoverflow.com/q/46882092
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80485714
type: QuestionComment
has text: @FluidFox You did not: `FileNotFoundError: [Errno 2] No such file or directory: 'output.0008'`. Besides your code does not look like "minimal".
score: 2
comment on: http://stackoverflow.com/q/46769026
type: Comment

http://stackoverflow.com/a/46829067
type: Answer
upvote count: 6
score: 6
accepted answer of: http://stackoverflow.com/q/46815141
answers question: http://stackoverflow.com/q/46815141
type: AcceptedAnswer
downvote count: 0
has body: I have found the solution for this myself now. My main source of information was this thread in the Python-tulip group and this piece of code which I had to adopt slightly. The main insight is that an epoll that can be used to watch for POLLPRI events is itself a file descriptor. Whenever an event occurs on an FD that the epoll watches, the epoll file descriptor will generate a POLLIN event which can be watched using asyncio with add_reader. So instead of registering directly, we manually create an epoll structure and register it with the ioloop like so: self.epoll = select.epoll() self.io_loop.add_reader(self.epoll.fileno(), self._handle_interrupt) The actual interrupt event is then registered to the epoll structure self.epoll.register(self.gpio._value_file, select.POLLPRI) At this point, interrupt events will be received in the _handle_interrupt function. Make sure to actually poll the epoll structure in the event handler, or it will continuously generate read events def _handle_interrupt(self): self.epoll.poll(0) ... It is important to use the low-level select functionality instead of the high-level selectors since they do a similar event flag filtering as in asyncio. The following code snipped is from selectors.EpollSelector: def register(self, fileobj, events, data=None): key = super().register(fileobj, events, data) epoll_events = 0 if events &amp; EVENT_READ: epoll_events |= select.EPOLLIN if events &amp; EVENT_WRITE: epoll_events |= select.EPOLLOUT try: self._epoll.register(key.fd, epoll_events) except BaseException: super().unregister(fileobj) raise return key It can be seen, that all events except READ and WRITE are filtered. Hence, you can't use the high level interface to watch for POLLPRI events. Therefore, use the low-level interface. I hope this helps people stumbling over this issue.

http://stackoverflow.com/q/46896105
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46896146
accepted answer: http://stackoverflow.com/a/46896146
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/46896190
has comment: http://stackoverflow.com/comment/80739468
tagged with: pandas
has body: I would like to set values in col2 of DF1 using the value held at the matching index of col2 in DF2: DF1: col1 col2 index 0 a 1 b 2 c 3 d 4 e 5 f DF2: col1 col2 index 2 a x 3 d y 5 f z DF3: col1 col2 index 0 a NaN 1 b NaN 2 c x 3 d y 4 e NaN 5 f z If I just try and set DF1['col2'] = DF2['col2'] then col2 comes out as all NaN values in DF3 - I take it this is because the indices are different. However when I try and use map() to do something like: DF1.index.to_series().map(DF2['col2']) then I still get the same NaN column, but I thought it would map the values over where the index matches... What am I not getting?
has title: Set dataframe column using values from matching indices in another dataframe
has answer: http://stackoverflow.com/a/46896190
favorite count: 0

http://stackoverflow.com/comment/80748867
comment on: http://stackoverflow.com/a/46900952
score: 0
type: AnswerComment
has text: would the file be there if i created the text document on my desktop?
type: Comment

regex
tags question: http://stackoverflow.com/q/46751152
tags question: http://stackoverflow.com/q/46774868
tags question: http://stackoverflow.com/q/46784423
tags question: http://stackoverflow.com/q/46841618
tags question: http://stackoverflow.com/q/46787468
tags question: http://stackoverflow.com/q/46893798
tags question: http://stackoverflow.com/q/46837695
tags question: http://stackoverflow.com/q/46857766
tags question: http://stackoverflow.com/q/46851192
tag name: regex
tags question: http://stackoverflow.com/q/46751453
tags question: http://stackoverflow.com/q/46798641
tags question: http://stackoverflow.com/q/46814671
tags question: http://stackoverflow.com/q/46791875
tags question: http://stackoverflow.com/q/46814225
tags question: http://stackoverflow.com/q/46772698
tags question: http://stackoverflow.com/q/46831437
tags question: http://stackoverflow.com/q/46871964
tags question: http://stackoverflow.com/q/46893770
tags question: http://stackoverflow.com/q/46902141
tags question: http://stackoverflow.com/q/46770225
tags question: http://stackoverflow.com/q/46833878
tags question: http://stackoverflow.com/q/46776298
tags question: http://stackoverflow.com/q/46893629
tags question: http://stackoverflow.com/q/46897988
tags question: http://stackoverflow.com/q/46782766
tags question: http://stackoverflow.com/q/46814207
tags question: http://stackoverflow.com/q/46818732
tags question: http://stackoverflow.com/q/46750954
tags question: http://stackoverflow.com/q/46839014
tags question: http://stackoverflow.com/q/46756154
tags question: http://stackoverflow.com/q/46753989
tags question: http://stackoverflow.com/q/46835610
tags question: http://stackoverflow.com/q/46854846
tags question: http://stackoverflow.com/q/46781544
tags question: http://stackoverflow.com/q/46808219
tags question: http://stackoverflow.com/q/46820898
tags question: http://stackoverflow.com/q/46788630
tags question: http://stackoverflow.com/q/46899718
tags question: http://stackoverflow.com/q/46879784
tags question: http://stackoverflow.com/q/46887870
tags question: http://stackoverflow.com/q/46889366
tags question: http://stackoverflow.com/q/46798445
tags question: http://stackoverflow.com/q/46801683
tags question: http://stackoverflow.com/q/46859958
tags question: http://stackoverflow.com/q/46884402
tags question: http://stackoverflow.com/q/46782472
tags question: http://stackoverflow.com/q/46853776
tags question: http://stackoverflow.com/q/46846518
tags question: http://stackoverflow.com/q/46751206
tags question: http://stackoverflow.com/q/46788728
tags question: http://stackoverflow.com/q/46763469
tags question: http://stackoverflow.com/q/46765886
tags question: http://stackoverflow.com/q/46797221
tags question: http://stackoverflow.com/q/46830435
tags question: http://stackoverflow.com/q/46782184
tags question: http://stackoverflow.com/q/46894909
tags question: http://stackoverflow.com/q/46882099
tags question: http://stackoverflow.com/q/46812096
tags question: http://stackoverflow.com/q/46814792
tags question: http://stackoverflow.com/q/46856698
tags question: http://stackoverflow.com/q/46755306
tags question: http://stackoverflow.com/q/46812957
tags question: http://stackoverflow.com/q/46768268
tags question: http://stackoverflow.com/q/46780835
tags question: http://stackoverflow.com/q/46847515
type: Tag
tags question: http://stackoverflow.com/q/46843196
tags question: http://stackoverflow.com/q/46832469

http://stackoverflow.com/comment/80751272
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46890822
has text: I have updated my code, similar to my old code. Please check, thanks in advance!

http://stackoverflow.com/q/46806641
favorite count: 0
tagged with: opendaylight
has body: I am trying to develop an external application in python that uses rest API to interact with the Opendaylight controller. How can I Make a call to the ODL to register myself as a listener for a specific type of event? what are the currently available events that ODL support? to create a customized event, for example, the remaining BW or any other sort monitoring, can I do that externally through the rest API and my python code or I need to develop java inside the OSGi container of the controller?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/46838201
type: Question
accepted answer: http://stackoverflow.com/a/46838201
has title: How to Make a call to the opendaylight controller to register us as a listener?
answer count: 1
has comment: http://stackoverflow.com/comment/80566089
upvote count: 1

http://stackoverflow.com/a/46782580
answers question: http://stackoverflow.com/q/46782471
type: Answer
score: 3
has body: The problem is you are not adding 1, 2, 3 to the LinkedList and letting it create a Node to wrap each. You are adding a Node whose stuff variable is 1, 2, and 3. When you call the append method to add each Node, they get wrapped in another Node by the append method. Therefore you need to call Node.stuff.stuff to access the actual element that is stored. Look at what your append method is actually doing. It accepts some parameter data and then creates a Node with either the line self.head = Node(data) or the line new_node = Node(data), depending on if the LinkedList already has a head Node or not. Change ll.append(Node("1")) to just ll.append("1"). Alternatively, change your append method to assume it is being passed a Node object. The first solution is much more preferable as the Node class has little use outside the context of the LinkedList class and the LinkedList doesn't work unless it is populated with Nodes anyways; it seems like extra work to make the user of the LinkedList class have to create a Node every single time. EDIT: Also what is the reason you are passing in numbers as strings? You don't need to put 1, 2, 2.5, and 3 in quotes unless you specifically want them to be strings- but if so, why?
downvote count: 0
has comment: http://stackoverflow.com/comment/80512511
upvote count: 3

http://stackoverflow.com/comment/80705173
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46842724
has text: That's good to know. That does work, but if I watch the browser as it's doing that, it doesn't actually cause the dropdown to come down, and (seemingly) as a result, it still can't find the elements inside the dropdown afterwards.
score: 0

http://stackoverflow.com/a/64305211
answers question: http://stackoverflow.com/q/46768088
type: Answer
upvote count: 2
score: 1
downvote count: 1
has body: Well if can give a proper output in a table format if instead of using format go for f"" ; for e.g Unable to handle Value Error for name, branch,year in college: print(f"{name:{10}} {branch:{20}} {year:{12}} ) name branch year ankit cse 2 vijay ece 4 raj IT 1

http://stackoverflow.com/comment/80619289
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46835710
has text: @LMc Yes, np.Nan is considered np.float. 'type(np.nan) == np.float' returns True

http://stackoverflow.com/q/46855602
downvote count: 0
has title: Using a Groupby Object and Resampling in Pandas
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/46855685
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1
type: Question
has body: I am hoping to use a groupby and resample on a data frame to get annual counts of a field. Let's say I had a dataframe structured as such: df = pd.DataFrame({'year': {0: '2017', 1: '2018', 2: '2016', 3: '2018'}, 'month': {0: '1', 1: '2', 2: '3', 3: '4'}, 'day': {0: '1', 1: '1', 2: '1', 3: '3'}}) df['Date']=pd.to_datetime(df) #Sorry there is probably and easier way to set up the df df['B']=[1, 2, 3, 1] df['C']=[2,3,4, 1] df=df.ix[:, ['Date', 'B', 'C']] df.groupby('B').resample('A', on='Date') How do I get the last line of code to group by Column B and still be able to resample by year or month, etc? In the end I'm looking for counts per year of C grouped by B. I'd like to maintain my index in the process, if possible. Thanks.
score: 1
has answer: http://stackoverflow.com/a/46855685
possible better answer: http://stackoverflow.com/a/46855870
has answer: http://stackoverflow.com/a/46855870
answer count: 2

http://stackoverflow.com/q/46786548
has body: Problem description I want to send an http post request to an online BLAST website.I inspected the POST requests and saw this: Request URL:https://p3.theseed.org/services/homology_service Referrer Policy:no-referrer-when-downgrade Request Headers Provisional headers are shown Accept:application/json Content-Type:application/x-www-form-urlencoded Origin:https://www.patricbrc.org Referer:https://www.patricbrc.org/ User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 X-Requested-With:XMLHttpRequest Form Data {"method":"HomologyService.blast_fasta_to_database","params":["&gt;test ATAGCTAACAGCATC","blastn","ref.fna","10",50,0],"version":"1.1","id":"27057295081137034"}: Now I want to do this for several sequences (so replacing the ATAGCTAACAGCATC ). I'm familiar with sending these type of request, however I don't now how to: Format the form data, so I can send it using Requests What I should do with the id in the post, because I don't know this because it's unique for every BLAST job. Code import requests as r blast_url = 'https://p3.theseed.org/services/homology_service' data = {"method":"HomologyService.blast_fasta_to_database","params":["%3Etest%0ATAGCTAACAGCATC","blastp","ref.faa","10",'50','0'],"version":"1.1"} headers = { 'Host': 'p3.theseed.org', 'Accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://www.patricbrc.org/app/BLAST', 'Content-Type': 'application/rqlquery+x-www-form-urlencoded', 'X-Requested-With' : 'XMLHttpRequest' } res = r.post(blast_url, headers = headers, params = data).text print(res) I didn't fill in the id, but that doesn't seem to be a problem because in the error message the id is filled in (so it seems to generated it automatically?) This is the error I get: {"id":"15004153692662703","error":{"name":"JSONRPCError","code":-32700,"message":"You did not supply any JSON to parse in the POST body."},"version":"1.1"} So obviously the wrong form…
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46786864
score: 0
tagged with: request
type: Question
has title: Python http post request format form data
tagged with: post
possible better answer: http://stackoverflow.com/a/46786613
accepted answer: http://stackoverflow.com/a/46786864
answer count: 2
tagged with: http-post
has answer: http://stackoverflow.com/a/46786613

http://stackoverflow.com/comment/80651548
score: 0
has text: @Bharathshetty, the output top_Type Resi Co_Name Lat Lng Shpr_ID 1.0 NaN NaN NaN NaN NaN 30.0 NaN NaN NaN NaN NaN 132.0 NaN NaN NaN NaN NaN 148.0 NaN NaN NaN NaN NaN 156.0 NaN NaN NaN NaN NaN
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46851319

http://stackoverflow.com/comment/80660107
comment on: http://stackoverflow.com/q/46856120
score: 1
has text: you are not storing the results of `file.read(names)` . name is just a file handle
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80664755
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46858607
has text: This is cubic in complexity though.
score: 0

http://stackoverflow.com/q/46793784
linked to: http://stackoverflow.com/q/750486
tagged with: generator
score: 2
duplicate of: http://stackoverflow.com/q/10733701
upvote count: 3
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/10733701
has comment: http://stackoverflow.com/comment/80534416
has title: Different result unrolling loop - Python generators
answer count: 1
has body: When I append two generators to a list using a loop the first generator duplicates the second generator's output. When I unroll the loop I get different output as I expected. The following code demonstrates the issue. import itertools iterators = itertools.tee(itertools.repeat(('a', 0), 5), 2) result = [] result.append(r[0] for r in iterators[0]) result.append(r[1] for r in iterators[1]) # As expected print('Written out...') print(list(result[0])) # ['a', 'a', 'a', 'a', 'a'] print(list(result[1])) # [0, 0, 0, 0, 0] # Now do it again but use a loop iterators = itertools.tee(itertools.repeat(('a', 0), 5), 2) result = [] for index in [0, 1]: result.append(r[index] for r in iterators[index]) # This time both lists are of the second item. print('With a loop...') print(list(result[0])) # [0, 0, 0, 0, 0] &lt;--- Huh?! print(list(result[1])) # [0, 0, 0, 0, 0] Why does the loop version not work as I expected? What can I do about it? Solution Now this is closed as a duplicate I can't post another answer, but for the record, here is the solution I used finally. The problem as pointed out by @MikeMüller is that the instance of index that indexes r is late-bound. The following forces early-binding by making a new local variable instance i for each value of index in the loop: for index, it in enumerate(iterators): g = lambda i: (r[i] for r in it) # force early binding on index result.append(g(index)) (I also liked Mike's suggestion to use generators all the way down, but unfortuantely I need the outer generator (for result) to be materialised so I can refer repeatedly to the individual elements in result. But list(result) has the same behaviour as my original loop code.)
has answer: http://stackoverflow.com/a/46793948
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80534520
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/37575481
has comment: http://stackoverflow.com/comment/80534350

http://stackoverflow.com/q/46785507
accepted answer: http://stackoverflow.com/a/46794505
has body: I am trying to pass a filename of an image and render it on a template, Although I am passing the actual name through it does not display on the page @app.route('/', methods=['GET','POST']) @app.route('/start', methods=['GET','POST']) def start(): person_to_show = 'tim' profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg") return render_template('start.html',profilepic_filename =profilepic_filename ) For example: profilepic_filename = /data/tim/img.jpg I have tried {{profilepic_filename}} &lt;img src="{{ url_for('data', filename='tim/img.jpg') }}"&gt;&lt;/img&gt; And I have also tried &lt;img src="{{profilepic_filename}}"&gt;&lt;/img&gt; Neither of which worked
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20646822
has answer: http://stackoverflow.com/a/46794505
type: Question
upvote count: 36
has title: python flask display image on a html page
downvote count: 0
answer count: 1
tagged with: flask
duplicate of: http://stackoverflow.com/q/16351826
score: 36
tagged with: flash-message
tagged with: http://stackoverflow.com/tag/html
duplicate of: http://stackoverflow.com/q/20646822
favorite count: 0

http://stackoverflow.com/comment/101286784
has text: Issue with Python 3.7 import error: /dev/venv/lib/python3.7/site-packages/re2.cpython-37m-x86_64-linux-gnu.so: undefined symbol: _ZNK3re23RE25MatchERKNS_11StringPieceEmmNS0_6AnchorEPS1_i
type: Comment
comment on: http://stackoverflow.com/a/46792358
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80749989
type: QuestionComment
comment on: http://stackoverflow.com/q/46884770
has text: In any event, `getLabeledDataVector` is returning the result of `zip` without `list`-ifying it, while the code using it assumes it can `+=` it (likely written by or for Python 2, where `zip` returned `list`, not a lazy generator).
type: Comment
score: 1

http://stackoverflow.com/comment/80696144
comment on: http://stackoverflow.com/q/46874343
has text: arpit but does freqdist can extract a word from a list and check the freq of the word in another list , if so can you tell me how???
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/80862333
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46889668
has text: Dear The4thIceman, I will follow your advise in the answers you provided earlier. It is a similar issue. Thanks!!!
score: 0

http://stackoverflow.com/a/46876916
score: 0
accepted answer of: http://stackoverflow.com/q/46876774
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80701249
has comment: http://stackoverflow.com/comment/80701270
type: Answer
has body: Your form meta model is User, so when you try: profile = form.save(commit=False) the variable profile is an instance of the User class, so, since you have the signal that creates the UserProfile instance, you should use this code: user = form.save() profile = user.userprofile user_group = form.cleaned_data.get('user_type') profile.user_type = user_group profile.save() instead of: profile = form.save(commit=False) profile.user = request.user profile.save()
answers question: http://stackoverflow.com/q/46876774

http://stackoverflow.com/q/46832084
has title: Python MQTT Reset timer after received a message
type: Question
has answer: http://stackoverflow.com/a/46832382
score: 0
answer count: 1
has body: I have the below python script from the thread "Python MQTT Connect only for a limited time". #!/usr/bin/python import sys import paho.mqtt.client as mqtt import time def on_message(client, userdata, msg): if msg.topic == "foo/bar": print ("test successful! Message = ", str(msg.payload.decode("utf-8"))) startTime = time.time() def on_connect(client, userdata, flags, rc): client.subscribe("foo/bar") print("Client connected") client = mqtt.Client("Python1", clean_session=True) try: client.connect("localhost") except: print ("ERROR: Could not connect to MQTT") client.on_connect = on_connect client.on_message = on_message startTime = time.time() waitTime = 10 while True: client.loop() elapsedTime = time.time() - startTime print("Elapsed time: ", elapsedTime) if elapsedTime &gt; waitTime: client.disconnect() break the client will wait for 10 seconds, if it didn't received any message within 10 seconds then the client will be disconnect. What I'm trying to do now is whenever the client received a message, I want to reset the startTime back to current time so that the client will be stay connected and won't be terminated after 10 seconds but I'm not sure where should I modify the coding to achieve it.
tagged with: paho
tagged with: mqtt
tagged with: python
accepted answer: http://stackoverflow.com/a/46832382
type: AnsweredQuestion

http://stackoverflow.com/comment/80729816
score: 1
has text: The point is the ternary statement reads like `return True if True else False` (assuming the set is not empty), which is a tautology. Besides behind the scenes python will call bool(something) when you put that something in a conditional statement, so returning its boolean value directly is more concise. If someone can handle the idea of `if my_set:`, they can handle `bool(my_set)`. But it's just a heads up.
comment on: http://stackoverflow.com/a/46890987
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46852090
upvote count: 2
type: UnansweredQuestion
has body: I have some code that is running through nested loops. I am guessing that there is a more "pythonic" way of doing this. Any suggestions? The basic section of code looks like this: for e in range(len(listOfTuples)): for item in self.items: if item.getName() == listOfTuples[e][0]: &lt;do stuff&gt; if item.getName() == listOfTyples[e][1]: &lt;do other stuff&gt; continue if &lt;both above if statements got answers&gt;: &lt;do yet more stuff&gt; Is there a better way to write these nested loops?
type: Question
has title: Is there a better way to iterate over nested loops in python
tagged with: algorithm
tagged with: optimization
has comment: http://stackoverflow.com/comment/80651583
answer count: 2
has comment: http://stackoverflow.com/comment/80651640
downvote count: 0
has answer: http://stackoverflow.com/a/46852226
has comment: http://stackoverflow.com/comment/80651562
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/80651624
has answer: http://stackoverflow.com/a/46852342
score: 2

http://stackoverflow.com/q/46901975
score: 1
tagged with: string
possible better answer: http://stackoverflow.com/a/46901997
has answer: http://stackoverflow.com/a/46902069
favorite count: 0
has answer: http://stackoverflow.com/a/46901997
has comment: http://stackoverflow.com/comment/80750700
type: Question
accepted answer: http://stackoverflow.com/a/46902069
tagged with: python
tagged with: list
linked to: http://stackoverflow.com/q/6797984
answer count: 2
upvote count: 1
has body: Suppose I have some data like: data[0] = ['I want to make everything lowercase'] data[1] = ['How Do I Do It'] data[2] = ['With A Large DataSet'] How do I repeatedly call the lower() function on all the elements of data, to make all the of strings in lowercase? I have tried {k.lower(): v for k, v in data.items()}, but I get an error saying that 'list' object has no attribute 'items'. I have also tried using .lower() and it is giving me the same AtrributeError.
has title: python: how to make list with all lowercase?
duplicate of: http://stackoverflow.com/q/6797984
duplicate of: http://stackoverflow.com/q/75666408
tagged with: lowercase
type: AnsweredQuestion
downvote count: 0
tagged with: dataset

http://stackoverflow.com/comment/80558292
has text: I works perfectly! Can you show how it would be using meshgrid? I strugled so much on that...
score: 0
comment on: http://stackoverflow.com/a/46805573
type: AnswerComment
type: Comment

http://stackoverflow.com/q/46811850
type: Question
score: 5
tagged with: deap
has title: Deap python package: create individuals with different ranges and mix of integers and floats
has answer: http://stackoverflow.com/a/47719547
answer count: 1
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: python
downvote count: 0
has body: I am trying to use DEAP to maximise a function. I understand how to do it with the basic example: toolbox.register("attr_bool", random.randint, 0, 1) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100) which creates 100 random values or either 0 or 1. You then go on and create a population and mutate ... How do you build a population when you have for example two parameters: parameter 1 integer with range [0,1] parameter 2 float with range [0,2] Then create an individual combining both randomly sampled parameters? or for parameter 2 sample with an arbitary step value , for example 0.25.

http://stackoverflow.com/a/46880706
has comment: http://stackoverflow.com/comment/92389482
has body: I don't recommend you to use imagemagick. Because this tools render output by pixels but not vectors inside the pdf file. So if your pdf file's original resolution is much lower than the resolution of your output png file, it will be a quality loss. Try to use mupdf. The command mudraw you should use is various decided by version. Most of time it should be: mudraw [-h 1080] [-w 1080] [-o &lt;output_path&gt;] &lt;input_path&gt; This tool could manipulate vectors so there won't be any quality loss not matter how you zoom your original file.
score: 1
has comment: http://stackoverflow.com/comment/92389512
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/92389317
answers question: http://stackoverflow.com/q/46879790
has comment: http://stackoverflow.com/comment/92389259
downvote count: 0

http://stackoverflow.com/a/46794209
answers question: http://stackoverflow.com/q/46794017
score: 0
has body: I assume you want to iterate through u and v simultaneously. In this case, you either want to just use a plain index using for loop over a range, or you could use enumerate as follows: txt = open(os.path.expanduser('~FOLDER\\numbers.txt'), 'r') res = txt.read().splitlines() u = [something] for index, item in enumerate(u): var['Number : ' + res[index]]
type: Answer

http://stackoverflow.com/q/46866268
upvote count: 3
has comment: http://stackoverflow.com/comment/80785865
tagged with: python
favorite count: 0
tagged with: stata
has comment: http://stackoverflow.com/comment/80680400
has body: I'm calling a Python script from another program (Stata), which has a command for calling the operating system (shell/winexec). This, in turn, opens a system window where you can see the Python script running. Sometimes the script runs just fine and sometimes it abruptly quits before finishing. I have no idea why. I never have this problem when I run the script in IDLE. I'm using Windows and Python 3.4. I've tried catching the error by logging the Python script, but no error ever gets recorded there. Everything seems to be working normally until the program just quits (and not always at the same point). Also, I'm calling 7 scripts and only two of them ever have this sudden quitting problem (again, they always run fine through IDLE). I tried changing the order in which I call the scripts and using shell instead of winexec and vise-versa. At this point, I don't even know what to try. Is it the operating system? Python? Stata? Any ideas would be appreciated!
downvote count: 0
accepted answer: http://stackoverflow.com/a/46918644
type: AnsweredQuestion
score: 3
tagged with: exit
has comment: http://stackoverflow.com/comment/80680044
has comment: http://stackoverflow.com/comment/80681697
linked to: http://stackoverflow.com/q/42630191
has comment: http://stackoverflow.com/comment/80695684
has comment: http://stackoverflow.com/comment/80680982
has answer: http://stackoverflow.com/a/46918644
type: Question
has title: Python script suddenly exiting when being run through windows
has comment: http://stackoverflow.com/comment/80784624
answer count: 1
has comment: http://stackoverflow.com/comment/80680393

http://stackoverflow.com/comment/80746079
comment on: http://stackoverflow.com/q/46899428
score: 4
type: QuestionComment
type: Comment
has text: Looking at your sample data, the problem might be that your `<paste>` elements aren't contained within a single root element.

http://stackoverflow.com/comment/80548092
comment on: http://stackoverflow.com/q/46792348
has text: After take a look of that library, I think that pyrebase is less complex, thank you @HristoStaykov
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46854602
answers question: http://stackoverflow.com/q/46854517
score: 0
accepted answer of: http://stackoverflow.com/q/46854517
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80656819
has body: As Arpit suggests, you need to add the pk value. You could also modify the items variable like this items = Game.objects.exclude(pk__in=[o.pk for o in objects]) Compared to Arpit's solution this won't throw a list index out of range.
type: Answer
has comment: http://stackoverflow.com/comment/80656875
has comment: http://stackoverflow.com/comment/80656950

http://stackoverflow.com/q/46858626
has comment: http://stackoverflow.com/comment/80664903
has answer: http://stackoverflow.com/a/46965504
score: 0
answer count: 2
has body: I would like to filter using a list of timestamps. In SQL the syntax would be like SELECT * FROM TABLE WHERE TABLE.QueryTimestamp IN ("2017-10-20 23:20:00", "2017-10-10 23:20:00") The column QueryTimestamp is datetime in Python. I tried using following which does not provide correct answers. ts_list is a list of python datetime values. session.query(TABLE).filter(TABLE.QueryTimestamp.in_(ts_list))).all()
type: UnansweredQuestion
tagged with: datetime
has title: Sqlalchemy python how to query using IN over list of datetime
tagged with: python
has answer: http://stackoverflow.com/a/46859599
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/80531911
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46792667
has text: tags will always be in the same form: a set of tuples containing two values. Another tag example would be '{(All Ages, S), ($, S), (Alternative & Rock, S), (Concerts & Live Music, P)}' In [ ]:

http://stackoverflow.com/comment/80510951
has text: Do you know what the function `bs` is supposed to be doing?
type: QuestionComment
comment on: http://stackoverflow.com/q/46781937
type: Comment
score: 1

http://stackoverflow.com/q/46795404
type: Question
tagged with: pyflakes
score: 18
upvote count: 18
has title: How can I disable flake8 for a multiline import?
has answer: http://stackoverflow.com/a/49549892
answer count: 1
downvote count: 0
has body: With flake8, to disable a certain error on a line you do this: example = lambda: 'example' # noqa: E731,E123 However, if I have multiline a statement, flake8 fails to parse the noqa statment at the end: from detect_fixtures import expected_response_stage3_mocked, expected_response_bbox_oob,\ mock_detection, mock_detection_models, mock_detection_stage1, mock_detection_stage2,\ mock_detection_stage3_given_bbox, mock_load_image # noqa: F401 I want to use '\' for continuation, so I don't want to do this (which does work) from detect_fixtures import (expected_response_stage3_mocked, # noqa: F401 expected_response_bbox_oob, img, mock_detection, mock_detection_models, # noqa: F401 mock_detection_stage1, mock_detection_stage2, mock_detection_stage3_given_bbox, # noqa: F401 mock_load_image) # noqa: F401 Any help here?
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49549892
type: AnsweredQuestion

http://stackoverflow.com/comment/80737677
comment on: http://stackoverflow.com/q/46895215
type: Comment
type: QuestionComment
has text: There is no 'setup.py' (or similar) as far as I can tell in the download. Is this required for this approach?
score: 0

http://stackoverflow.com/q/46902193
has answer: http://stackoverflow.com/a/46902329
type: Question
has answer: http://stackoverflow.com/a/46902990
has title: how to print output in txt file of for loop?
tagged with: python-2.7
score: 0
answer count: 2
has body: def input_sentence(): sppc = BetterICP(grammar2) with open("output.txt","w") as op: with open("input.txt", "r") as ins: array = [] temp = [] for line in ins: array.append(line) for a in array: op.write(str(sppc.parse(a.split())) I need to write my output which I will get from str(sppc.parse(a.split()) but not able to write it in file
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/80644403
type: QuestionComment
comment on: http://stackoverflow.com/q/46848408
type: Comment
has text: Don't perform the check before emitting the event, but in the receiving function before you process anything
score: 0

http://stackoverflow.com/comment/80630912
score: 0
has text: It looks like sympy simplifies the function by removing the a^3 tan-1(x/a) term. Not sure why though.
type: QuestionComment
comment on: http://stackoverflow.com/q/46841488
type: Comment

http://stackoverflow.com/comment/80457370
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46755940
has text: @EdvardHaugland The only answer to that off the top of my head is performance comparison. When you end up dealing with larger chunks of data, regex will be slower. However, with what seems like a smaller data set, I would do a `timeit` comparison to see which one in fact is faster.
score: 0

nodes
tags question: http://stackoverflow.com/q/46858710
tags question: http://stackoverflow.com/q/46842021
tags question: http://stackoverflow.com/q/46892866
tag name: nodes
type: Tag
tags question: http://stackoverflow.com/q/46851776

http://stackoverflow.com/q/46828089
type: Question
linked to: http://stackoverflow.com/q/436198
tagged with: python
has comment: http://stackoverflow.com/comment/80652171
tagged with: module
has comment: http://stackoverflow.com/comment/80617324
tagged with: namespaces
has answer: http://stackoverflow.com/a/46853219
upvote count: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/46853219
has answer: http://stackoverflow.com/a/46852679
has body: I'm trying to dynamically update code during runtime by reloading modules using importlib.reload. However, I need a specific module variable to be set before the module's code is executed. I could easily set it as an attribute after reloading but each module would have already executed its code (e.g., defined its default arguments). A simple example: # module.py def do(): try: print(a) except NameError: print('failed') # main.py import module module.do() # prints failed module.a = 'succeeded' module.do() # prints succeeded The desired pseudocode: import_module_without_executing_code module module.initialise(a = 'succeeded') module.do() Is there a way to control module namespace initialisation (like with classes using metaclasses)?
has comment: http://stackoverflow.com/comment/80652413
has title: Module namespace initialisation before execution
type: AnsweredQuestion
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/1676835
accepted answer: http://stackoverflow.com/a/46852679
favorite count: 0
has comment: http://stackoverflow.com/comment/80647200

http://stackoverflow.com/a/46773572
type: Answer
score: 0
has body: The tutorial you refer to reads the data into a numpy array (see the code here) and pass the input with tf.estimator.inputs.numpy_input_fn. This is the easiest way. However, if you prefer to operate with tensors from the very beginning, it's possible as well using a custom input function. Here's a trivial example: def read_images(batch_size): # A stub. Should read the next batch, shuffle it, etc images = tf.zeros([batch_size, 28, 28, 1]) # 4-rank tensor labels = tf.ones([batch_size]) # 1-rank tensor (not one-hot encoded) return images, labels def simple_input(): x, labels = read_images(batch_size=10) return {"x": x}, labels tensors_to_log = {"probabilities": "softmax_tensor"} logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=50) classifier.train(input_fn=simple_input, steps=10, hooks=[logging_hook])
answers question: http://stackoverflow.com/q/46757973

http://stackoverflow.com/a/46952330
score: 2
has body: .pyc and .pyo files are just cached bytecode. Python's import machinery is built entirely around strings, and this leaves code that executes an import decoupled from whatever library they import. So those files are no more tied to the version of the libraries they import than the source code itself. If the source code works with a wide range of versions of the library, so will the compiled bytecode. You can always take a look at what bytecode Python generates with the dis module. A straight-up import statement becomes: &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile('import numpy as np', '', 'single')) 1 0 LOAD_CONST 0 (0) 2 LOAD_CONST 1 (None) 4 IMPORT_NAME 0 (numpy) 6 STORE_NAME 1 (np) 8 LOAD_CONST 1 (None) 10 RETURN_VALUE The IMPORT_NAME opcode takes the name from the co_names structure that is attached to a code object (stored in the cache too): &gt;&gt;&gt; compile('import numpy as np', '', 'single').co_names ('numpy', 'np') It doesn't matter here that the numpy module consists in large parts of dynamically-loaded libraries; if you replaced the name numpy with something else that would be imported instead. Modules are loaded at runtime, not at compile time after all.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46886704
upvote count: 2
accepted answer of: http://stackoverflow.com/q/46886704

http://stackoverflow.com/q/46791742
score: 0
tagged with: decoder
upvote count: 1
tagged with: python
answer count: 1
downvote count: 1
tagged with: audio
has body: How can I: read my audio file stores in a binary file, Can somebody give me examples to implement encoder and decoder in python?
has title: Encodeer and decoder in python/ from wav to bin
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80540104
favorite count: 0
tagged with: encoder
type: Question
has answer: http://stackoverflow.com/a/46792106
has comment: http://stackoverflow.com/comment/80530162

http://stackoverflow.com/q/46797086
type: Question
has comment: http://stackoverflow.com/comment/80540984
tagged with: pyspark
has comment: http://stackoverflow.com/comment/80541198
has body: I am using an EMR that I myself did not setup in AWS. I am trying to understand what Python interpreter spark is using and in my .bashrc I have the following setup export PYSPARK_PYTHON=/mnt/anaconda/bin/python When I run our spark-submit command I have used sys.executable to print to the path to the python interpreter and this is indeed the interpreter that its using. However, when I go specifically to that folder, launch that instance of Python with ./python and then try import pyspark I get: &gt;&gt;&gt; import pyspark Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pyspark What's going on here? Shouldn't this interpreter have the pyspark module installed?
tagged with: apache-spark
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80541744
score: 0
type: UnansweredQuestion
tagged with: amazon-emr
has comment: http://stackoverflow.com/comment/80541236
has title: pyspark module not available from within python instance that spark is using
has answer: http://stackoverflow.com/a/46797968

http://stackoverflow.com/comment/80660392
type: Comment
comment on: http://stackoverflow.com/q/46856276
has text: It's not json once you've made your df, it's a dict. But it's keeping me occupied trying to selectively keep those columns for sure :)
score: 0
type: QuestionComment

http://stackoverflow.com/q/46770292
tagged with: octave
has comment: http://stackoverflow.com/comment/80513991
tagged with: oct2py
has title: How to call octave function from python?
upvote count: 4
has comment: http://stackoverflow.com/comment/80577036
answer count: 1
favorite count: 0
has body: I have a problem.m file that has a function like this: myfun(p,m). It does some calculation and returns the result. For testing the execution of this function I have a test.m file that looks like this. myfun(myarg1,myarg2) If I run this file as: octave test.m Then it returns me the correct result which looks like this : 0.38007 Now, the problem is when calling this function myfun(p,m) using python. I tried to use python library : oct2py The python code looks like this: import sys import subprocess import oct2py import requests from oct2py import octave def myfun(p,m): octave.addpath('/mypath'); oc = oct2py.Oct2Py() #res = octave.myfun(p,m nout=1);#this didn't work, hence comment #res = oc.myfun(p, m) #this didn't work, hence comment x = oc.feval("myfun",p,m); print(x); if __name__ == '__main__': myfun(sys.argv[1],sys.argv[2]) When i run this code as: python FileName.py arg1 arg2 (same arguments i used in test.m) , it gives me a warning message and an empty list like this : warning: some elements in list of return values are undefined [] I am not sure what to do about this. As the function seems to be returning correct result in a correct format when using octave. but for some reason oct2py is not working.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46784012
score: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/80490663
type: Question

http://stackoverflow.com/comment/81382704
comment on: http://stackoverflow.com/a/47203289
score: 0
type: Comment
has text: Thank you for your reply. I will check it.
type: AnswerComment

http://stackoverflow.com/comment/80742484
score: 0
type: Comment
has text: Seems like there are still some differences in the score even though it is close. Right now I need to make a ranking depending on the probability, so even small differences matter (therefore I switched to Theano backend for this purpose). But thank you! I will try what results I get.
type: AnswerComment
comment on: http://stackoverflow.com/a/46886311

http://stackoverflow.com/a/46883633
has body: If you can do without regex, you could do it, like so: def find_first_vowel(s): first_vowels = '' for word in s.split(): for index, char in enumerate(word): if char in 'aeiouAEIOU': # you can check the index here first_vowels += char break return ', '.join(first_vowels) my_str = "The sky's the limit" &gt;&gt;&gt; print(find_first_vowel(my_str)) e, e, i
type: Answer
answers question: http://stackoverflow.com/q/46882099
score: 0

http://stackoverflow.com/q/46772012
type: UnansweredQuestion
has title: Unexpected keyword argument 'ibm_api_key_id' when using ibm-cos-sdk?
has comment: http://stackoverflow.com/comment/80491024
tagged with: ibm-cloud-storage
has comment: http://stackoverflow.com/comment/80491099
tagged with: python
has answer: http://stackoverflow.com/a/46772652
score: 1
has comment: http://stackoverflow.com/comment/80490431
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80490560
has comment: http://stackoverflow.com/comment/80490015
tagged with: object-storage
has comment: http://stackoverflow.com/comment/80490096
has body: I'm getting a Unexpected keyword argument 'ibm_api_key_id' error argument when using ibm-cos-sdk on python 3.6.2. I've installed the library in a clean virtual enviroment using these steps: virtualenv --python=python3.5 boto-test source boto-test/bin/activate pip install ibm-cos-sdk Then, I've tried to run the example from here: import boto3 import json import requests import random from botocore.client import Config from pprint import pprint with open('./credentials.json') as data_file: credentials = json.load(data_file) print("Service credential:") print(json.dumps(credentials, indent=2)) print("") print("Connecting to COS...") # Rquest detailed enpoint list endpoints = requests.get(credentials.get('endpoints')).json() #import pdb; pdb.set_trace() # Obtain iam and cos host from the the detailed endpoints iam_host = (endpoints['identity-endpoints']['iam-token']) cos_host = (endpoints['service-endpoints']['cross-region']['us']['public']['us-geo']) api_key = credentials.get('apikey') service_instance_id = credentials.get('resource_instance_id') # Constrict auth and cos endpoint auth_endpoint = "https://" + iam_host + "/oidc/token" service_endpoint = "https://" + cos_host print("Creating client...") # Get bucket list cos = boto3.client('s3', ibm_api_key_id=api_key, ibm_service_instance_id=service_instance_id, ibm_auth_endpoint=auth_endpoint, config=Config(signature_version='oauth'), endpoint_url=service_endpoint) # Call S3 to list current buckets response = cos.list_buckets() # Get a list of all bucket names from the response buckets = [bucket['Name'] for bucket in response['Buckets']] # Print out the bucket list print("Current Bucket List:") print(json.dumps(buckets, indent=2)) print("---") result = [bucket for bucket in buckets if 'cos-bucket-sample-' in bucket] print("Creating a new bucket and uploading an object...") if len(result) == 0 : bucket_name = 'cos-bucket-sample-' + str(random.randint(100,99999999)); # Create a bucket cos.create_bucket(Bucket=bucket_name)…
has comment: http://stackoverflow.com/comment/80490818
has comment: http://stackoverflow.com/comment/80491835
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/80489574
favorite count: 0
has answer: http://stackoverflow.com/a/46773079

http://stackoverflow.com/a/46871297
has comment: http://stackoverflow.com/comment/80689800
upvote count: 3
has comment: http://stackoverflow.com/comment/80690205
type: Answer
has comment: http://stackoverflow.com/comment/80689886
downvote count: 0
score: 3
has body: You could subtract 4 days, resample, then add the 4 days back... but this is kind of horrible: In [11]: data2.index = data2.index - pd.offsets.Day(4) In [12]: res = data2.resample("AS-JUL").sum() In [13]: res.index = res.index + pd.offsets.Day(4) In [14]: res Out[14]: value date 2004-07-05 4 2005-07-05 22 2006-07-05 26 2007-07-05 12
answers question: http://stackoverflow.com/q/46871173
has comment: http://stackoverflow.com/comment/80690120

http://stackoverflow.com/comment/80675452
type: QuestionComment
has text: Welcome to SO. Please take the time to read [ask]. It makes it easier for *us* if you include a minimal example of the data you are operating on.
score: 0
comment on: http://stackoverflow.com/q/46863866
type: Comment

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/46882803
tags question: http://stackoverflow.com/q/46803405
tags question: http://stackoverflow.com/q/46755489
tags question: http://stackoverflow.com/q/46764858
tags question: http://stackoverflow.com/q/46877806
type: Tag

http://stackoverflow.com/q/46804040
favorite count: 0
type: Question
tagged with: python
downvote count: 3
answer count: 1
has body: I have two decimal number with different digit places ( like 3.60 and 12.750), I am going to have then in the output with the same length such as following (in this case both of them have 7 characters): 3.60000 and 12.7500
type: UnansweredQuestion
has title: Write two decimal numbers in same lenth
score: -3
has comment: http://stackoverflow.com/comment/80554839
has answer: http://stackoverflow.com/a/46804053
upvote count: 0

dictionary
tags question: http://stackoverflow.com/q/46761597
tags question: http://stackoverflow.com/q/46777114
tags question: http://stackoverflow.com/q/46753672
tags question: http://stackoverflow.com/q/46755639
tags question: http://stackoverflow.com/q/46833160
tags question: http://stackoverflow.com/q/46810099
tags question: http://stackoverflow.com/q/46837646
tags question: http://stackoverflow.com/q/46836864
tags question: http://stackoverflow.com/q/46791559
tags question: http://stackoverflow.com/q/46787046
tags question: http://stackoverflow.com/q/46866327
tags question: http://stackoverflow.com/q/46886865
tags question: http://stackoverflow.com/q/46901638
tags question: http://stackoverflow.com/q/46810479
tags question: http://stackoverflow.com/q/46867083
tags question: http://stackoverflow.com/q/46817029
tags question: http://stackoverflow.com/q/46800740
tags question: http://stackoverflow.com/q/46810867
tags question: http://stackoverflow.com/q/46832263
tags question: http://stackoverflow.com/q/46844950
tags question: http://stackoverflow.com/q/46775709
tags question: http://stackoverflow.com/q/46900269
tags question: http://stackoverflow.com/q/46873838
tags question: http://stackoverflow.com/q/46768337
tags question: http://stackoverflow.com/q/46782871
tags question: http://stackoverflow.com/q/46870263
tags question: http://stackoverflow.com/q/46848642
tags question: http://stackoverflow.com/q/46887750
tags question: http://stackoverflow.com/q/46905380
tags question: http://stackoverflow.com/q/46795006
tags question: http://stackoverflow.com/q/46783100
tags question: http://stackoverflow.com/q/46863437
tags question: http://stackoverflow.com/q/46759533
tags question: http://stackoverflow.com/q/46863568
tags question: http://stackoverflow.com/q/46860847
tags question: http://stackoverflow.com/q/46756019
tags question: http://stackoverflow.com/q/46845464
tags question: http://stackoverflow.com/q/46838446
tags question: http://stackoverflow.com/q/46796451
tags question: http://stackoverflow.com/q/46816393
tags question: http://stackoverflow.com/q/46817348
tags question: http://stackoverflow.com/q/46855947
tags question: http://stackoverflow.com/q/46821838
tags question: http://stackoverflow.com/q/46834186
tags question: http://stackoverflow.com/q/46764479
tags question: http://stackoverflow.com/q/46879064
tags question: http://stackoverflow.com/q/46832760
tags question: http://stackoverflow.com/q/46823861
tags question: http://stackoverflow.com/q/46896727
tags question: http://stackoverflow.com/q/46868855
tags question: http://stackoverflow.com/q/46784707
tag name: dictionary
tags question: http://stackoverflow.com/q/46894995
tags question: http://stackoverflow.com/q/46760282
tags question: http://stackoverflow.com/q/46868164
tags question: http://stackoverflow.com/q/46761892
tags question: http://stackoverflow.com/q/46872756
tags question: http://stackoverflow.com/q/46835197
tags question: http://stackoverflow.com/q/46805697
tags question: http://stackoverflow.com/q/46798445
tags question: http://stackoverflow.com/q/46817386
tags question: http://stackoverflow.com/q/46897949
tags question: http://stackoverflow.com/q/46762929
tags question: http://stackoverflow.com/q/46752489
tags question: http://stackoverflow.com/q/46819090
tags question: http://stackoverflow.com/q/46882871
tags question: http://stackoverflow.com/q/46787155
tags question: http://stackoverflow.com/q/46762939
tags question: http://stackoverflow.com/q/46889762
tags question: http://stackoverflow.com/q/46754415
tags question: http://stackoverflow.com/q/46758093
tags question: http://stackoverflow.com/q/46856540
tags question: http://stackoverflow.com/q/46793033
tags question: http://stackoverflow.com/q/46859181
tags question: http://stackoverflow.com/q/46831228
tags question: http://stackoverflow.com/q/46782184
tags question: http://stackoverflow.com/q/46759620
tags question: http://stackoverflow.com/q/46862450
tags question: http://stackoverflow.com/q/46760442
tags question: http://stackoverflow.com/q/46854137

http://stackoverflow.com/comment/80468374
type: Comment
comment on: http://stackoverflow.com/q/46761495
type: QuestionComment
has text: @Unni No what I mean is I have the string `103` I would like to make it get seperate which make it to show something is like `1 0 3`. How I can do that?
score: 0

http://stackoverflow.com/comment/80470388
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46762536
has text: `i` is just a name. Conceptually, you're using it as an index. But, using a short, meaningless name like `i` or `ii` (or `x`, or whatever) usually hints to other programmers that it's just something temporary.

http://stackoverflow.com/comment/80617921
score: 0
type: QuestionComment
has text: Possible duplicate of [How to sort a list of strings?](https://stackoverflow.com/questions/36139/how-to-sort-a-list-of-strings)
type: Comment
comment on: http://stackoverflow.com/q/46835119

http://stackoverflow.com/q/46830958
tagged with: python
tagged with: text-based
type: AnsweredQuestion
type: Question
has body: So I'm trying to arrange how the gameplay of my text base game will function if the player may/not have certain items in their inventory. print ("You are back in your cell. You saw your bed, broken sink, grotty toilet, cut up jumpsuit") if "comb" and "razor" in inventory: print ("and the table with the empty bottle.") else "comb" not in inventory and "razor" in inventory: print ("and the table with the empty bottle and comb.") else "razor" not in inventory and "comb" in inventory: print ("and the table with the empty bottle and razor") it is telling me that I have a syntax error in this line of code else "comb" not in inventory and "razor" in inventory: I can't seem to see what mistake I have made, I am a beginner so perhaps there is an alternative way of executing my needs.
tagged with: inventory
accepted answer: http://stackoverflow.com/a/46833215
has answer: http://stackoverflow.com/a/46831194
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/46833215
possible better answer: http://stackoverflow.com/a/46831194
has comment: http://stackoverflow.com/comment/80609343
has title: Inventory help Python

http://stackoverflow.com/comment/80466389
score: 0
type: Comment
type: QuestionComment
has text: Try this? `zscore = lambda x: (x - x.mean()) / x.std(); df.groupby([df.Date, df.Style])'F1', 'F2', 'F3'.apply(zscore)` This should work.
comment on: http://stackoverflow.com/q/46760318

http://stackoverflow.com/comment/80461533
has text: It did - I marked your answer below as the correct. Now I need to add a redirect to the class based view to complete.
comment on: http://stackoverflow.com/q/46757725
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46763851
has comment: http://stackoverflow.com/comment/80472978
score: 0
has body: driver.title returns a string I believe what you're trying to do is more inline with: assert self.driver.title == "Facebook – log in or sign up"
type: Answer
accepted answer of: http://stackoverflow.com/q/46763675
answers question: http://stackoverflow.com/q/46763675
type: AcceptedAnswer

http://stackoverflow.com/a/46895771
has body: Welcome to SO and glad u chose Python :). If you are new to Python and intend to work with tables do not hesitate to learn pandas. There are tons of documents and questions about pandas. Examples: import pandas as pd url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true' df = pd.read_json(url) And from pandas.io.json import json_normalize df = pd.concat(json_normalize(df["segments"].values[i]) for i in range(len(df))) With pandas you can output to list, dictionaries, csv, json and so on... Here is a snippet that returns html table with first 3 rows: print(df.head(3).to_html(index=False)) Result arrivalDate carrierCode departureDate destination.cityLabel destination.label destination.rrcode duration inventory onboardServices origin.cityLabel origin.label origin.rrcode physicalSpace quotations.12-HAPPY_CARD.cos quotations.12-HAPPY_CARD.cosLevel quotations.12-HAPPY_CARD.fareCode quotations.12-HAPPY_CARD.fareCondition.conditions quotations.12-HAPPY_CARD.fareCondition.fareName quotations.12-HAPPY_CARD.fareSequence quotations.12-HAPPY_CARD.fareSpecificRule quotations.12-HAPPY_CARD.passengerType trainNumber trainType transporter travelClass 2017-11-01T19:46 SN 2017-11-01T16:41 Grenoble Grenoble FRGNB 185 wdi [BAR, HAN, SMP] Paris Paris Gare de Lyon FRPLY B BN 17 HC16 [Pièce d'identité à présenter à bord du train.... TGVmax None None PT00AD 6921 TGD tgv 2 2017-11-01T17:45 SN 2017-11-01T14:41 Grenoble Grenoble FRGNB 184 wdi [BAR, HAN, SMP] Paris Paris Gare de Lyon FRPLY B BN 17 HC16 [Pièce d'identité à présenter à bord du train.... TGVmax None None PT00AD 6919 TGD tgv 2 2017-11-01T10:44 SN 2017-11-01T07:41 Grenoble Grenoble FRGNB 183 wdi [VEP, BAR, HAN, SMP] Paris Paris Gare de Lyon FRPLY B BN 17 HC16 [Pièce d'identité à présenter à bord du train.... TGVmax None None PT00AD 6905 TGS tgv 2
score: 0
has comment: http://stackoverflow.com/comment/80747516
answers question: http://stackoverflow.com/q/46895204
type: Answer
has comment: http://stackoverflow.com/comment/80744607

http://stackoverflow.com/q/46803122
has comment: http://stackoverflow.com/comment/80553067
has body: I am currently having the dataset like- customerID store_code mode BBID_204100102 2655 a BBID_204100102 2906 b BBID_204100102 2906 d BBID_204100150 4986 c BBID_204100150 4986 a BBID_204100277 4986 d BBID_204100310 4986 d and i want something like customerID store_code a b c d 0 BBID_204100102 2655 1 0 0 0 1 BBID_204100102 2906 0 1 0 0 2 BBID_204100150 4986 1 0 1 0 3 BBID_204100277 4986 0 0 0 1 4 BBID_204100310 4986 0 0 0 1 first of it makes pivot on customer ud and student id and then it will encode mode in above manner.
linked to: http://stackoverflow.com/q/37292872
has title: How to get join values in pivot?
tagged with: pandas
has answer: http://stackoverflow.com/a/46803194
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
answer count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/80553028
accepted answer: http://stackoverflow.com/a/46803194
has comment: http://stackoverflow.com/comment/80553742
has answer: http://stackoverflow.com/a/46803393
possible better answer: http://stackoverflow.com/a/46803393
downvote count: 0

http://stackoverflow.com/comment/80682242
comment on: http://stackoverflow.com/q/46867307
type: Comment
type: QuestionComment
has text: I forgot; the OS is Ubuntu 16.04 and after the installation I have updated both my PYTHONPATH that LD_LIBRARY_PATH export PYTHONPATH=$PYTHONPATH:$HOME/Software/VTK/build/Wrapping/Python/:$HOME/Software/VTK/build/bin export LD_LIBRARY_PATH=$HOME/Software/VTK/build/bin:/usr/local/lib/:$LD_LIBRARY_PATH
score: 0

http://stackoverflow.com/comment/80663254
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46857703
has text: @adda.fuentes Did you check the docs for the `count` method? It likely takes a string, not a list. There's only 1 function call on the line the trace points to. That would have been a good place to start debugging this yourself.

string-formatting
tags question: http://stackoverflow.com/q/46812643
tags question: http://stackoverflow.com/q/46768088
tag name: string-formatting
tags question: http://stackoverflow.com/q/46854740
type: Tag
tags question: http://stackoverflow.com/q/46842412

http://stackoverflow.com/comment/80684466
has text: can you add your input string? Please add an as an example for my_string so we can test it.
score: 0
comment on: http://stackoverflow.com/q/46868534
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80527552
type: Comment
comment on: http://stackoverflow.com/a/46790028
score: 0
type: AnswerComment
has text: @josh - I never see it before, can you explain more? In my opinion the best is the more general solution, if problem with timezones I think OP give comment. Or do you think is not good `dates = pd.to_datetime(df['INTV'])` ? If yes, why? Can you explain?

http://stackoverflow.com/a/46758859
has comment: http://stackoverflow.com/comment/80463669
has comment: http://stackoverflow.com/comment/80463753
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80463873
has comment: http://stackoverflow.com/comment/80463721
upvote count: 3
type: Answer
has body: awk to the rescue. Case (1), filtering according to the values in the first column ($1): $ awk -F'\t' '$1~"here" {print}' file secondline:is:here VHNBVFTYHNBGHJMKJHJMN 0:0:0:0:0 - third:canbefound:here VFTYHBVFGHJNJGVGHJKMNGB 4:1:0:1:0 - (Where we print the complete line if the first column, $1, contains the pattern/string here.) Case (2), filter according to the values in the first column, but only if the third column contains at least one non-zero element: $ awk -F'\t' '$3~/(^|:)[1-9]+(:|$)/ &amp;&amp; $1~"here" {print}' file third:canbefound:here VFTYHBVFGHJNJGVGHJKMNGB 4:1:0:1:0 - (Where in addition to the condition from the previous case, we ensure the third column, $3, contains the pattern :&lt;one_or_more_digits_except_zero&gt;:, with the starting colon : is omitted on the start and end of the value.)
has comment: http://stackoverflow.com/comment/80463933
downvote count: 0
accepted answer of: http://stackoverflow.com/q/46758555
answers question: http://stackoverflow.com/q/46758555
score: 3

http://stackoverflow.com/q/46897380
has comment: http://stackoverflow.com/comment/80743787
tagged with: arrays
has body: Here is the code, I am using python 3.5 from scipy.optimize import fsolve from scipy.integrate import dblquad from numpy import sqrt,cos,pi,absolute Ueh=2320.5 Uhh=2192.5 ED=120 LCP=-59.28179796 UCP=-58.96721714 def Ih(mu,x): var,err= dblquad(lambda ky, kx: 1/sqrt((ED-mu-2540*(2-cos(kx)-cos(ky)))**2+x**2)/8/pi/pi, -pi, pi, lambda kx:-pi,lambda kx: pi) return var def Ie(mu,x): var,err= dblquad(lambda ky, kx: 1/sqrt((2540*(2-cos(kx)-cos(ky))-mu)**2+x**2)/8/pi/pi, -pi, pi, lambda kx:-pi,lambda kx: pi) return var def spp(mu,p): x, y = p return (absolute(x)-2*Ueh*absolute(y)*Ih(mu,y),4*Ueh**2*Ie(mu,x)*Ih(mu,y)/(1+Uhh*Ih(mu,y))-1) def spm(mu,y): return Uhh*Ih(mu,y)-1 def sis(mu,p): x,y=p return(Uhh*Ih(mu,y)-1, Ie(mu,x)*2*Ueh**2/Uhh-1) def solution(mu): if mu&lt;=LCP: Dele=0 Delh=fsolve(lambda y:spm(mu,y),4) phase=0 elif mu&gt; LCP and mu&lt;UCP: Dele,Delh=fsolve(lambda p: sis(mu,p),(4,4)) phase=-Uhh/2/Ueh*Dele/Delh elif mu&gt;=UCP: Dele,Delh=fsolve(lambda p: spp(mu,p),(9,4)) phase=-1 return Dele,Delh,phase if I take mu=-60, following if mu&lt;=LCP, print(solution(-60)) (0, array([ 4.1349274]), 0) it I take mu in two other elif, the return is without array print(solution(-59)) (8.2553379473241311, 4.1210736864119193, -0.94635157721569463) print(solution(-58)) (8.9677408867771558, 4.2580061198120394, -1) How to change it to make the first return has same format as other two? I know I could take [0] from a array to get the number. It would be better If I could understand what is the reason the fsolve return array in the first case?
score: 0
linked to: http://stackoverflow.com/q/431866
has comment: http://stackoverflow.com/comment/80745485
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/80746696
has comment: http://stackoverflow.com/comment/80754828
has comment: http://stackoverflow.com/comment/80746773
type: Question
has title: fsolve return array instead of number

http://stackoverflow.com/a/46877557
answers question: http://stackoverflow.com/q/46877403
has comment: http://stackoverflow.com/comment/80709887
downvote count: 0
type: Answer
has body: The post by Tim Peters correctly explains that what you are seeing is rounding towards the nearest even integer in Python 3. If you want to have Python 3 return numbers rounded to the nearest integer instead of the nearest even integer use numpy.floor(np.float(x)+0.5) instead of numpy.rint(x) For example: for i in range(5,105,10): print(i,np.floor(np.float(i)/10+0.5)) prints 5 1.0 15 2.0 25 3.0 35 4.0 ...... 75 8.0 85 9.0 95 10.0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/80707571

http://stackoverflow.com/q/46854740
favorite count: 0
has comment: http://stackoverflow.com/comment/80657010
tagged with: python-3.x
tagged with: string-formatting
tagged with: python
type: AnsweredQuestion
has body: &gt;&gt;&gt; class MyInt(int): ... def __rmod__(self, other): ... return 42 ... &gt;&gt;&gt; class MyStr(str): ... def __rmod__(self, other): ... return 'wat' ... &gt;&gt;&gt; 0 % MyInt() 42 &gt;&gt;&gt; '%r' % MyStr() "''" Why is the int subclass able to control this BinOp from the reflected side, but str can not? This seems to contradict the documented datamodel. I was hoping to use the feature to create a non-intrusive and backwards-compatible extension providing curly-braces-style handlers/formatters for the logging framework, but this stopped me in my tracks. Is that a bug? Python 3.6.0 on Linux. Using collections.UserString as a base class also has the issue. Using bytes as a base does not.
type: Question
accepted answer: http://stackoverflow.com/a/46854813
has title: Why doesn't __rmod__ work properly for strings?
tagged with: subclassing
upvote count: 3
score: 0
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/46854813
duplicate of: http://stackoverflow.com/q/40402235

http://stackoverflow.com/q/46751453
has answer: http://stackoverflow.com/a/46751550
accepted answer: http://stackoverflow.com/a/46751550
has body: I am trying to check if expressions with substrings of length 3 contain exactly one c character. That is, every substring of length 3 in a string must contain a c character. For example: Strings such as: "a", "cc", "bbc", "cabcbbca", "acaacbacbb", "abcabcabc", all have exactly one c in their substrings of length 3. If any substrings have less than length 2, then they are valid regardless. However, strings such as: "caaa", "bbcaacbcaac", fail this requirement as they contain substrings of length 3 that don't contain exactly one c character. So far I have made a quick python program which checks this: # Testing expressions expressions = ["a", "cc", "bbc", "cabcbbca", "acaacbacbb", "abcabcabc", "caaa", "bbcaacbcaac"] # Getting substrings of a certain length def get_substrings(string, sublen): substrs = [] for i in range(len(string)): if len(string[i:i+sublen]) == sublen: substrs.append(string[i:i+sublen]) return substrs # extracting valid expressions def get_valid_expression(expressions, minlen, char_to_check): valid = [] for string in expressions: # if string is less than min length, then it is already valid if len(string) &lt; minlen: valid.append(string) else: # get the subtrings lst = get_substrings(string, minlen) # Check if the substring contains exactly one of the characters if all(substring.count(char_to_check) == 1 for substring in lst): valid.append(string) return valid print("Valid expressions with all substrings of length 3 containing exactly one c:") print(get_valid_expression(expressions, 3, "c")) Which returns the valid expressions['a', 'cc', 'bbc', 'cabcbbca', 'acaacbacbb', 'abcabcabc'] from the original list. Is their a way with regex I can do this? I believe generating a regular expression to search this would be better and not require much code.
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: substring
type: Question
has title: Using regex to check subsequences of string
score: -1
answer count: 1
downvote count: 1
tagged with: string
favorite count: 0
upvote count: 0

http://stackoverflow.com/comment/80677630
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46864539
has text: @Trig: printing the whole list at the beginning will give you a different o/p. Did you mean print(mapax[repeticiones])?

http://stackoverflow.com/a/46765050
has body: I have done small changes to your code for conversion of float numbers to integers. It is running without errors now. Check this: import numpy as np import cv2 import os from scipy import ndimage img = cv2.pyrDown(cv2.imread('img.jpeg')) ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY) image, contours, heir = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: x, y ,w ,h = cv2.boundingRect(c) cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2) rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img, [box], 0 , (0, 0, 255), 3) (x,y), radius = cv2.minEnclosingCircle(c) x = np.round(x).astype("int") y = np.round(y).astype("int") center = (x,y) radius = np.round(radius).astype("int") cv2.circle(img, center, radius, (0,255, 0), 2) cv2.drawContours(img, contours, -1, (255, 0, 0), 1) cv2.imshow('contours',img) cv2.waitKey(0) cv2.destroyAllWindows()
type: Answer
answers question: http://stackoverflow.com/q/46764711
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90997148
downvote count: 0

http://stackoverflow.com/comment/80491295
has text: if abs solves this issue then yeah, I was referring to what @Wen said
type: Comment
comment on: http://stackoverflow.com/a/46772454
score: 0
type: AnswerComment

http://stackoverflow.com/comment/80450055
type: QuestionComment
score: 0
has text: thanks for @Momin and {aUXcoder} to edit, help my question
type: Comment
comment on: http://stackoverflow.com/q/46751551

http://stackoverflow.com/comment/80675966
type: Comment
type: AnswerComment
has text: Thank You very much, gonna test it :), lol, there's no other one2many field, thankfully hehe
comment on: http://stackoverflow.com/a/46843285
score: 0

http://stackoverflow.com/comment/80671901
type: QuestionComment
comment on: http://stackoverflow.com/q/46862000
score: 1
has text: The build window is a text window like a console. What makes you think that it can show graphics? Is there any hint or evidence for that?
type: Comment

http://stackoverflow.com/q/46895916
has title: Most Frequent Character-Issue - Python?
score: -1
has body: I am trying to Write a program that lets the user enter a string and displays the string that was entered and the most frequently occurring character in the string. The program can treat upper and lower-case characters the same. If there is tie, then both characters should be output. Use the following strings to test the program: The House on Haunted Hill Python programming is fun Gone with the Wind The program works as its intended only on "Python programming is fun", but I only get the frequency of the character on the other 2, but not the letter. def main(): string = input('Enter a sentence: ') string.lower() counter = 0 total_counter = 0 most_frequent_character = "" for ch in string: for str in string: if str == ch: counter += 1 if counter &gt; total_counter: total_counter = counter most_frequent_character = ch counter = 0 print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.") main()
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/80739010
has comment: http://stackoverflow.com/comment/80738986
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/46896366
has comment: http://stackoverflow.com/comment/80738960
tagged with: python
has comment: http://stackoverflow.com/comment/80738932
has answer: http://stackoverflow.com/a/65526520
has answer: http://stackoverflow.com/a/46896154
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/46896072
has comment: http://stackoverflow.com/comment/80739044
has answer: http://stackoverflow.com/a/46896067

http://stackoverflow.com/q/46883925
has comment: http://stackoverflow.com/comment/80721516
has comment: http://stackoverflow.com/comment/80720684
type: Question
linked to: http://stackoverflow.com/q/115974
score: 0
has body: New Python with a small (large) OOP problem that can not be solved :( I downloaded an example of a running code for a webserver implemented by BaseHTTPServer So far everything is fine, I tried to call the do_GET method through my "external" class The script stopped working with the error message: Traceback (most recent call last): File "/usr/lib/python2.7/SocketServer.py", line 290, in _handle_request_noblock self.process_request(request, client_address) File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request self.finish_request(request, client_address) File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__ self.handle() File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle self.handle_one_request() File "/usr/lib/python2.7/BaseHTTPServer.py", line 328, in handle_one_request method() File "./webserver.py", line 41, in do_GET MyHTTPHandlerClass.m_HTTPRequestHandler.do_GET(self) AttributeError: 'module' object has no attribute 'do_GET' What is the best way to solve the problem? Thanks! webserver.py #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import argparse import HTTPRequestHandler import BaseHTTPServer import logging import os import sys def make_request_handler_class(opts): MyHTTPRequestHandler = HTTPRequestHandler MyHTTPRequestHandler.m_opts = opts return MyHTTPRequestHandler def make_http_handler_class(opts, localHTTPRequestHandler): ''' Factory to make the request handler and add arguments to it. It exists to allow the handler to access the opts.path variable locally. ''' class MyHTTPHandlerClass(BaseHTTPServer.BaseHTTPRequestHandler): m_opts = opts m_HTTPRequestHandler = localHTTPRequestHandler def do_HEAD(self): ''' Handle a HEAD request. ''' logging.debug('HEADER %s' % (self.path)) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): MyHTTP…
has comment: http://stackoverflow.com/comment/80720109
tagged with: python
has comment: http://stackoverflow.com/comment/80720585
has comment: http://stackoverflow.com/comment/80719658
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80718386
has comment: http://stackoverflow.com/comment/80718047
has title: Python - BaseHTTPServer: external do_GET method outside the scope
has comment: http://stackoverflow.com/comment/80721687

http://stackoverflow.com/a/46844369
score: 0
answers question: http://stackoverflow.com/q/46844000
type: Answer
has body: Pyspark dataframes don't have indexes. You can create one, but note that any shuffle operation (group, join...) that took place before the creation of the index might have changed the order of your rows. import pyspark.sql.functions as psf start = 400 end = 700 df2 = df1.rdd.zipWithIndex()\ .map(lambda l: [l[1]] + list(l[0]))\ .toDF(["index"] + df1.columns)\ .filter(psf.col("index").between(start, end)) Another way is to collect only the first rows of your dataframe into a list: df2 = spark.createDataFrame(df1.head(end)[start:], df1.columns) or using Pandas: df2 = spark.createDataFrame(df1.limit(end).toPandas().iloc[start:, :])

http://stackoverflow.com/a/53967684
has comment: http://stackoverflow.com/comment/133101521
score: 15
has body: My answer: set_headless(headless=True) is deprecated. https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html options.headless = True works for me
answers question: http://stackoverflow.com/q/46753393
has comment: http://stackoverflow.com/comment/137615127
type: Answer
upvote count: 15
downvote count: 0

http://stackoverflow.com/q/46826139
type: Question
tagged with: nltk
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/75028060
favorite count: 0
has title: Error(urlopen) while downloading data from python shell (nltk)
type: UnansweredQuestion
tagged with: python
has body: I have tried: Changing server index Updating proxy Re-installing python and nltk Downloading numpy ( It was installed properly but threw an exception on cleaning) I want to download a stopword list. If this doesn't workout, I will really appreciate if you can suggest me a way to do the same by downloading zip files and physically storing them in the folder or any other method. Thank you! Here are the error snippets: 1. $ python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4]enter code here on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download('all') [nltk_data] Error loading all: &lt; urlopen error [Errno 111] Connection [nltk_data] refused&gt; False &gt;&gt;&gt; 2. &gt;&gt;&gt; nltk.download() Downloader&gt; l Packages: Error connecting to server: [Errno 111] Connection refused
tagged with: corpus
upvote count: 1
has answer: http://stackoverflow.com/a/46829000
downvote count: 1

http://stackoverflow.com/a/46846995
has body: As mentioned in Eric Duminil's answer, one way of approaching this is to use difflib.SequenceMatcher.find_longest_match: from difflib import SequenceMatcher upstream_seq = 'ATACATTGGCCTTGGCTTAGACTTAGATCTAGACCTGAAAATAACCTGCCGAAAAGACCCGCCCGACTGTTAATACTTTACGCGAGGCTCACCTTTTTGTTGTGCTCCC' downstream_seq = 'ATACACGAAAAGCGTTCTTTTTTTGCCACTTTTTTTTTATGTTTCAAAACGGAAAATGTCGCCGTCGTCGGGAGAGTGCCTCCTCTTAGTTTATCAAATAAAGCTTTCG' s = SequenceMatcher(None, upstream_seq, downstream_seq) match = s.find_longest_match(0, len(upstream_seq), 0, len(downstream_seq)) print(match) upstream_start = match[0] upstream_end = match[0]+match[2] seq = upstream_seq[match[0]:(match[0]+match[2])] downstream_start = match[1] downstream_end = match[1]+match[2] print("Upstream seq: %s\nstart-stop: %s-%s\n") % (seq, upstream_start, upstream_end) print("Downstream seq: %s\nstart-stop: %s-%s\n") % (seq, downstream_start, downstream_end) Match(a=49, b=5, size=7) Upstream seq: CGAAAAG start-stop: 49-56 Downstream seq: CGAAAAG start-stop: 5-12
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/46846177
score: 1

http://stackoverflow.com/comment/80684028
has text: and it should print out : Feqwgba <3 fnvta effo ox0xiv syfvbxf
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46865070

http://stackoverflow.com/q/46805735
has answer: http://stackoverflow.com/a/46839724
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/38833934
tagged with: tensorflow
has body: I am trying to register a python function and its gradient as a tensorflow operation. I found many useful examples e.g.: Write Custom Python-Based Gradient Function for an Operation? (without C++ Implementation) https://programtalk.com/python-examples/tensorflow.python.framework.function.Defun/ Nonetheless I would like to register attributes in the operation and use these attributes in the gradient definition by calling op.get_attr('attr_name'). Is this possible without going down to C implementation? May you give me an example?
type: Question
has title: Defining tensorflow operations in python with attributes
score: 0
answer count: 1

http://stackoverflow.com/q/46792756
tagged with: proxy
answer count: 1
has title: Python: How can I use urllib or requests modules from a corporate domain (firewall, proxy, cntlm etc)
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/46793880
tagged with: python-requests
type: AnsweredQuestion
upvote count: 5
tagged with: urllib
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/46793880
downvote count: 0
has body: I am trying to do the following: from urllib.request import urlopen data = urlopen("https://www.duolingo.com/users/SaifullahS6").read() I get the following error: URLError: &lt;urlopen error [WinError 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&gt; Similarly, when I try this: import requests session = requests.Session() data = {"login": "SaifullahS6", "password": "mypassword"} req = requests.Request('POST', "https://www.duolingo.com/login", data=data, cookies=session.cookies) prepped=req.prepare() returned = session.send(prepped) I get: ConnectionError: HTTPSConnectionPool(host='www.duolingo.com', port=443): Max retries exceeded with url: /login (Caused by NewConnectionError('&lt;requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000000000E6948D0&gt;: Failed to establish a new connection: [WinError 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',)) I am not sure how to give details of my internet connection. I'm at work and I know we have a corporate proxy. We have Windows Firewall turned on, but i have checked that python and pythonw are ticked in the "Domain" column of the control panel for allowing a program through the firewall. When I ping google.co.uk from a command shell, all four requests time out, but I can access it from a browser. In the Internet Options control panel, I click on the Connections tab and then LAN settings, and I have "Automatically detect settings" turned on, and also "Use a proxy server for your LAN", "Address" is "localhost" and "Port" is 3128. This is cntlm. I set it up once to do download python packages, and it appears to still be active because I have just managed to update one of my packages. I don't even need a direct answer t…

http://stackoverflow.com/comment/80663701
type: Comment
has text: Thank you for really nice answer. It is exactly what I wanted. According to numpy documentation `fromfile` function does support dtype and on your example and my data they both work. Maybe it is worth adding, that time-wise `open` with `frombuffer` is roughly 25% faster than `fromfile`.
type: AnswerComment
comment on: http://stackoverflow.com/a/46850107
score: 0

http://stackoverflow.com/q/46862256
linked to: http://stackoverflow.com/q/45830838
has comment: http://stackoverflow.com/comment/80673034
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/46862663
has comment: http://stackoverflow.com/comment/80672839
favorite count: 0
has comment: http://stackoverflow.com/comment/80672016
type: Question
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/80672053
has comment: http://stackoverflow.com/comment/80672181
has comment: http://stackoverflow.com/comment/80672792
has comment: http://stackoverflow.com/comment/80672101
tagged with: indexing
linked to: http://stackoverflow.com/q/46862148
accepted answer: http://stackoverflow.com/a/46862663
upvote count: 3
has comment: http://stackoverflow.com/comment/80672038
has comment: http://stackoverflow.com/comment/80673015
has answer: http://stackoverflow.com/a/46864422
tagged with: numpy
possible better answer: http://stackoverflow.com/a/46862564
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/46862564
has title: Determine the position of each element of an array B in another array A
has comment: http://stackoverflow.com/comment/80672119
has body: Given two lists: In [518]: A Out[518]: [3, 4, 2, 1, 7, 6, 5] In [519]: B Out[519]: [4, 6] Every element in B exists in A, without exception. I'd like to retrieve an array of indexes for B as seen in A. For example, 4 is present in index 1 in A, and 6 is in position 5 for B. My expected output is [1, 5] for this scenario. This is what I did to get the index: In [520]: np.flatnonzero(np.in1d(a, b)) Out[520]: array([1, 5]) Unfortunately, this won't work in most other cases. For example, if B = [6, 4], my method still outputs [1, 5] when it should output [5, 1]. Is there an efficient numpy way to get what I'm trying to achieve?
has comment: http://stackoverflow.com/comment/80672030

http://stackoverflow.com/comment/80883477
type: QuestionComment
comment on: http://stackoverflow.com/q/46902090
type: Comment
has text: The reason I was using AJAX was because I need to send a javascript object...and am having a lot of trouble figuring out how to do that through a html form? Any tips?
score: 0

http://stackoverflow.com/q/46869092
type: UnansweredQuestion
tagged with: ssh
tagged with: django
tagged with: python
answer count: 0
tagged with: pycharm
score: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/80686451
upvote count: 1
type: Question
has title: Django Cannot Connect to Remote MySQL Server
has comment: http://stackoverflow.com/comment/80689340
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/80685627
has body: I am running a Django and attempting to connect to a MySQL server at my university. First of all: In order to connect the database, I normally SSH into a remote server (with authentication) of theirs, and then run MySQL and enter my MySQL authentications. This works without an issue, in Terminal as well as DataGrip. Now, using PyCharm, I have installed mysqlclient in the intepreter and changed my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '[DB_NAME]', 'USER': '[DB_USERNAME]', 'PASSWORD': '[DB_PASSWORD]', 'HOST': '[REMOTE SERVER ADDRESS HOSTING MYSQL]', 'PORT': '3306', } } Also using PyCharm, I have even opened up a data source in the Data Sources Tool Window and connected through SSH tunnel and MySQL authentication to the database. This is successful, and it is possible to make queries. However, I try to run: manage.py check and I receive: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '[REMOTE SERVER ADDRESS HOSTING MYSQL]' (60)") The above exception was the direct cause of the follow…

http://stackoverflow.com/comment/119197071
type: AnswerComment
type: Comment
has text: @Salchem Findings?
comment on: http://stackoverflow.com/a/46809257
score: 0

http://stackoverflow.com/comment/80540550
type: Comment
has text: I would see if the results are different despite processing time, and if you can "fix" the issue with optimization turned off then start your journey into assembly differences :)
score: 0
comment on: http://stackoverflow.com/q/46796126
type: QuestionComment

http://stackoverflow.com/a/46852909
type: Answer
answers question: http://stackoverflow.com/q/46849799
has body: You can locate null values and return them for assignment in the same step: df.loc[df['End Date'].isnull(), 'End Date'] = &lt;&lt;val&gt;&gt; If you need to locate the group as well: df.loc[(df['End Date'].isnull()) &amp; (df['Group']==&lt;&lt;group&gt;&gt;), 'End Date'] = &lt;&lt;val&gt;&gt; This way you can keep everything in the same dataframe, which is less messy than separating your df and re-merging.
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/46849799
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80569711
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46807209
has text: Either this or you could try to fill ```REQUIRED_PACKAGES``` with your modules, like this: ```REQUIRED_PACKAGES=["google-cloud-spanner==0.26", "another-module==1.0"]``` etc...

http://stackoverflow.com/comment/80654834
comment on: http://stackoverflow.com/q/46852887
score: 0
has text: If your problem is solved by an answer, please accept it. But if you had a different problem, this is unlikely to be very useful to others.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46829989
has body: I wonder if we have a way of enabling the following this: Python script running on Machine1 Machine1 -------pass sudo commands, ssh password, sudo password------> Machine2 Machine1 &lt;--------Get output and store in python variable--------- Machine2 Can we do this without using paramiko?
has comment: http://stackoverflow.com/comment/80607292
score: 0
tagged with: ssh
has comment: http://stackoverflow.com/comment/80607340
has comment: http://stackoverflow.com/comment/80607405
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Any way to execute commands on a remote ssh client from python?
has comment: http://stackoverflow.com/comment/80607260
linked to: http://stackoverflow.com/q/1233655
type: Question
linked to: http://stackoverflow.com/q/3586106

http://stackoverflow.com/a/46801401
answers question: http://stackoverflow.com/q/46800655
score: 1
upvote count: 1
downvote count: 0
has body: I do not why I come up this solution , ugly but work .. df.iloc[df.index[(df.E=='test').eq(1)].values[0]:df.index[(df.E=='tested').eq(1)].values[0]+1,:] Out[151]: A B C D E 0 1.0 2013-01-02 1.0 1 test 1 1.0 2014-01-02 1.0 2 car 2 1.0 2015-01-02 1.0 3 tested
type: Answer

http://stackoverflow.com/q/46828086
type: Question
has answer: http://stackoverflow.com/a/46828289
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 2
has title: How to assign result to a variable AND print result in one command in Python?
has answer: http://stackoverflow.com/a/46828134
has comment: http://stackoverflow.com/comment/80603996
type: UnansweredQuestion
tagged with: python
has body: In R, when you assign something to a variable, you can wrap your code in brackets to also print the result: &gt; a&lt;-1+2 &gt; a 3 &gt;(a&lt;-1+2) 3 Is there an equivalent feature in python?

http://stackoverflow.com/a/46833608
downvote count: 0
score: 1
has body: You need to put the return value of the function into a variable to be able to evaluate it (I also corrected a few bugs in your code, mainly typos): import random import os def startGame(): answer = input('Do you want to play Super Dice Roll?\nEnter 1 for Yes\nEnter 2 for No\n') os.system('cls') while answer == '1': answer = rollDice() if answer == '2': print('Thank you for playing!') else: print('That isn/t a valid selection.') startGame() def rollDice(): input('Press Enter to roll dice.') os.system('cls') dice = sum(random.randint(1,6) for x in range (2)) print('you rolled ', dice, '\n') choice = input('Do you want to play again?\nEnter 1 for Yes\nEnter 2 for No.\n') return choice def main(): print('!~!~!~!~WELCOME TO SUPER DICE ROLL~!~!~!~!~\n') startGame() print('Thank you for playing') main()
has comment: http://stackoverflow.com/comment/80615305
has comment: http://stackoverflow.com/comment/80616392
has comment: http://stackoverflow.com/comment/80615359
has comment: http://stackoverflow.com/comment/80615380
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80616015
type: Answer
answers question: http://stackoverflow.com/q/46833451
accepted answer of: http://stackoverflow.com/q/46833451

http://stackoverflow.com/a/46804977
has comment: http://stackoverflow.com/comment/80557449
downvote count: 0
answers question: http://stackoverflow.com/q/46804799
type: Answer
has body: First thing first: having one extra closing brace means this is not valid json, so the best thing to do would be to cure the problem at the source. If this comes verbatim from some api then contact the tech staff, if this comes from your own code then fix it where this extra brace is introduced. This being said, assuming your json is stored as a string data, then removing the last closing brace is as simple as data = data.strip().rstrip("}") If this is part of an automated process and you only sometimes have this extraneaous brace, you can test before cleaning up: if data.count("}") &gt; data.count("{"): data = data.strip().rstrip("}")
upvote count: 2
has comment: http://stackoverflow.com/comment/80557054
score: 2

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/46882424
tags question: http://stackoverflow.com/q/46782048
tags question: http://stackoverflow.com/q/46771611
type: Tag

http://stackoverflow.com/a/46777024
score: 3
accepted answer of: http://stackoverflow.com/q/46776628
answers question: http://stackoverflow.com/q/46776628
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90796729
downvote count: 0
has body: You don't need to reinstall entire SQL Server. Just use Add Features to an Instance of SQL Server (Setup) New SQL Server stand-alone installation or add features to an existing installation. And select desired components: Image source: https://www.sqlshack.com/wp-content/uploads/2017/06/word-image-215.png More info: How to use Python in SQL Server 2017 to obtain advanced data analytics
type: Answer
has comment: http://stackoverflow.com/comment/90796725
has comment: http://stackoverflow.com/comment/80517109
upvote count: 3
has comment: http://stackoverflow.com/comment/90817685

http://stackoverflow.com/comment/80536619
type: QuestionComment
comment on: http://stackoverflow.com/q/46781448
has text: Thanks Vivek. I've definitely used sklearn pipelines with custom transformers that accept/return a pandas dataframe before, still trying to figure out why my old one worked and this seemingly minimal example doesn't. I think you're probably right about gridSearchCV being the issue, I used a custom cv iterator on my last project...
score: 0
type: Comment

http://stackoverflow.com/comment/80566961
type: Comment
type: QuestionComment
has text: **Never** create two root windows `xx = Tk()` in the same application. Use Toplevel() for windows other than the root window. But that's not the cause of what you're seeing. That is a parenting problem.
comment on: http://stackoverflow.com/q/46809771
score: 0

http://stackoverflow.com/q/46869155
has comment: http://stackoverflow.com/comment/80685595
has answer: http://stackoverflow.com/a/49074907
has answer: http://stackoverflow.com/a/57705626
type: Question
has title: Trying to convert a hexdump from Python2 to Python3
answer count: 2
has comment: http://stackoverflow.com/comment/80685641
linked to: http://stackoverflow.com/q/19877306
score: 0
has comment: http://stackoverflow.com/comment/80685578
linked to: http://stackoverflow.com/q/14066883
tagged with: hexdump
has comment: http://stackoverflow.com/comment/80685739
type: UnansweredQuestion
tagged with: python
has body: So I've been learning Python3 for the last month or so. I'm going through "Black Hat Python" by Justin Seitz right now, but all of the code is in Python2. Most of the code so far was easy to convert to Python3, but I ran across a hexdump function in a tcp_proxy program that has me stumped. Below is the Python2 code from the book. def hexdump(src, length=16): result = [] digits = 4 if isinstance(src, unicode) else 2 for i in xrange(0, len(src), length): s = src[i:i+length] hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s]) text = b''.join([x if 0x20 &lt;= ord(x) &lt; 0x7F else b'.' for x in s]) result.append(b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text)) print b'\n'.join(result) I have a few questions that I haven't been able to find online. Why would digits need to be unpacked if it's a single int? Would the equivalent of "%0*X" % (digits, ord(x)) be "{0:X}".format(*digits, ord(x))? Why are there two arguments for this? I noticed that there was an additional argument in result.append() as well. Any help would be greatly appreciated.
has comment: http://stackoverflow.com/comment/80702012

http://stackoverflow.com/comment/80575657
type: QuestionComment
has text: I am not asking you nothing, if you dont want to help dont help.
comment on: http://stackoverflow.com/q/46813949
score: 0
type: Comment

http://stackoverflow.com/a/46858351
score: 0
type: Answer
has body: In a big loop? You could just load the csv file as string so you only have to look through your list once instead of for every item. Though its not really very efficient as python strings are immutable, your still facing the same problem either way. According to this answer Optimizing find and replace over large files in Python (re the efficiency), Maybe line by line would work better so you don't have the giant string in memory if that actually becomes a problem. edit: So something like this... # open original and new file. with open(old_file, 'r') as old_f, open(new_file, 'w') as new_f: # loop through each line of the original file (old file) for old_line in old_f: new_line = old_line # loop through your dictionary of replacements and make them. for r in replacements: new_line = new_line.replace(r, replacements[r]) # write each line to the new file. new_f.write(new_line) Anyway I would forget the file is a csv file and just treat it like a big collections of lines or characters.
answers question: http://stackoverflow.com/q/46856979

http://stackoverflow.com/q/46883601
tagged with: python
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/46883680
score: 2
type: AnsweredQuestion
type: Question
answer count: 2
has title: Failed test #2. Wrong answer
downvote count: 0
has answer: http://stackoverflow.com/a/46883737
has answer: http://stackoverflow.com/a/46883680
has body: The input for this program are two sets. Each set in a separate line; elements of the set are space separated. Your program must output the symmetric difference of these sets. Example Symmetric difference of the sets {1, 2, 3} and {0, 1, 2} equals to {0, 3}. Sample Input: 1 2 3 0 1 2 Sample Output: 0 3 My Solution : set_1 = set(input()) set_2 = set(input()) difference_set1 = set_1 - set_2 difference_set2 = set_2 - set_1 for x in difference_set1: difference_set2.add(x) for x in difference_set2: print(x, end=' ') Test Results are failing... Can somebody please explain :
favorite count: 0
possible better answer: http://stackoverflow.com/a/46883737

http://stackoverflow.com/a/46910937
answers question: http://stackoverflow.com/q/46891359
has body: Ok, it now opens a window and shows the output of the camera Because of this code: import sys sys.path.append('/home/pi/.virtualenvs/cv/lib/python2.7/site- packages/usr/local/lib/python2.7/site-packages') and i also use sudo python program.py in the terminal But this Error :"NameError: name 'CV_CAP_PROP_FRAME_HEIGHT' is not defined" still persists...
score: 0
type: Answer

http://stackoverflow.com/q/46840920
tagged with: aws-cloudformation
has comment: http://stackoverflow.com/comment/80644500
type: Question
has title: Invoke Lambda from CloudFormation template or vice-versa
tagged with: amazon-web-services
tagged with: aws-lambda
score: 0
has comment: http://stackoverflow.com/comment/80630312
tagged with: python
tagged with: ruby
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80655428
has body: Sometimes I need certain fields in a CF template to be dynamically generated from a list of complex objects, currently I don't know of any way to loop over anything using CF functions so parts of the execution is delegated to Lambdas -- by providing the list of parameters as character-delimited strings -- which in turn use the Python/Ruby AWS SDK to create other resources. It seems to me that it would be easier to invoke a Lambda first, that Lambda would dynamically construct the CF stack given an arbitrarily complex JSON payload without having to encode list of objects as character-delimited strings. This seems like inverting the current pattern I have where the CF template invokes Lambdas and instead have a Lambda receive the parameters and then create the CF stack using Python/Ruby SDK (as part of the Lambda execution). I haven't found much about this pattern being a bad idea or it being discouraged but I also haven't found many examples of it on the web. Btw, I'm quite new to CF and Lambdas so I'm not sure if this is a no-no for AWS/CF/Lambdas, so this question is partly to figure that out. Example Creating an ECS task definition with a dynamic list of port mappings: "ecsTask":{ "Properties":{ # ... other stuffs "container_definitions": [ { "name": {"Ref":"AWS::StackName"}, "image": {"Ref":"DockerImage"}, "portMappings": [ # ... dynamic list of ports, example below { "ContainerPort": "123", "HostPort": "456" }, ], "environment":{ "Ref": "EnvironmentVariables" }, # ... other stuffs } ] },
has comment: http://stackoverflow.com/comment/80685389

http://stackoverflow.com/comment/80525795
comment on: http://stackoverflow.com/a/46789472
type: AnswerComment
type: Comment
has text: this is awesome, now I definitely have to upgrade to python 3.6. thanks :)
score: 0

http://stackoverflow.com/comment/104936167
comment on: http://stackoverflow.com/a/48721478
score: 1
type: AnswerComment
type: Comment
has text: For latest version of sklearn (0.19.1) use from sklearn.feature_extraction.text import HashingVectorizer instead of from sklearn.feature_extraction.text import HashingVectoriser

oauth-2.0
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/46893628
type: Tag

http://stackoverflow.com/comment/80560373
has text: At first I would expect the index to change. With your code `KIND1` and `KIND2` should be the same.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46806615

http://stackoverflow.com/q/46751667
type: Question
answer count: 1
has body: I have a pretty short python program to map my RAM usage over time. while i &lt; 1000000000000: x.append(i); y.append(psutil.virtual_memory().used); plt.plot(x,y) i+=1; plt.show() plt.pause(0.0001) For some reason, this graph changes color every time a new data point is added. Does this have anything to do with the plt.ion() I have? It also re-opens every time I close it. Do you guys have any solutions? Thanks in advance!
duplicate of: http://stackoverflow.com/q/16006572
tagged with: python-2.7
score: 0
has title: Matplotlib Multi-Colored Graph Python
has comment: http://stackoverflow.com/comment/80454574
has comment: http://stackoverflow.com/comment/80451795
tagged with: python
has comment: http://stackoverflow.com/comment/80449208
accepted answer: http://stackoverflow.com/a/46751759
linked to: http://stackoverflow.com/q/16006572
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80449301
tagged with: matplotlib
has answer: http://stackoverflow.com/a/46751759

http://stackoverflow.com/comment/80481291
type: Comment
comment on: http://stackoverflow.com/q/46767681
type: QuestionComment
has text: I guess what you are trying to do has left the area of unittests and it is already an end to end or behavior test. The normal test client is not made for this. You might want to have a look at the live test server: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#liveservertestcase
score: 0

http://stackoverflow.com/q/46833218
has answer: http://stackoverflow.com/a/48446564
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/48446564
has body: I am trying to use gmplot for the first time. I installed it fine. I was trying to run the sample code just to see it work before I started to do anything, and got this: AttributeError: module 'gmplot' has no attribute 'GoogleMapPlotter' Below is the sample code for gmplot: import gmplot gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16) gmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10) gmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False) gmap.scatter(marker_lats, marker_lngs, 'k', marker=True) gmap.heatmap(heat_lats, heat_lngs) gmap.draw("mymap.html") I installed Google API Client Libraries pip install --upgrade google-api-python-client and then upgraded gmplot. pip install --upgrade gmplot I tried running it with Python 2.7 and 3.6. All with the same result. Any ideas?
favorite count: 0
tagged with: google-maps-api-3
has comment: http://stackoverflow.com/comment/83994565
tagged with: python
score: 1
has title: Python gmplot has no attitribute 'GoogleMapPlotter'
upvote count: 2
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/46866513
has answer: http://stackoverflow.com/a/46866594
duplicate of: http://stackoverflow.com/q/14365542
has body: I have a text file and want to get its values and want to put them in a dataframe in python. I know I have to use read_csv but not sure how to do it. The text file looks something like this: duration,protocol_type,service,flag,src_bytes,dst_bytes,land,wrong_fragment,urgent,hot,num_failed_logins,logged_in,num_compromised,root_shell,su_attempted,num_root,num_file_creations,num_shells,num_access_files,num_outbound_cmds,is_host_login,is_guest_login,count,srv_count,serror_rate,srv_serror_rate,rerror_rate,srv_rerror_rate,same_srv_rate,diff_srv_rate,srv_diff_host_rate,dst_host_count,dst_host_srv_count,dst_host_same_srv_rate,dst_host_diff_srv_rate,dst_host_same_src_port_rate,dst_host_srv_diff_host_rate,dst_host_serror_rate,dst_host_srv_serror_rate,dst_host_rerror_rate,dst_host_srv_rerror_rate 0,icmp,ecr_i,SF,1032,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,511,511,0.0,0.0,0.0,0.0,1.0,0.0,0.0,255,255,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0 Where all the strings are what I want to use for rows and the rest of them are values. I am using pandas in anaconda and the text file is called kddcup.txt. If anyone can help me out it would be much appreciated. Thank you!
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/46866594
tagged with: pandas
has comment: http://stackoverflow.com/comment/80680481
has comment: http://stackoverflow.com/comment/80680493
answer count: 1
has comment: http://stackoverflow.com/comment/80680520
has title: How do I get values from a text file and put them into a dataframe in python?
has comment: http://stackoverflow.com/comment/80680515
tagged with: python
linked to: http://stackoverflow.com/q/14365542
type: AnsweredQuestion

http://stackoverflow.com/a/46751557
has comment: http://stackoverflow.com/comment/80450068
answers question: http://stackoverflow.com/q/46751465
has comment: http://stackoverflow.com/comment/80449465
has comment: http://stackoverflow.com/comment/80449020
has body: If you want to use some, you can try this way: df.astype(str).apply(lambda x: x.sum(),1) Output: 0 0414 1 1515 2 2616 3 3719 dtype: object
upvote count: 2
has comment: http://stackoverflow.com/comment/80449068
has comment: http://stackoverflow.com/comment/80448981
type: Answer
has comment: http://stackoverflow.com/comment/80449026
has comment: http://stackoverflow.com/comment/80449008
score: 2
has comment: http://stackoverflow.com/comment/80450043
downvote count: 0
has comment: http://stackoverflow.com/comment/80448994

http://stackoverflow.com/comment/80733347
type: Comment
comment on: http://stackoverflow.com/q/46892999
has text: have you tried printing out (logging) the requests before executing them ? Sound like one of the objects you're manipulating is an Error instead of a string (maybe you're accessing an empty structure or something)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/80637307
has text: Don't use a class as a module. Use a module.
comment on: http://stackoverflow.com/q/46844595
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/80491099
has text: Yes, the credential file is in place.
comment on: http://stackoverflow.com/q/46772012
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/80620369
type: QuestionComment
has text: read two lines?
comment on: http://stackoverflow.com/q/46836284
score: 0
type: Comment

http://stackoverflow.com/comment/80653655
has text: Could you update your code to include how you call the estimator?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46852018
score: 0

http://stackoverflow.com/comment/80617235
has text: Are you certain the column holds `datetime` values and not `str`ings that look like `datetime`s?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46834732
type: QuestionComment

http://stackoverflow.com/comment/80704583
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46878736
has text: check that in dev-C++ tools > compiler options > directories > c includes and c++ includes have the path to where your Python.h is.

http://stackoverflow.com/a/46876648
downvote count: 1
has comment: http://stackoverflow.com/comment/80700208
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/46876563
has body: This will probably do what you want it to do: def find_max_index(data, max_num=0, index_of_max=0, step=1): for item in data: if int(item) &gt; max_num: max_num = int(item) index_of_max += step return max_num, index_of_max - step Here's an example: items = [1, 2, 3, 4, 999, 6, 7, 8, 9] find_max_index(items) # (999, 4)
type: Answer

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/46839861
tags question: http://stackoverflow.com/q/46900437
type: Tag

http://stackoverflow.com/q/46758107
tagged with: pandas
tagged with: python
favorite count: 0
has body: I'd like to plot "MJD" vs "MULTIPLE_MJD" for the data given here:: https://www.dropbox.com/s/cicgc1eiwrz93tg/DR14Q_pruned_several3cols.csv?dl=0 import numpy as np import pandas as pd import matplotlib.pyplot as plt import ast filename = 'DR14Q_pruned_several3cols.csv' datafile= path+filename df = pd.read_csv(datafile) df.plot.scatter(x='MJD', y='N_SPEC') plt.show() ser = df['MJD_DUPLICATE'].apply(ast.literal_eval).str[1] df['MJD_DUPLICATE'] = pd.to_numeric(ser, errors='coerce') df['MJD_DUPLICATE_NEW'] = pd.to_numeric(ser, errors='coerce') df.plot.scatter(x='MJD', y='MJD_DUPLICATE') plt.show() This makes a plot, but only for one value of MJD_DUPLICATE:: print(df['MJD_DUPLICATE_NEW']) 0 55214 1 55209 ... Thoughts??
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/46777465
score: 1
has comment: http://stackoverflow.com/comment/80478531
type: Question
has title: Plotting a multiple column in Pandas (converting strings to floats)
linked to: http://stackoverflow.com/q/39790830
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/80478447
linked to: http://stackoverflow.com/q/23661583
linked to: http://stackoverflow.com/q/29550414
tagged with: series
tagged with: type-conversion
has comment: http://stackoverflow.com/comment/80470155
has comment: http://stackoverflow.com/comment/80470224

http://stackoverflow.com/a/46894977
has comment: http://stackoverflow.com/comment/80737711
upvote count: 1
has body: I would not do this with a regex. Split text into blocks by double line break Put line[0] at end of line [1] to line[n] of each block Code #!/usr/bin/env python """Adjust text according to example.""" def adjust_text(text): blocks = text.split("\n\n\n") for block_nr, block in enumerate(blocks): lines = block.split("\n") for line_nr, _ in enumerate(lines): if line_nr != 0: lines[line_nr] += " " + lines[0] blocks[block_nr] = "\n".join(lines) text = "\n\n\n".join(blocks) return text if __name__ == '__main__': text = """Customer-01 192.168.12.100 60000 10 18w3d 00:00:37 00:00:22 E 179/34634 9/1 192.168.12.120 64524 337 6d00h 00:00:07 00:00:06 E 179/29837 0/0 192.168.12.130 64522 0 1w3d 00:00:42 00:00:54 E 9835/179 0/0 192.168.12.140 64512 0 36w6d 00:00:14 00:00:22 E 33883/179 0/0 192.168.12.150 64512 4 11w3d 00:00:24 00:00:22 E 179/13712 4/0 Cust-02 192.168.13.100 64512 10 18w3d 00:00:37 00:00:22 E 179/34634 9/1 192.168.14.120 64524 337 6d00h 00:00:07 00:00:06 E 179/29837 0/0 192.168.15.130 64522 0 1w3d 00:00:42 00:00:54 E 9835/179 0/0 192.168.16.140 64512 0 36w6d 00:00:14 00:00:22 E 33883/179 0/0 192.168.17.150 64512 4 11w3d 00:00:24 00:00:22 E 179/13712 4/0""" text = adjust_text(text) print(text)
has comment: http://stackoverflow.com/comment/80737142
has comment: http://stackoverflow.com/comment/80737188
score: 1
has comment: http://stackoverflow.com/comment/80753117
has comment: http://stackoverflow.com/comment/80737959
has comment: http://stackoverflow.com/comment/80737227
downvote count: 0
has comment: http://stackoverflow.com/comment/80741621
type: Answer
answers question: http://stackoverflow.com/q/46894909
has comment: http://stackoverflow.com/comment/80741745

http://stackoverflow.com/a/46952333
answers question: http://stackoverflow.com/q/46876504
has body: What if you had more columns? for example df = pd.DataFrame({'A': [NaN, 15,20,25,NaN],'y_l': [NaN, 97,95,98,NaN],'y_h': [90, NaN,NaN,NaN,95]}, columns=['A','y_l','y_h']) &gt;&gt;&gt;df A y_l y_h 0 NaN NaN 90.0 1 15.0 97.0 NaN 2 20.0 95.0 NaN 3 25.0 98.0 NaN 4 NaN NaN 95.0 How could you keep the values in column A after filtering out the irrelevant rows as below? A y_l y_h 0 NaN NaN 90.0 1 20.0 95.0 NaN 2 NaN NaN 95.0
type: Answer
downvote count: 0
score: 2
upvote count: 2

http://stackoverflow.com/comment/80587527
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46819546
has text: Sounds like you're not going through all detections.

http://stackoverflow.com/comment/91186104
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46780520
has text: I was able to get it to work. I was referring to the S3 directory. Once referred to a py file in the s3 directory or even a zip file that included a python script in the s3 directory, it worked.

http://stackoverflow.com/a/46815731
type: Answer
has comment: http://stackoverflow.com/comment/80862726
score: 1
upvote count: 1
has body: An older version of SIP was present on the machine and was being imported instead of the new one, built from source, used to build PyQt. Removing the old version of SIP fixes the issue. Before $ python &gt;&gt;&gt; import sip &gt;&gt;&gt; print sip.SIP_VERSION_STR 4.17 After removing the old version with sudo apt remove python-sip $ python &gt;&gt;&gt; import sip &gt;&gt;&gt; print sip.SIP_VERSION_STR 4.19.3 &gt;&gt;&gt; from PyQt5 import Qt # Does not segfault
answers question: http://stackoverflow.com/q/46795315
has comment: http://stackoverflow.com/comment/80858545
accepted answer of: http://stackoverflow.com/q/46795315
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/80575030
has text: By the way, `range(1,maxsize)` will only get you `maxsize - 1` rolls. Simply use `range(maxsize)` instead.
score: 0
comment on: http://stackoverflow.com/q/46813252
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80648139
type: AnswerComment
score: 0
type: Comment
has text: thanks, it works. now I can see how filters are working.
comment on: http://stackoverflow.com/a/46828989

http://stackoverflow.com/q/46893247
has comment: http://stackoverflow.com/comment/80733892
tagged with: laravel
score: 2
upvote count: 2
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/80735356
has body: Im trying to run my python script that uses tensorflow library (not sure if it's relevant) in Laravel. My problem is returning any messages back to PHP after doing basically anything with TF library. Ihave tried following execute methods $command = 'python C:/wamp64/www/hi.py'; $execMethod = exec($command); $systemMethod = system($command); $shellMethod = shell_exec($command); My python script: #!c:/Program Files/Python36/python.exe import os import urllib.request import tensorflow as tf import numpy as np import time IRIS_TRAINING = "iris_training.csv" IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv" IRIS_TEST = "iris_test.csv" IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv" def main(): # If the training and test sets aren't stored locally, download them. if not os.path.exists(IRIS_TRAINING): raw = urllib.request.urlopen(IRIS_TRAINING_URL).read() with open(IRIS_TRAINING, "wb") as f: f.write(raw) if not os.path.exists(IRIS_TEST): raw = urllib.request.urlopen(IRIS_TEST_URL).read() with open(IRIS_TEST, "wb") as f: f.write(raw) # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv_with_header(filename=IRIS_TRAINING, target_dtype=np.int, features_dtype=np.float32) test_set = tf.contrib.learn.datasets.base.load_csv_with_header(filename=IRIS_TEST, target_dtype=np.int, features_dtype=np.float32) # Specify that all features have real-value data feature_columns = [tf.feature_column.numeric_column("x", shape=[4])] # Build 3 layer DNN with 10, 20, 10 units respectively. classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=3, model_dir="c:/wamp64/www/Laravel/resources/pythonscripts/tmp/iris_model") # Define the training inputs train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(training_set.data)}, y=np.array(training_set.target), num_epochs=None, shuffle=True) # Train model. classifier.train(input_fn=train_input_fn, steps=1000) # Define th…
has answer: http://stackoverflow.com/a/46895835
downvote count: 0
answer count: 1
favorite count: 0
has title: Running tensorflow python script in PHP Laravel
type: UnansweredQuestion
tagged with: python
tagged with: php

http://stackoverflow.com/comment/80453353
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/46753845
has text: Please post your code and traceback as text - not as images...
type: Comment

http://stackoverflow.com/q/46817290
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/46835217
has answer: http://stackoverflow.com/a/46817552
type: Question
has title: How do I paste the copied text from keyboard in python
tagged with: pyperclip
score: 5
upvote count: 6
has answer: http://stackoverflow.com/a/46817405
answer count: 3
downvote count: 1
tagged with: tkinter-entry
favorite count: 0
tagged with: python-3.x
has body: If I execute this code, it works fine. But if I copy something using the keyboard (Ctrl+C), then how can I paste the text present on clipboard in any entry box or text box in python? import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste()
tagged with: tkinter

http://stackoverflow.com/comment/80731452
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46892131
type: AnswerComment
has text: this doesn't add columns for total fixed and total float rate maturing this year. It gives the sum both for the given year. I want to convert the groupby ['Year', 'LoanType'] into loan type being columns

http://stackoverflow.com/comment/80574124
score: 0
comment on: http://stackoverflow.com/q/46796663
type: Comment
has text: Okay, hopefully I'll have something for you in a few minutes. Interesting issue to optimise actually.
type: QuestionComment

http://stackoverflow.com/comment/80688788
has text: @Bharathshetty sorry for being unclear. Im not saying duplicate indexes, just how to keep the first. I'll try to add that "traditional method" later (which is in fact just the usual rolling method).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46870557

http://stackoverflow.com/comment/132218091
comment on: http://stackoverflow.com/a/49772856
score: 0
type: AnswerComment
type: Comment
has text: Downvoted as the example doesn't result in video with audio. Also it ignores video frame rate. If I understand OP correctly, the input should be a list of jpeg files plus frame rate or video without sound (it already has a frame rate) and the result should be a file with audio, that can be played by a video player app such QuickTime or VLC or in browser.

http://stackoverflow.com/comment/80738261
score: 0
comment on: http://stackoverflow.com/q/46895463
type: Comment
type: QuestionComment
has text: the expression is only true for dtype('float64'), its changed to "Double". If its not true its changed to "Long". Maybe I dont know how this expression works.

http://stackoverflow.com/a/46766621
has body: Maybe the simplest solution is to use string slicing: test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear LoreLoreLore,Greetings from Amsterdam!We have received your wonderful comments and wanted to thank you for sharing your positive experience with us. We are so thankful that you have selected the Andaz Amsterdam for your special all-girls weekend getaway. Please come and see us again in the near future and let our team pamper you and your girlfriends!!Thanks again!Anna MaryAndaz Amsterdam -Guest RelationsReport response as inappropriateThank you. We appreciate your input.This response is the subjective opinion of the management representative' pos = test.find('ago') + 3 print(test[:pos], test[pos:])
score: 8
downvote count: 0
upvote count: 8
answers question: http://stackoverflow.com/q/46766530
type: Answer

http://stackoverflow.com/comment/80665858
comment on: http://stackoverflow.com/q/46859001
type: QuestionComment
has text: Maybe that might work? I still can't imagine how I'd pass z3 a python array and convert it into a bunch of "or"s like that. And how would you be communicating it can re-use a value as many times as it likes, or not at all?
score: 0
type: Comment

http://stackoverflow.com/q/46752575
has title: gRPC/proto Google cloud client libraries vs GAPIC Google cloud client libraries
type: Question
downvote count: 0
tagged with: google-cloud-platform
answer count: 1
has answer: http://stackoverflow.com/a/46774453
favorite count: 0
upvote count: 2
tagged with: google-api
tagged with: python
score: 2
type: AnsweredQuestion
has body: I've mostly found working with google's client libraries easy to work with, intuitive, and well suited to idiomatic python, with the notable exception of auth (there is a special place in hell for whoever came up with the oAuth dance) Although in the past, most of my work was on Gsuite, I'm tinkering with the google cloud client libraries, Looking for a specific library i realised they come in two flavors now: gRPC and GAPIC. although both come with a side of pickles, I could not find any reference about which flavor would be preferable to the other, (if any). Gapic Flavor (ame) hector@trantor ~/a/envs ❯❯❯ pip search gapic gapic-google-iam-admin-v1 (0.10.0) - GAPIC library for the Google IAM Admin API gapic-google-cloud-spanner-admin-instance-v1 (0.15.3) - GAPIC library for the Cloud Spanner Instance Admin API gapic-google-cloud-spanner-admin-database-v1 (0.15.3) - GAPIC library for the Cloud Spanner Database Admin API gapic-google-cloud-speech-v1 (0.15.3) - GAPIC library for the Google Cloud Speech API gapic-google-cloud-language-v1beta2 (0.15.3) - GAPIC library for the Google Cloud Natural Language API google-cloud-trace (0.15.5) - GAPIC library for the Stackdriver Trace API gapic-google-cloud-functions-v1beta2 (0.15.3) - GAPIC library for the Google Cloud Functions API gapic-google-cloud-spanner-v1 (0.15.3) - GAPIC library for the Cloud Spanner API gapic-google-cloud-language-v1 (0.15.3) - GAPIC library for the Google Cloud Natural Language API gapic-google-cloud-monitoring-v3 (0.15.3) - GAPIC library for the Stackdriver Monitoring API gapic-google-cloud-error-reporting-v1beta1 (0.15.3) - GAPIC library for the Stackdriver Error Reporting API gapic-google-cloud-pubsub-v1 (0.15.4) - GAPIC library for the Google Cloud Pub/Sub API gapic-google-cloud-language-v1beta1 (0.11.1) - GAPIC library for the Google Language API gapic-google-cloud-logging-v2 (0.91.3) - GAPIC library for the Stackdriver Logging API gapic-google-cloud-datastore-v1 (0.90.4) - GAPIC library for the…
tagged with: grpc
accepted answer: http://stackoverflow.com/a/46774453

http://stackoverflow.com/a/46759813
score: 2
upvote count: 2
has body: You are stuck in an infinite loop. Moreover, you cannot compare to the string "True", but rather to True only: if X.isdigit() == True: Instead of: if X.isdigit() == "True": You can also skip the comparison to True altogether if X.isdigit():
downvote count: 0
answers question: http://stackoverflow.com/q/46759780
type: Answer

http://stackoverflow.com/q/46863047
has title: Detecting corners using Opencv Python
tagged with: python
has answer: http://stackoverflow.com/a/46863737
favorite count: 0
has comment: http://stackoverflow.com/comment/80674755
has body: I am trying to find the corners of the 4 pillars which are of yellow in colour and also detecting extreme corners of the board which is of white in colour. Basically i want to calculate the area of whole space after subtracting the area of each pillar. For that first am trying to identifying the corner of pillars to find the area of each pillar. Here is the code which I tried, I am almost half way through it. import numpy as np import cv2 img = cv2.imread('Corner_0.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10) corners = np.int0(corners) for corner in corners: x,y = corner.ravel() cv2.circle(img,(x,y),3,255,-1) cv2.imwrite('Detected_Corner_0.jpg',img) I would like to detect corner and calculating the area of the pillar. When I use Grabcut I am able to apply for one pillar, does this make sense?
upvote count: 1
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46863737
has comment: http://stackoverflow.com/comment/80674810
type: Question
has comment: http://stackoverflow.com/comment/80674845
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80674824
score: 1

http://stackoverflow.com/comment/80481001
score: 0
comment on: http://stackoverflow.com/q/46762597
type: Comment
type: QuestionComment
has text: I'm not really sure what that answer means.

http://stackoverflow.com/a/46751356
type: Answer
downvote count: 0
score: 5
has body: You can use ''.join after converting the columns' data type to str: df[ls].astype(str).apply(''.join, axis=1) #0 02214 #1 12315 #2 22416 #3 32519 #dtype: object
answers question: http://stackoverflow.com/q/46751326
upvote count: 5

http://stackoverflow.com/q/46760027
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/51846669
has comment: http://stackoverflow.com/comment/80465491
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/46767158
score: 3
downvote count: 0
has body: I want to let users choose from languages they speak. Is there a Django built-in list of languages or should I get list of languages from another source? For now: class UserProfile(models.Model): languages = models.ManyToManyField(Language) class Language(models.Model): shortcut ... name ... The languages field should only be able to list all languages user can speak.
has title: Django - field of language choices
type: Question

http://stackoverflow.com/q/46801701
has answer: http://stackoverflow.com/a/46815050
tagged with: opengl
type: Question
downvote count: 0
answer count: 1
has body: I am trying to figure out the coordinates of the vertices of two rectangles in a pygame window that is using OpenGL to create the 3D objects. import pygame from pygame.locals import * import random from OpenGL.GL import * from OpenGL.GLU import * rect1 = [(-5.125,0,-40),(-3.125,0,-40),(-3.125,5,-40),(-5.125,5,-40),] rect2 = [(3.125,0,-40),(5.125,0,-40),(5.125,5,-40),(3.125,5,-40)] edges = ((0,1),(1,2),(2,3),(3,0)) #This draws the rectangles edges def Target(): glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(rect1[vertex]) glEnd() glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(rect2[vertex]) glEnd() def main(): try: pygame.init() display = (320,240) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) gluPerspective(45, (display[0]/display[1]), .1, 1000) while True: #iterates through events to check for quits for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() Target() pygame.display.flip() pygame.time.wait(100) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) except Exception as e: print (e) main() How do I grab the coordinates on the pygame window(320,240) of the object?
linked to: http://stackoverflow.com/q/11277501
tagged with: coordinate-transformation
tagged with: pygame
linked to: http://stackoverflow.com/q/46749675
favorite count: 0
tagged with: perspectivecamera
upvote count: 2
type: UnansweredQuestion
has title: How to find PyGame Window Coordinates of an OpenGL Vertice?
tagged with: python
linked to: http://stackoverflow.com/q/45893277
score: 2

http://stackoverflow.com/a/46902235
type: Answer
has body: &gt;&gt;&gt; number = "456367" &gt;&gt;&gt; [char for char in number] ['4', '5', '6', '3', '6', '7']
answers question: http://stackoverflow.com/q/46902206
score: 0

http://stackoverflow.com/comment/80501109
type: Comment
has text: I like this answer because it mentions a function which is frequently missed in the docs.
comment on: http://stackoverflow.com/a/46777638
type: AnswerComment
score: 0

http://stackoverflow.com/comment/80449856
score: 0
has text: Is your system the same version as the blender Python interpreter? ( https://docs.blender.org/manual/en/dev/troubleshooting/python.html )
comment on: http://stackoverflow.com/q/46751535
type: Comment
type: QuestionComment

http://stackoverflow.com/a/46804053
has comment: http://stackoverflow.com/comment/80554979
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80554940
has comment: http://stackoverflow.com/comment/80555261
has comment: http://stackoverflow.com/comment/80555029
type: Answer
score: 1
has body: nums = [3.60, 12.750] for num in nums: s = "%.5f" % num # 5 because it's 7-2 s = s[:7] # Accounts for the '.' print(s) Output: 3.60000 12.7500 # Each has length 7.
answers question: http://stackoverflow.com/q/46804040
has comment: http://stackoverflow.com/comment/80555210
has comment: http://stackoverflow.com/comment/80554989

http://stackoverflow.com/a/46779687
score: 0
type: Answer
has body: When you do: results[i] = ... you are not adding values to the DictProxy at results[i], you are replacing it with another brand new dict, inside the outer results dict. Therefore, the only one you need to be synchronized is that outer dict. Replace line 15 with results = multiprocessing.Manager().dict(), and remove the loop line 18-20 that never did anything.
answers question: http://stackoverflow.com/q/46768813

http://stackoverflow.com/comment/80500539
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46777397
has text: https://stackoverflow.com/questions/10865483/print-results-in-mysql-format-with-python I'd look at the second answer here.

http://stackoverflow.com/q/46860358
has title: Wildcards in a string and splitting the string up after them in Python
type: Question
has body: I have a string that takes on the following format: TEST 1 EXAMPLE 1 BLAHBLAH The number 1 can be replaced by any number and "BLAHBLAH" by any string, e.g: TEST 2 EXAMPLE 99 HELLOWORLD What I'd like to do is first, check if the string (which I'm receiving as 'data') starts with TEST * EXAMPLE * and then, split it apart so I have a new string of only whatever follows. Here's what I've tried: import fnmatch filtered = fnmatch.filter(data, 'TEST ? EXAMPLE ?') if filtered != "": str = filtered.split("EXAMPLE ",1)[1]
answer count: 2
accepted answer: http://stackoverflow.com/a/46860482
possible better answer: http://stackoverflow.com/a/46860474
tagged with: string
has answer: http://stackoverflow.com/a/46860474
has comment: http://stackoverflow.com/comment/80668505
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80668462
has answer: http://stackoverflow.com/a/46860482
score: 0

http://stackoverflow.com/q/46759620
has comment: http://stackoverflow.com/comment/80465352
accepted answer: http://stackoverflow.com/a/46760234
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/46759857
has comment: http://stackoverflow.com/comment/80465124
has answer: http://stackoverflow.com/a/46760234
has comment: http://stackoverflow.com/comment/80465269
favorite count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/80464918
possible better answer: http://stackoverflow.com/a/46759857
has body: I have a dictionary with keyed tuples. I would like to multiply the 2 tuples and sum for every dictionary key. I've created two classes. The first (ExampleBase) simply creates a variable and a dictionary. The second (Useful) passes the dictionary and does the calculation. I believe I am calling the method from the second class (Useful) incorrectly as the error I'm currently getting is: 'ExampleBase' objest has no attribute 'compute_value' The code should do this: dictionary = { "key1": (v1, v2), "key2": (v1, v2), "key3": (v1, v2) } total = key1v1*key1v2 + key2v1*key2v2 + key3v1*key3v2 class ExampleBase: def __init__(self, company_name="N/A", stock_dict={}): """ class constructor """ self.company_name = company_name self.stock_dict = stock_dict print(self.stock_dict) return class Useful(ExampleBase): """ Inherits from ExampleBase class """ def __init__(self, company_name, stock_dict): super().__init__(name) return def compute_value(self, stock_dict): """ Computes value of stk """ sum(v1*v2 for v1,v2 in stock_dict.values()) return ## ## Program starts running from here ## if __name__ == "__main__": a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)} b = ExampleBase("Bern", a) b.compute_value(a)
downvote count: 1
has title: Python: Summing product of tuples inside a dictionary
type: Question

http://stackoverflow.com/comment/80698223
has text: Thank you! I succesfully installed it :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46873334

http://stackoverflow.com/q/46903676
downvote count: 5
has answer: http://stackoverflow.com/a/46903739
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/2960772
has comment: http://stackoverflow.com/comment/80754079
upvote count: 0
possible better answer: http://stackoverflow.com/a/46903739
has comment: http://stackoverflow.com/comment/80754047
has answer: http://stackoverflow.com/a/46903839
tagged with: boolean
has comment: http://stackoverflow.com/comment/80753988
tagged with: concatenation
has comment: http://stackoverflow.com/comment/80754449
has comment: http://stackoverflow.com/comment/80754524
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/80754160
accepted answer: http://stackoverflow.com/a/46903839
duplicate of: http://stackoverflow.com/q/2960772
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80754022
has body: As a part of program I wrote the following method (hidden is a boolean variable). It's located in an object called Deltext, which inherits a type called DelMsg. info_msg() is overriding and using a similar method in its parent type. def info_msg(self): info = DelMsg.info_msg(self) if self.code == 'l': # If message is long message return info + '#' + str(len(self.content)) + '#' + str(self.hidden) elif self.code == 'm': # If message is snap message return info + '#' + str(self.timeout) + '#' + self.content else: # If message is a normal message return info + '#' + self.content + '#' + str(self.hidden) But every time I call the method (from the object instance) it displays an error: TypeError: cannot concatenate 'str' and 'bool' objects, and says the error is in the last line, even though hidden is parsed to string. Is there any way to solve this without using conditionals?
score: -5
has title: Python concatenating boolean to string doesn't work

http://stackoverflow.com/a/46762302
downvote count: 0
answers question: http://stackoverflow.com/q/46762265
type: Answer
has body: Try this (parens instead of square brackets for index): impact = trades.index(trades.zero == total_columns).astype(str).tolist() trades_impact = transactions.join(impact)
score: 1
has comment: http://stackoverflow.com/comment/80469967
has comment: http://stackoverflow.com/comment/80496339
upvote count: 1

http://stackoverflow.com/q/46751249
score: 0
favorite count: 0
answer count: 5
has title: Find maximum in list of objects in Python
upvote count: 1
tagged with: python
tagged with: object
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/80448394
has answer: http://stackoverflow.com/a/46751275
downvote count: 1
has answer: http://stackoverflow.com/a/46751277
has answer: http://stackoverflow.com/a/46751869
type: Question
has answer: http://stackoverflow.com/a/46751436
has answer: http://stackoverflow.com/a/46751496
has body: I have a list of objects. Could someone help return the object with the highest score? For example: objs = [ { "name": "John", "score": 30 }, { "name": "Josh", "score": 40 }, { "name": "Jason", "score": 50 }, ] I need a method that will return the object with the highest score. In this case it should return { "name": "Jason", "score": 50 } So far I tried: print max(objs, key=attrgetter('score')) but it gives me AttributeError: 'dict' object has no attribute 'score' Thanks in advance!
possible better answer: http://stackoverflow.com/a/46751277
accepted answer: http://stackoverflow.com/a/46751869
has comment: http://stackoverflow.com/comment/80448376
has comment: http://stackoverflow.com/comment/80448356

http://stackoverflow.com/comment/80734793
type: Comment
has text: @davideps. You can think of the roles as the standardised keys of a mapping. This allows the view to request data from the model without knowing anything about its implementation (and *vice versa*). So the roles are part of the model/view interface specification - they are contractual guarantees that allow the components to negotiate with each other whilst remaining completely independent.
comment on: http://stackoverflow.com/a/46874833
type: AnswerComment
score: 0

http://stackoverflow.com/a/46863477
downvote count: 2
answers question: http://stackoverflow.com/q/46863394
has comment: http://stackoverflow.com/comment/80674445
score: -1
has comment: http://stackoverflow.com/comment/80674524
upvote count: 1
has body: The issue is the line op=input('enter the operation:\t'). If you enter nothing, it still returns '', an empty string, so for the z argument, you pass in ''. The interpreter runs through all of your if and elif statements, and none of them are satisfied, so it just returns r. However, r has not been assigned any value, so an exception is raised. Instead, you should write something like this def clc(x,y,z): if z=='a' or z=='': r=x+y elif z=='s': r=x-y elif z=='m': r=x*y elif z=='d': r=x/y elif z=='mod': r=x%y elif z=='ex': r=x**y else: return 'N/A' return r while True: a=int(input('Enter a number:\t ')) b=int(input('Enter a number:\t ')) op=input('enter the operation:\t') answer=clc(a,b,op) print('the answer is',answer) query=input('If you want to continue, please press Enter\t') if len(query)&gt;0: break
type: Answer
has comment: http://stackoverflow.com/comment/80674423
has comment: http://stackoverflow.com/comment/80674471

http://stackoverflow.com/comment/80448967
type: Comment
type: QuestionComment
has text: No, never post multi-line Python code in comments because the indentation gets lost. But anyway, your code belongs in the body of the question itself, comments are just to help you clarify & improve your question.
comment on: http://stackoverflow.com/q/46751441
score: 0

http://stackoverflow.com/comment/80645942
comment on: http://stackoverflow.com/q/46848343
score: 0
type: Comment
type: QuestionComment
has text: Thanks @Jacob. But my problem is not how to resolve the error I got. It is how to store the output of pattern.en package into a variable or Dataframe. So please let me know if you have any idea on that. Hope this is not a basic one and you can rethink to remove the downvote if you think this not the basic one

http://stackoverflow.com/a/46801166
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/80550631
has comment: http://stackoverflow.com/comment/80549718
has body: You have set bids and asks to be the same dictionary: bids = asks = {} You want them to be different dictionaries bids, asks = {}, {}
accepted answer of: http://stackoverflow.com/q/46801139
answers question: http://stackoverflow.com/q/46801139
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/46838233
type: UnansweredQuestion
has title: Pass value to Django model attribute
tagged with: django
tagged with: python
tagged with: django-views
has body: I am building a file upload page where files will be saved with a different prefix in their name (get_file_path function uses instance.mname) but will go through the same upload model/form. I want the prefix to be declared in the views in form in mname='prefix'. How can I pass this value from views to form? Thank you! models.py class Upload(models.Model): mname = # need it to be passed document = models.FileField(upload_to=get_file_path, validators=[validate_file_extension]) upload_date=models.DateTimeField(auto_now_add =True) forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('document',) views.py def uploadFile(request): if request.method == "POST": file = UploadForm(request.POST, request.FILES, mname='....') if file.is_valid(): file.save()
tagged with: django-forms
type: Question
tagged with: django-models
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/46838405

http://stackoverflow.com/a/46903593
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/46891634
type: Answer
has body: I read the blog suggested by Will Croxford, and here's the solution to my problem: app/blueprint/views.py from app import main from app.blueprint import blueprint
score: 1

http://stackoverflow.com/a/46818089
type: Answer
has body: Simple, like this: from sampleA import classA You can now call functionA like this: classA.functionA() Using your code: sampleA.py class classA(): def functionA(): print("Jello World!") sampleB.py from sampleA import classA class classB(): def __init__(self): classA.functionA() I added an __init__ function to classB so functionA gets executed immediately. Important caveat: sampleA.py and sampleB.py must be in the same directory.
has comment: http://stackoverflow.com/comment/80585685
answers question: http://stackoverflow.com/q/46817900
accepted answer of: http://stackoverflow.com/q/46817900
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/46763595
type: Answer
has body: import itertools s= "abcsaabcpaosdjaf" result = max( ( list(next(sub)) + [b for a, b in sub] for ascending, sub in itertools.groupby(zip(s,s[1:]), lambda x: x[0] &lt;= x[1]) if ascending ), key=len ) print (''.join(result)) Credits to this
answers question: http://stackoverflow.com/q/46751527
score: 0

http://stackoverflow.com/comment/80624944
type: QuestionComment
has text: `var = None`, so `while var == 1` is **always going to be false**. Ergo, the `else` block of the `while` is always going to be executed when a number is divisible by 3.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/46838603

http://stackoverflow.com/q/46805634
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/46805739
tagged with: facebook-graph-api
has comment: http://stackoverflow.com/comment/80558363
has body: Below is the code: token=.. graph=facebook.GraphAPI(token) data = graph.request('/search?q=baby&amp;type=user') Actually I just run the code successfully few hours before, now it says" facebook.GraphAPIError: Error validating access token: Session has expired on Tuesday, 17-Oct-17 21:00:00 PDT. The current time is Wednesday, 18-Oct-17 01:06:39 PDT Anyone occur this error?
type: Question
has comment: http://stackoverflow.com/comment/80558361
type: AnsweredQuestion
has title: facebook api access token: session has expired
has comment: http://stackoverflow.com/comment/80558344
answer count: 1
has comment: http://stackoverflow.com/comment/80558482
accepted answer: http://stackoverflow.com/a/46805739

http://stackoverflow.com/q/46773577
tagged with: python
has comment: http://stackoverflow.com/comment/80493382
answer count: 3
has comment: http://stackoverflow.com/comment/80493207
linked to: http://stackoverflow.com/q/53809310
downvote count: 1
has answer: http://stackoverflow.com/a/46779361
has answer: http://stackoverflow.com/a/75033450
has title: Threading with Python Curses giving me weird characters?
type: UnansweredQuestion
has body: Hey there Stack Overflow. I'm trying to build a testing script that should mix outputting changing characters (using curses) on multiple lines (creating them over time), creating new lines based on the thread number. I have the below code: # -*- coding: utf-8 -*- import curses, time, threading def threadedFunction(linePos): stdscr = curses.initscr() curses.noecho() curses.cbreak() try: stdscr.clear() for i in range(50): stdscr.addstr(linePos, 0, "testing %s..." % i) stdscr.refresh() time.sleep(.1) finally: curses.echo() curses.nocbreak() curses.endwin() pass pass if __name__ == "__main__": for x in xrange(0, 4): # should produce 5 lines maximum exec("process" + str(x) + " = threading.Thread(target = threadedFunction, args = (" + str(x) + ",))") exec("process" + str(x) + ".start()") I tried using the multithreading library before, but I had no hope with it. The threading library at least will display the numbers I want on a few lines before it goes crazy. Here's an example of what it does when I run it: All I want is for the program to just simply start a new thread, and display a line that counts to 50 while adding new lines doing the same thing. How would I go about doing this?? Thanks in advance :)
has comment: http://stackoverflow.com/comment/95803484
has answer: http://stackoverflow.com/a/54499180
linked to: http://stackoverflow.com/q/55308818
linked to: http://stackoverflow.com/q/8569878
tagged with: curses
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80506192
type: Question
upvote count: 2
tagged with: multithreading

http://stackoverflow.com/comment/80545938
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46799496
has text: `.apply` is *not* faster than a for-loop, generally. Indeed, it *is a Python for loop, under the hood*.

http://stackoverflow.com/a/54711862
upvote count: 5
downvote count: 0
has body: You have to reset the auth_permission_id_seq as it is most likely lower than the maximum id SELECT MAX(id)+1 FROM auth_permission ALTER SEQUENCE auth_permission_id_seq RESTART WITH &lt;result of previous cmd&gt;; Where 100 is the MAX(id)+1. There is probably a way to do this in one command but my SQL knowledge is limited. The following will show you the current value of the sequence number and not the one you have to set it to (as it can be way off the MAX(id) in auth_permission) SELECT last_value FROM auth_permission_id_seq; I personally had the same issue when I restored the dump (data only) of the production database to the development one.
score: 5
type: Answer
answers question: http://stackoverflow.com/q/46785841

http://stackoverflow.com/a/46817077
downvote count: 0
type: Answer
upvote count: 7
answers question: http://stackoverflow.com/q/46816226
has body: Here's a vectorized one with NumPy's advanced-indexing to select one element per column, given the row indices ind per col - pd.Series(df.values[ind, np.arange(len(ind))], df.columns) Sample run - In [107]: ind = [0, 2, 1] # different one than sample for variety ...: cols = ['A','B','C'] ...: df = pd.DataFrame(np.arange(9).reshape((3,3)),columns=cols) ...: In [109]: df Out[109]: A B C 0 0 1 2 1 3 4 5 2 6 7 8 In [110]: pd.Series(df.values[ind, np.arange(len(ind))], df.columns) Out[110]: A 0 B 7 C 5 dtype: int64 Runtime test Let's compare the propose one against the pandas built-in vectorized lookup method proposed in @MaxU's solution and since we are seeing how good the vectorized ones are, let's have greater number of cols - In [111]: ncols = 10000 ...: df = pd.DataFrame(np.random.randint(0,9,(100,ncols))) ...: ind = np.random.randint(0,100,(ncols)).tolist() ...: # @MaxU's solution In [112]: %timeit pd.Series(df.lookup(ind, df.columns), index=df.columns) 1000 loops, best of 3: 718 µs per loop # Proposed in this post In [113]: %timeit pd.Series(df.values[ind, np.arange(len(ind))], df.columns) 1000 loops, best of 3: 410 µs per loop In [114]: ncols = 100000 ...: df = pd.DataFrame(np.random.randint(0,9,(100,ncols))) ...: ind = np.random.randint(0,100,(ncols)).tolist() ...: # @MaxU's solution In [115]: %timeit pd.Series(df.lookup(ind, df.columns), index=df.columns) 100 loops, best of 3: 8.83 ms per loop # Proposed in this post In [116]: %timeit pd.Series(df.values[ind, np.arange(len(ind))], df.columns) 100 loops, best of 3: 5.76 ms per loop
score: 7

http://stackoverflow.com/q/46791411
tagged with: python
has body: My goal is to parse data from a website and store those data on a text file, formatted to be opened in Excel. Here is the code: from bs4 import BeautifulSoup import requests import pprint import re import pyperclip import json import pandas as pd import csv pag = range (2, 126) out_file = open('bestumbrellasoffi.txt', 'w', encoding='utf-8') with open('bestumbrellasoffi.txt', 'w', encoding='utf-8') as file: for x in pag: # Iterate pages url = 'https://www.paginegialle.it/ricerca/lidi%20balneari/italia/p-' + str(x) + '?mr=50' response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") # Parse data for i, j, k, p, z in zip(soup.find_all('span', attrs= {'itemprop': 'name'}), soup.find_all('span', attrs= {'itemprop': 'longitude'}), soup.find_all('span', attrs= {'itemprop': 'latitude'}), soup.find_all('span', attrs = {'class': 'street- address'}), soup.find_all('div', attrs = {'class': 'tel elementPhone'})): info = i.text, j.text, k.text, p.text, z.text # Check if data is good print(url) print (info) # Create dataframe raw_data = { 'nome': [i], 'longitudine': [j], 'latitudine': [k], 'indirizzo': [p], 'telefono': [z]} print(raw_data) df = pd.DataFrame(raw_data, columns = ['nome', 'longitudine', 'latitudine', 'indirizzo', 'telefono']) df.to_csv('bestumbrellasoffi.txt') out_file.close() There are all those modules because I made many tries. So the output of print(info) [is][1] The output of print(raw_data) is This is the code reviewed and perfectly functioning. from bs4 import BeautifulSoup import requests import pprint import re import pyperclip import json import pandas as pd import csv pag = range (2, 126) with open('bestumbrellasoffia.txt', 'a', encoding='utf-8') as file: for x in pag: # Iterate pages url = 'https://www.paginegialle.it/ricerca/lidi%20balneari/italia/p-' + str(x) + '?mr=50' response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") raw_data = { 'nome': [], 'longitudine': [], 'latitudine': [], 'indirizzo': [],…
downvote count: 0
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/46791607
has comment: http://stackoverflow.com/comment/80531659
type: Question
tagged with: export-to-csv
answer count: 1
has comment: http://stackoverflow.com/comment/80545434
tagged with: pandas
upvote count: 1
has title: Parsing data with BeautifulSoup and sorting data with pandas DataFrame to_csv
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/comment/80696283
type: Comment
comment on: http://stackoverflow.com/q/46874594
type: QuestionComment
score: 0
has text: And there is a problem with the example output. Does "12.28" mean "12:28" (which is 12 + 28/60) or does it mean decimal fraction 12 + 28/100?

http://stackoverflow.com/comment/80622080
has text: " If you add a value that already exists an exception is raised." how that would ever happen?
comment on: http://stackoverflow.com/q/46830730
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80750213
comment on: http://stackoverflow.com/q/46901401
score: 0
type: Comment
type: QuestionComment
has text: `for i, (first,second) in enumerate(zip(c, c[1:])):`

http://stackoverflow.com/comment/80588225
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/46820315
has text: The same. Use Django Debug Toolbar, Luke!

http://stackoverflow.com/a/51827378
score: 2
has comment: http://stackoverflow.com/comment/123022806
has comment: http://stackoverflow.com/comment/123023870
downvote count: 0
answers question: http://stackoverflow.com/q/46806918
upvote count: 2
has body: The defintion for the RoundTripConstructor.construct_mapping is:: def construct_mapping(self, node, maptyp=None, deep=False) and it needs to know what kind of mapping it is expected to construct. There is some expectation in the RoundTripDumper on what can be attached to such an object, so you best of emulating what the routines in the RoundTripDumper pass: CommentedMap (a normal dict is not going to work). So you will need to do something like: from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap yaml = YAML() class Hero: yaml_tag = '!Hero' def __init__(self, name, age): self.name = name self.age = age @classmethod def to_yaml(cls, representer, data): return representer.represent_mapping(cls.yaml_tag, {'name': data.name, 'age': data.age}) @classmethod def from_yaml(cls, constructor, node): data = CommentedMap() constructor.construct_mapping(node, data, deep=True) return cls(**data) def __str__(self): return "Hero(name -&gt; {}, age -&gt; {})".format(self.name, self.age) yaml.register_class(Hero) ante_hero = Hero('Saber', 15) with open('config.yml', 'w') as fout: yaml.dump(ante_hero, fout) with open('config.yml') as fin: post_hero = yaml.load(fin) print(post_hero) which gives: Hero(name -&gt; Saber, age -&gt; 15) The above works because your class is relatively simple, if it could have recursive parts, you would need to follow a two-step creation process, with initial yield of the object created, so that it can be used during the recursion. That the maptyp defaults to None is historical, it must be set. E.g. one of the first things that construct_mapping does is trying to attach comments (if any were available on the node). I'll remove the default value in 0.15.55, which gives a more sensible error if you leave it out, like you did.
type: Answer

http://stackoverflow.com/a/49074907
answers question: http://stackoverflow.com/q/46869155
type: Answer
has body: This worked for me. Changed the xrange to range, isinstance isn't really necessary but 2to3 suggested it. Removed byte strings. def hexdump(src, length=16): result = [] digits = 4 if isinstance(src, str) else 2 for i in range(0, len(src), length): s = src[i:i+length] hexa = " ".join(map("{0:0&gt;2X}".format,src)) text = "".join([chr(x) if 0x20 &lt;= x &lt; 0x7F else "." for x in s]) result.append("%04X %-*s %s" % (i, length*(digits + 1), hexa, text) ) return "\n".join(result)
score: 0

http://stackoverflow.com/a/46903839
score: 2
upvote count: 3
downvote count: 1
accepted answer of: http://stackoverflow.com/q/46903676
has body: Here's how you can proceed to debug your code: check the type of the variables: Edit you code to include the following print(type(variable)) def info_msg(self): print(type(info)) print(type(self.content)) return info + '#' + self.content + '#' + str(self.hidden) Then, run the program and see which other variable is boolean. add str(...) to the boolean variables At most, all variables will be of type boolean, so you can edit your code as follows: def info_msg(self): return str(info) + '#' + str(self.content) + '#' + str(self.hidden) An other option is to use str.format, which will take care of casting the variables to string for you: def info_msg(self): return "{0}#{1}#{2}".format(info, self.content, self.hidden)
answers question: http://stackoverflow.com/q/46903676
type: AcceptedAnswer
type: Answer

sqlite
tags question: http://stackoverflow.com/q/46851802
tags question: http://stackoverflow.com/q/46779416
tags question: http://stackoverflow.com/q/46868730
tags question: http://stackoverflow.com/q/46867476
tags question: http://stackoverflow.com/q/46854532
type: Tag
tags question: http://stackoverflow.com/q/46787651
tags question: http://stackoverflow.com/q/46905691
tags question: http://stackoverflow.com/q/46754674
tags question: http://stackoverflow.com/q/46872357
tags question: http://stackoverflow.com/q/46888360
tags question: http://stackoverflow.com/q/46856379
tags question: http://stackoverflow.com/q/46894693
tags question: http://stackoverflow.com/q/46809693
tags question: http://stackoverflow.com/q/46758389
tags question: http://stackoverflow.com/q/46875682
tags question: http://stackoverflow.com/q/46814200
tags question: http://stackoverflow.com/q/46815435
tags question: http://stackoverflow.com/q/46773474
tags question: http://stackoverflow.com/q/46751267
tags question: http://stackoverflow.com/q/46867827
tags question: http://stackoverflow.com/q/46834412
tags question: http://stackoverflow.com/q/46759232
tags question: http://stackoverflow.com/q/46831783
tag name: sqlite

http://stackoverflow.com/a/46755648
accepted answer of: http://stackoverflow.com/q/46753162
has comment: http://stackoverflow.com/comment/80484532
has comment: http://stackoverflow.com/comment/80488060
type: Answer
has body: I have tried to do that by myself. So I convert char * to bytes in cython. (according to docs) That is what I came up with. I have the following setup (gcc and centos7.2): setup.py from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("func.pyx") ) main.c #include "Python.h" #include "func.h" int main() { Py_Initialize(); initfunc(); func("0123hello jorghy!!"); Py_Finalize(); return 0; } func.pyx cdef public func(char * arg): cdef bytes py_bytes = arg print(str(py_bytes)); I build all this stuff with the following commands: python setup.py build_ext --inplace gcc -I/usr/include/python2.7 -lpython2.7 -Wall -Wextra -O2 -g -o test main.c func.c Then when running the executable file test I get the following results: 0123hello jorghy!! UPDATE There is another way to approach this problem: I have created a cython file test.pyx: import sys if __name__ == "__main__": print("hei") print(sys.argv) And compiled as an executable it using commands: cython test.pyx --embed gcc -I/usr/include/python2.7 -lpython2.7 -Wall -Wextra -O2 -g -o test test.c Then you can call this code as an executable file: $ ./test 1 2 3 hei ['./test', '1', '2', '3'] Then you can call it from C++ using std::system or other (better) methods.
upvote count: 1
has comment: http://stackoverflow.com/comment/80456743
answers question: http://stackoverflow.com/q/46753162
has comment: http://stackoverflow.com/comment/80484620
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80484485

http://stackoverflow.com/comment/136345831
comment on: http://stackoverflow.com/a/47016710
score: 0
type: AnswerComment
type: Comment
has text: I don't understand exactly the **update** part for python >= 3.12, the [doc](https://docs.python.org/3/reference/datamodel.html#preparing-the-class-namespace) says _"The namespace returned by __prepare__ is passed in to __new__, but when the final class object is created the namespace is copied into a new dict."_ and you wrote _"discarded after the metaclass __init__ method is called"_. Can you say smt more on this sentence?

http://stackoverflow.com/q/46869468
downvote count: 0
has comment: http://stackoverflow.com/comment/80686753
score: 1
accepted answer: http://stackoverflow.com/a/46869490
has comment: http://stackoverflow.com/comment/80686150
type: Question
tagged with: passwords
has title: Am I able to use the function 'count()' to find the amount of upper cases in a password? (PYTHON)
has answer: http://stackoverflow.com/a/46869490
possible better answer: http://stackoverflow.com/a/46869499
answer count: 2
has answer: http://stackoverflow.com/a/46869499
upvote count: 1
has body: When I enter the code below, it says: TypeError: must be str, not list Does this mean I cannot use the function count() or is there another way I could program it? password = "CheeseMakesMeHappy" uppercase =["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"] print (password.count(uppercase))
favorite count: 0
tagged with: uppercase
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/106253893
has text: Added include_package_data above. Re: cfg, I'm a bit torn. Having an extra cfg file is cleaner for the setup, but limits my ability to do stuff to the opened files. For example, in this case I strip whitespace from VERSION to prevent easy to make/hard to identify errors in updating the file. Re: your original point #2, I had originally intended for both __init__.py and setup.py to read the VERSION file, but had trouble with the pathing to the VERSION file in __init__.py. Any thoughts on what that path should be? I had thought just a relative path to 'VERSION'.
comment on: http://stackoverflow.com/a/60066396
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/46845464
has comment: http://stackoverflow.com/comment/80638960
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/80639091
has comment: http://stackoverflow.com/comment/80639104
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80639084
has comment: http://stackoverflow.com/comment/80639371
upvote count: 3
has comment: http://stackoverflow.com/comment/80638506
possible better answer: http://stackoverflow.com/a/46845801
has answer: http://stackoverflow.com/a/53643996
has answer: http://stackoverflow.com/a/46845801
type: Question
score: 3
has answer: http://stackoverflow.com/a/46845731
has comment: http://stackoverflow.com/comment/80638692
has body: I am receiving data in batches from an API in JSON format. I wish to store only the values, in a list. The raw data looks like this and will always look like this, i.e: all {...} will look like the first example: data = content.get('data') &gt;&gt;&gt; [{'a':1, 'b':{'c':2, 'd':3}, 'e':4}, {...}, {...}, ...] The nested dictionary is making this harder; I need this unpacked as well. Here is what I have, which works but it feels so bad: unpacked = [] data = content.get('data') for d in data: item = [] for k, v in d.items(): if k == 'b': for val in v.values(): item.append(val) else: item.append(v) unpacked.append(item) Output: &gt;&gt;&gt; [[1,2,3,4], [...], [...], ...] How can I improve this?
has comment: http://stackoverflow.com/comment/80638560
has answer: http://stackoverflow.com/a/46846813
has answer: http://stackoverflow.com/a/46845795
has comment: http://stackoverflow.com/comment/80638651
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/46845731
has title: Cleaner way to unpack nested dictionaries
has comment: http://stackoverflow.com/comment/80638670
answer count: 5

http://stackoverflow.com/comment/80655431
type: QuestionComment
has text: @sascha I did copy the command I am running with `pip3` to install the wheel file. And `pip3` is located at: `(whereis pip3) C:\Users\xxxxx\AppData\Local\Programs\Python\Python36-32\Scripts\pip3.exe`.
comment on: http://stackoverflow.com/q/46853873
score: 0
type: Comment

http://stackoverflow.com/comment/80528700
comment on: http://stackoverflow.com/q/46791139
score: 0
type: QuestionComment
has text: The above commenter is right, but it might be faster to do it in place? Loop over it and explicitly change each one rather than creating a new list. It's still a for loop, but you avoid needing to create extra space in memory.
type: Comment

http://stackoverflow.com/comment/80485116
type: Comment
type: QuestionComment
score: 0
has text: I don't think you need a pipe here... You want to `map` an `os.system` call... Besides, I'm not even sure `ffmpeg` accepts binary data
comment on: http://stackoverflow.com/q/46769464

http://stackoverflow.com/comment/93257363
comment on: http://stackoverflow.com/q/46796126
score: 0
has text: @Broman Without determinism, can you even define the semantic of a program?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/80646534
comment on: http://stackoverflow.com/a/46849429
has text: Hm, I've tried it out and I'm still getting the same error.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/59844043
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46896093
type: Answer
has body: When you use "virtualenv" to create an env, it saves an "activate.bat" file in the scripts folder originating from the directory you ran the first command. E.g if you ran the command virtualenv env from C:/Users/Name/Documents/..., the .bat will be located in C:/Users/Name/Documents/.../env/scripts/activate.bat. You can run it from there.

http://stackoverflow.com/comment/80704128
has text: Please post your code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46876388

http://stackoverflow.com/comment/80750112
has text: @ShadowRanger thx. fixed
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/46901641
score: 0

http://stackoverflow.com/comment/80742064
type: Comment
has text: My solution is in updated question, thank you for your help.
comment on: http://stackoverflow.com/a/46879022
type: AnswerComment
score: 0

http://stackoverflow.com/q/46801798
has body: Currently I have the following directory my_epic_module -&gt; .gitignore -&gt; my_epic_module.py main.py When I try to import my_epic_module.py from main.py I do the following # the following does not work import my_epic_module my_epic_module.bar("foo") # the following works from my_epic_module import my_epic_module my_epic_module.bar("foo") How do I make it so that I can just import it "normally" like the top first example? Do I need to add an __init__.py? If so what do I need to put into it?
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46801821
tagged with: python
has answer: http://stackoverflow.com/a/46804512
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/46804512
has title: How to make python import module along with folder?
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/46801821
answer count: 2

http://stackoverflow.com/comment/80454433
comment on: http://stackoverflow.com/q/46754398
score: 1
has text: Could you add `df.dtypes` to the question? Suspecting if later is string column and former is numeric type.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/46778379
has body: It turns out lonAltMatrix = [list(a) for a in zip(lon, alt)] works to create a 5x2 matrix. For np.polyfit() the number of rows for the y-coordinate must match the length of the x-coordinate.
accepted answer of: http://stackoverflow.com/q/46776079
answers question: http://stackoverflow.com/q/46776079
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/46854786
tagged with: cython
answer count: 1
has title: Set visibility in pure-python Cython code
has body: one of my major problems with cython cdef classes is that all their variables are by default private. When I am converting some python code to pure-python-mode cython, I have to manually use var_name = cython.declare(type, visibility='public) for every variable. Is it possible to set all cdef class variables to be public by default? If not, do you consider it a good idea, perhaps for feature request?
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/46854868
favorite count: 0
type: Question
score: 3
tagged with: python
upvote count: 3

http://stackoverflow.com/a/46755185
type: Answer
has body: Use join: df = df1.join(df2, on='accountname', how='inner').reset_index() print (df) ip accountname name gsm 0 192.168.1.1 aaaa john doe 850 1 192.168.1.2 bbbb jane doe 860
has comment: http://stackoverflow.com/comment/80455999
has comment: http://stackoverflow.com/comment/80455873
upvote count: 3
answers question: http://stackoverflow.com/q/46755146
has comment: http://stackoverflow.com/comment/80456594
score: 3
has comment: http://stackoverflow.com/comment/80455886
downvote count: 0
has comment: http://stackoverflow.com/comment/80456012
has comment: http://stackoverflow.com/comment/121985983

http://stackoverflow.com/a/46899182
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/46898063
score: 4
has body: The issue was corrected by updating Pillow. The following command was run: sudo pip3 pillow --upgrade
answers question: http://stackoverflow.com/q/46898063

http://stackoverflow.com/comment/80534793
type: QuestionComment
has text: you set `u` to `[]` and then iterate over it. this will not work. i think you made a copy&paste error here.
comment on: http://stackoverflow.com/q/46794017
score: 0
type: Comment

http://stackoverflow.com/comment/80858391
type: Comment
has text: run `module purge` before the `module load` to make sure Slurm does not propagate another MPI env to the job
type: QuestionComment
comment on: http://stackoverflow.com/q/46873656
score: 0

google-app-engine
tag name: google-app-engine
tags question: http://stackoverflow.com/q/46836664
type: Tag
tags question: http://stackoverflow.com/q/46757071
tags question: http://stackoverflow.com/q/46759689
tags question: http://stackoverflow.com/q/46872034
tags question: http://stackoverflow.com/q/46885025
tags question: http://stackoverflow.com/q/46895679
tags question: http://stackoverflow.com/q/46902090
tags question: http://stackoverflow.com/q/46857639
tags question: http://stackoverflow.com/q/46846612
tags question: http://stackoverflow.com/q/46887497
tags question: http://stackoverflow.com/q/46831801
tags question: http://stackoverflow.com/q/46792603
tags question: http://stackoverflow.com/q/46821301
tags question: http://stackoverflow.com/q/46867161
tags question: http://stackoverflow.com/q/46840828
tags question: http://stackoverflow.com/q/46877583
tags question: http://stackoverflow.com/q/46836564
tags question: http://stackoverflow.com/q/46889772
tags question: http://stackoverflow.com/q/46781683
tags question: http://stackoverflow.com/q/46879228
tags question: http://stackoverflow.com/q/46807209
tags question: http://stackoverflow.com/q/46823143
tags question: http://stackoverflow.com/q/46800575

http://stackoverflow.com/a/46901547
type: Answer
has body: file_average = number_total/line+number After the while loop you are using line toget average. Is that really required. Or are you finding each line average then place in while loop.
answers question: http://stackoverflow.com/q/46899900
score: 0
has comment: http://stackoverflow.com/comment/80772655

http://stackoverflow.com/q/46807838
has comment: http://stackoverflow.com/comment/80563843
type: Question
tagged with: airflow
has body: I would like to schedule a Python job to launch it every 15 minutes. I have already used airflow and haven't met any issues before. I created a dag with a start date earlier today, a frequency of 15 minutes and two tasks which consist of activating a virtual Python environment and then launch a python script. However, my dags do not execute itself so I started a web server to check its status and nothing happened. I, therefore, tried to launch it externally using the trigger_dag command but its status remain on running. I really do not understand what the problem is, any help would be appreciated. I attach two screenshots of the Airflow webserver which show the problem. Edit : added the dags.py file, here is the definition of my dags : import os from airflow import DAG from datetime import datetime, timedelta from airflow.operators.bash_operator import BashOperator default_args = { 'owner': 'test', 'depends_on_past': False, 'start_date': datetime(2017,10,13,0,0,0,0), 'email': ['test@gmail.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=15), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, #'end_date': datetime(2017, 9, 23), } dag = DAG('dbscan_integ', default_args=default_args) t_dbscan = BashOperator( task_id='job_batch_dbscan', bash_command='/home/test/Documents/git_repo/analyser/algo_integ/integration_dbscan/python main_algo.py', dag=dag) t_virtual_dbscan = BashOperator( task_id='virtual_dbscan', bash_command='source activate integdb', dag=dag) t_dbscan.set_upstream(t_virtual_dbscan)
score: 0
has comment: http://stackoverflow.com/comment/80566569
answer count: 1
has title: Airflow does not launch my dags (activate a python environment and launch a python script)
has answer: http://stackoverflow.com/a/46857704
accepted answer: http://stackoverflow.com/a/46857704
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/80454318
has text: The amount of times I read through the code and didn't see this. Thanks Daniel aka eagle eye
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46754329

http://stackoverflow.com/comment/80930393
score: 0
has text: Fixed using python 3.4 instead of 3.6
comment on: http://stackoverflow.com/q/46819980
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46890646
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46896215
has title: Asyncio: Weirdness of Task exception was never retrieved
tagged with: error-handling
upvote count: 44
type: Question
score: 44
accepted answer: http://stackoverflow.com/a/46896215
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/30361824
tagged with: python-asyncio
tagged with: exception
tagged with: python
has body: Lets assume I have a simple code: import asyncio async def exc(): print(1 / 0) loop = asyncio.get_event_loop() loop.create_task(exc()) try: loop.run_forever() except KeyboardInterrupt: loop.stop() loop.close() If I run it, I get error message immediately Task exception was never retrieved future: &lt;Task finished coro=&lt;exc() done, defined at qq.py:4&gt; exception=ZeroDivisionError('division by zero',)&gt; Traceback (most recent call last): File "qq.py", line 5, in exc print(1 / 0) ZeroDivisionError: division by zero But, if I change loop.create_task(exc()) to task = loop.create_task(exc()) I'll get the same error message after click ctrl+c Why does task assignment change the time of output of error?
has comment: http://stackoverflow.com/comment/80729977

http://stackoverflow.com/comment/80617241
comment on: http://stackoverflow.com/q/46834732
has text: have you tried: `df.dates.apply(lambda x: x.replace("-", ""))` because it seems like the data is in string format.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46798489
tagged with: gdb
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/46798740
tagged with: c++
has title: Extracting "object contents" printout from a c++ const ref in gdb?
score: 0
has body: Consider the following example, called for instance test-types-gdb-printout.cpp (which emulates a similar situation in my current, more complex, debugging process): #include &lt;iostream&gt; #include &lt;cstdio&gt; namespace Some { namespace Stuff { template&lt;typename Type&gt; class MyVect { public: MyVect(); MyVect(Type x, Type y); Type AddComps(); operator const Type*() const; operator Type*(); Type x; Type y; }; template&lt;typename Type&gt; MyVect&lt;Type&gt;::MyVect() { } template&lt;typename Type&gt; MyVect&lt;Type&gt;::MyVect(Type _x, Type _y) { x = _x; y = _y; } template&lt;typename Type&gt; Type MyVect&lt;Type&gt;::AddComps() { return x+y; } template &lt; typename Type &gt; MyVect&lt; Type &gt;::operator const Type*() const { return &amp;x; } template &lt; typename Type &gt; MyVect&lt; Type &gt;::operator Type*() { return &amp;x; } typedef MyVect&lt;int&gt; MyVecti; }} int main() { Some::Stuff::MyVecti mvi(5,10); const Some::Stuff::MyVecti&amp; mvic = mvi; Some::Stuff::MyVecti* mvip = new Some::Stuff::MyVecti(30,12); printf("Result is: %d ; then %d\n", mvi.AddComps(), mvip-&gt;AddComps()); // line 46 delete mvip; return 0; } I compile this with: g++ -g test-types-gdb-printout.cpp -o test-types-gdb-printout.exe ... and then I run it in the gdb debugger as so: $ gdb -ex "b test-types-gdb-printout.cpp:46" -ex "r" -ex "p mvi" -ex "p mvic" -ex "p mvip" --args ./test-types-gdb-printout.exe GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.3) 7.7.1 ... Reading symbols from ./test-types-gdb-printout.exe...done. Breakpoint 1 at 0x4007e7: file test-types-gdb-printout.cpp, line 50. Starting program: /tmp/test-types-gdb-printout.exe Breakpoint 1, main () at test-types-gdb-printout.cpp:50 50 printf("Result is: %d ; then %d\n", mvi.AddComps(), mvip-&gt;AddComps()); $1 = {x = 5, y = 10} $2 = (const Some::Stuff::MyVecti &amp;) @0x7fffffffdc30: {x = 5, y = 10} $3 = (Some::Stuff::MyVecti *) 0x602010 (gdb) Note that in gdb, when I print: mvi, which is of type Some::Stuff::MyVecti, I get…
answer count: 1
tagged with: debugging
type: UnansweredQuestion

http://stackoverflow.com/a/46876158
has comment: http://stackoverflow.com/comment/80699259
downvote count: 0
answers question: http://stackoverflow.com/q/46876101
has comment: http://stackoverflow.com/comment/80699294
score: 4
type: AcceptedAnswer
has body: In Python, functions always return something. If there is no return statement, then the value None is returned. In your code, f() executes a(), and returns the return value of a(), which happens to be None. g() executes a(), and ignores a()'s return value. That said, when you have statements like f() and g(), you are ignoring the return values of these function calls. As @Patrick suggested, let's try making a() return a value 42. Then, instead of ignoring the values of function calls f() and g(), let's save their return values in variables f_return_val and g_return_val. Print them out and see what you get. def a(): print('Hello World') return 42 def f(): return a() def g(): a() f_return_val = f() print(f_return_val) g_return_val = g() print(g_return_val) You may find this article What precisely does "return" in this code do? helpful.
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/46876101

http://stackoverflow.com/comment/80842660
type: Comment
comment on: http://stackoverflow.com/a/46905659
score: 0
type: AnswerComment
has text: The problem seems to have gone; I'm not sure if it was about the files being overwritten or something. I learned from your test regarding the file's presence, though, so I've attempted an upvote of your answer. (My reputation isn't yet high enough for my upvotes to be counted.) Thanks!

http://stackoverflow.com/a/46754172
type: Answer
has body: You can capture the return value in a variable, and return it after printing: def decorator(func): def logger(*args, **kwargs): print "start logging" result = func(*args, **kwargs) print "end logging" return result return logger Decorators are not special here; it's just a function calling another function.
answers question: http://stackoverflow.com/q/46754128
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/46754128

xml.etree
type: Tag
tag name: xml.etree
tags question: http://stackoverflow.com/q/46901106

http://stackoverflow.com/q/46862147
favorite count: 0
has answer: http://stackoverflow.com/a/46862220
has answer: http://stackoverflow.com/a/46862190
has comment: http://stackoverflow.com/comment/80671981
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/80672013
answer count: 4
has comment: http://stackoverflow.com/comment/80671977
has body: I am practicing python code and executing it through command line. each time i have to execute my python file i go to cmd and write D:\PythonPractice&gt;python myClass.py Is there any standard and comfortable way available to execute python code quickly?
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/80672021
has answer: http://stackoverflow.com/a/46862264
has comment: http://stackoverflow.com/comment/80671799
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46862190
has comment: http://stackoverflow.com/comment/80671754
has title: How to run python script without writing command on cmd again and again
type: Question
has answer: http://stackoverflow.com/a/46862418
possible better answer: http://stackoverflow.com/a/46862220

http://stackoverflow.com/comment/80594298
type: QuestionComment
type: Comment
has text: `random.sample` selects *without replacement*. If you have Python 3.6 (or more recent) see `random.choice`. [Documentation](https://docs.python.org/3/library/random.html#functions-for-sequences)
comment on: http://stackoverflow.com/q/46822979
score: 0

http://stackoverflow.com/comment/80696435
comment on: http://stackoverflow.com/a/46867849
type: AnswerComment
has text: Yes my code is checking whether number of rows are equal or not, because if it is not equal, you can't compare columns. After checking the equality of row numbers, the function compares content of columns in for loop. For loop is inside the function. If you you try the function with different inputs, you will see it works.
score: 0
type: Comment

http://stackoverflow.com/comment/80735147
type: QuestionComment
comment on: http://stackoverflow.com/q/46888809
has text: That seems really odd... A quick and dirty fix would be to just replace them with a `.replace('{}', '')` at the end of the url. Have you tried running this locally? How do you upload your code to scrapinghub?
score: 0
type: Comment

http://stackoverflow.com/comment/80752027
has text: Oh sorry, that should be `select_node` as well. I will change the original question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46902467

http://stackoverflow.com/comment/80749780
type: QuestionComment
has text: Use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
score: 1
comment on: http://stackoverflow.com/q/46901401
type: Comment

http://stackoverflow.com/comment/80522182
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46784010
has text: That is correct. Hence your code snippet below "is actually evaluated as:" is incorrect. You imply there that the assignment `A = c` happens __before__ any other assignments.

http://stackoverflow.com/comment/80622580
type: Comment
comment on: http://stackoverflow.com/a/46826627
has text: @tinaK - not that I'm aware of (it's what I do). Your post indicated that you didn't want to have to be a root user in order to manage the installation/update of packages. One reason that you might want to set up a group as described is if you want to allow other people to add/update packages without giving them root privileges.
score: 0
type: AnswerComment

http://stackoverflow.com/a/46843510
upvote count: 5
has comment: http://stackoverflow.com/comment/84253828
type: Answer
has comment: http://stackoverflow.com/comment/80817425
has comment: http://stackoverflow.com/comment/80672942
downvote count: 0
answers question: http://stackoverflow.com/q/46818391
accepted answer of: http://stackoverflow.com/q/46818391
score: 5
has comment: http://stackoverflow.com/comment/80657141
type: AcceptedAnswer
has body: You can get the desired functionality with Plotly online but all the data needs to be loaded when the first graph is rendered. Perhaps have a look at Plotly's Dash which enabled dynamic loading of data. In order to get the dropmenu which shows traces you could do the following: First create map, then add a scatter plot for each country but only show the map by setting the visible attribute. Create a drop down menu which shows the scatter plot for the selected country (by passing an array of Booleans to visible) Add a menu entry to show the map again import pandas as pd import plotly plotly.offline.init_notebook_mode() df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv') # create the initial map data = [dict(type='choropleth', locations = df['code'].astype(str), z=df['total exports'].astype(float), locationmode='USA-states', visible=True)] layout = dict(geo=dict(scope='usa', projection={'type': 'albers usa'})) # create the empty dropdown menu updatemenus = list([dict(buttons=list()), dict(direction='down', showactive=True)]) total_codes = len(df.code.unique()) + 1 for s, state in enumerate(df.code.unique()): # add a trace for each state data.append(dict(type='scatter', x=[i for i in range(1980, 2016)], y=[i + random.random() * 100 for i in range(1980, 2016)], visible=False)) # add each state to the dropdown visible_traces = [False] * total_codes visible_traces[s + 1] = True updatemenus[0]['buttons'].append(dict(args=[{'visible': visible_traces}], label=state, method='update')) # add a dropdown entry to reset the map updatemenus[0]['buttons'].append(dict(args=[{'visible': [True] + [False] * (total_codes - 1)}], label='Map', method='update')) layout['updatemenus'] = updatemenus fig = dict(data=data, layout=layout) plotly.offline.iplot(fig)

http://stackoverflow.com/comment/80591446
has text: Yes, for lists and dictionaries, or any other mutable object.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/46821979
score: 0

http://stackoverflow.com/a/46910220
upvote count: 3
answers question: http://stackoverflow.com/q/46892522
score: 3
has comment: http://stackoverflow.com/comment/86120298
has comment: http://stackoverflow.com/comment/86107078
downvote count: 0
has body: This is a safer solution than @jdoe's, because the structure of the Validator.errors property doesn't necessarily correlate to a document's one. But the document_error_tree provides such. def remove_invalid_fields(document, errors_tree): if errors_tree is None: return document filtered = {} for field, value in document.items(): if field in errors_tree.descendants: continue if isinstance(value, Mapping): value = remove_invalid_fields(value, errors_tree[field]) filtered[field] = value return filtered schema = {'name': {'type': 'string'}, 'user_id': {'type': 'integer'}} document = {'name': 'john doe', 'user_id': 'fdfdfd'} validator = Validator(schema) validator(document) result = remove_invalid_fields(document, validator.document_error_tree) assert result == {'name': 'john doe'} It also takes errors in subdocuments into account.
type: Answer

http://stackoverflow.com/comment/80504195
type: Comment
type: QuestionComment
has text: f.write(str(starttime) + '--' + str(endtime))
comment on: http://stackoverflow.com/q/46776501
score: 0

http://stackoverflow.com/q/46820793
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/46822103
score: 0
has body: I have made a crosstab on 3 variables (position, offer, group). How can I calculate the percentage by the total of 1 variable offer, but not the margins (i.e. normalize by column)? df = pd.crosstab(df.group, [df.position, df.offer], margins = True) df pid offer position group 1 accept left group1 1 accept left group1 1 accept right group2 1 reject right group2 1 reject right group1 2 reject right group1 2 reject left group2 2 accept left group3 3 accept right group3 3 reject right group1 3 reject right group2 my current crosstab: position left right All offer accept reject accept reject group1 2 0 0 3 5 group2 0 1 1 2 4 group3 1 0 1 0 2 All 3 1 2 5 11 expected outcome: position left right offer accept reject accept reject group1 1 0 0 1 group2 0 1 0.33 0.66 group3 1 0 1 0 Thanks!
answer count: 2
tagged with: pandas
tagged with: crosstab
has answer: http://stackoverflow.com/a/46821047
has comment: http://stackoverflow.com/comment/80589044
accepted answer: http://stackoverflow.com/a/46821047
has answer: http://stackoverflow.com/a/46822103
tagged with: python
has title: calculate percentage in high dimensional crosstab

http://stackoverflow.com/q/46842995
has title: python failed to check module which I installed
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80633649
tagged with: python
type: Question
has body: I have installed a module named "Image" in python 3.6 using pip doing: pip install Image it installed successfully. But when I tried to import this into my script it produced an error. Here is what happened import Image ModuleNotFoundError: No module named 'Image' When i tried to reinstall it pip says all the requirements are satisfied. C:\Users\abc&gt;pip install Image Requirement already satisfied: Image in c:\users\abc\appdata\local\programs\python\python36-32\lib\site-packages Requirement already satisfied: django in c:\users\abc\appdata\local\programs\python\python36-32\lib\site-packages (from Image) Requirement already satisfied: pillow in c:\users\abc\appdata\local\programs\python\python36-32\lib\site-packages (from Image) Requirement already satisfied: pytz in c:\users\abc\appdata\local\programs\python\python36-32\lib\site-packages (from django-&gt;Image) Requirement already satisfied: olefile in c:\users\abc\appdata\local\programs\python\python36-32\lib\site-packages (from pillow-&gt;Image) Any help to solve this issue.... or anyother package to download googlemaps of a partucular area at high resolution
has answer: http://stackoverflow.com/a/46843150
score: 0

http://stackoverflow.com/comment/80733019
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46858035
has text: I mean pretty much exactly how I have the two rules for align in my answer, but the inputs are outputs instead. Can you post what your snakemake file looks like after making them two separate rules? There may be some other issue causing the error.
type: AnswerComment

http://stackoverflow.com/a/46797508
has body: You're modifying one dataframe, but writing another, that's the reason. Use select_dtypes instead. c = df.select_dtypes(include=[object]).columns df[c] = df[c].astype(str) df.to_csv("2008_data_test.csv_tostring2.csv", index=False) As MaxU suggested, it might be simpler to do filter by dtypes in this manner: c = df.columns[df.dtypes.eq('object')] The former creates a dataframe subslice before accessing columns, so this should be cheaper. If you want to convert specific columns only, you can remove columns as needed from c before the conversion using c = c.difference(['Col1', 'Col2', ...]).
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/46797412
upvote count: 1
answers question: http://stackoverflow.com/q/46797412
has comment: http://stackoverflow.com/comment/80545123
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80544830
has comment: http://stackoverflow.com/comment/80545151

http://stackoverflow.com/comment/80609229
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/46830631
has text: yeah you should really learn some html basics if you want to be able to use any of this sort of thing
type: Comment

http://stackoverflow.com/q/46774127
accepted answer: http://stackoverflow.com/a/46775305
tagged with: numpy
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80494333
tagged with: python
has body: I've noticed a weird thing recently, Tensorflow seems to use too much memory when initializing the variables with constants. Can someone help me understand the example below? $ python -m memory_profiler test.py [0 1 2 3 4 5 6 7 8 9] Filename: test.py Line # Mem usage Increment Line Contents ================================================ 4 144.531 MiB 0.000 MiB @profile 5 def go(): 6 907.312 MiB 762.781 MiB a = np.arange(100000000) 7 910.980 MiB 3.668 MiB s = tf.Session() 8 1674.133 MiB 763.152 MiB b = tf.Variable(a) 9 3963.000 MiB 2288.867 MiB s.run(tf.variables_initializer([b])) 10 3963.145 MiB 0.145 MiB print(s.run(b)[:10])
type: AnsweredQuestion
tagged with: memory-management
has answer: http://stackoverflow.com/a/46775305
has comment: http://stackoverflow.com/comment/80495776
upvote count: 3
has title: Tensorflow uses too much memory when initializing with constants
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/80495545
score: 3
has comment: http://stackoverflow.com/comment/80495564
has comment: http://stackoverflow.com/comment/80495120

http://stackoverflow.com/comment/80566966
comment on: http://stackoverflow.com/q/46809445
score: 0
type: Comment
type: QuestionComment
has text: make_timestamped_loc() ?? But what happens next? Does that function return data? If you tell us how you get your data it is much easier to help

http://stackoverflow.com/q/46903114
has body: I am quiet new to python, and I want to extract one page from a text file. Each page starts with a unique line and ends with '//'. And I want to find a way to return a certain page knowing the unique line associated with it. Do you know what tools can I use?
answer count: 3
has answer: http://stackoverflow.com/a/46903262
has title: print one page in text file using python
has answer: http://stackoverflow.com/a/46903291
favorite count: 0
possible better answer: http://stackoverflow.com/a/46903198
has answer: http://stackoverflow.com/a/46903198
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46903262
downvote count: 2
tagged with: file
upvote count: 1
type: Question
score: -1

http://stackoverflow.com/comment/80679253
type: Comment
has text: OK, I understand...but I think perhaps your answer needs more elaborate example code as well as a more complete explanation.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/46865661

http://stackoverflow.com/a/46905064
type: Answer
score: 0
answers question: http://stackoverflow.com/q/46905022
has body: you can try this data = request.data if you sending file data files = request.FILES

http://stackoverflow.com/comment/80674877
comment on: http://stackoverflow.com/q/46863568
score: 1
has text: @new_to_coding your approach is basically giving the same results, by fluke, if you are attempting to sort them by keys i.e. 1, 2, 3. In a very different scenario of values in your dictionary these two sorted calls might return entirely different sequences.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/46820625
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80703341
possible better answer: http://stackoverflow.com/a/46821748
has comment: http://stackoverflow.com/comment/80605954
upvote count: 18
has answer: http://stackoverflow.com/a/46821748
accepted answer: http://stackoverflow.com/a/46820836
type: Question
has body: I'm using Kali dist so I have already installed Python 2.7, 3.5 and 3.6. Commands 'python' and 'pip' are associated with Python 2.7. But the 'python3' uses Python 3.6 while pip3 is installing packages for Python 3.5. When I tried to create an venv: pip3 -p python3.6 virtualenv myenv I've got an error: no such option: -p How can I associate pip3 with Python 3.6 instead of Python 3.5?
linked to: http://stackoverflow.com/q/34803040
has answer: http://stackoverflow.com/a/59038498
answer count: 7
has comment: http://stackoverflow.com/comment/80624286
has title: How to use pip3 for python 3.6 instead of python 3.5?
favorite count: 0
has comment: http://stackoverflow.com/comment/80685861
score: 17
has answer: http://stackoverflow.com/a/62929254
tagged with: python
has answer: http://stackoverflow.com/a/46820915
linked to: http://stackoverflow.com/q/38249961
has answer: http://stackoverflow.com/a/65942543
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41328451
has answer: http://stackoverflow.com/a/46820836
has answer: http://stackoverflow.com/a/67981417
tagged with: pip
downvote count: 1

http://stackoverflow.com/comment/80626285
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46838871
has text: I think the infinite print part is now settled, if you have further questions about your code/bugs, please post a new question. Also, please follow the guidelines as the people above posted.

http://stackoverflow.com/q/46762648
has comment: http://stackoverflow.com/comment/80470927
answer count: 1
has body: I have set this dataframe: df = pd.DataFrame(columns=('artist', 'track', 'pos', 'neg', 'neu')) and this code to populate it: i = 0 for item in artist_track: artist = item[0] track = item[1] try: mood = track_mood(artist, track) # a function df.loc[i] = (artist, track, mood['pos'], mood['neg'], mood['neu']) i += 1 except: print 'cant find {} lyrics'.format(track) the code works when lyrics are found, but I'm losing artist and track entries for each exception raised. how can I add 'artist'and 'track' to dataframe with 0.0 values for 'pos', 'neg' and 'neu' when exceptions are raised? traceback: assert type(exception).__name__ == 'NameError' AssertionError
has answer: http://stackoverflow.com/a/46762701
has comment: http://stackoverflow.com/comment/80470597
tagged with: exception
has comment: http://stackoverflow.com/comment/80470605
has comment: http://stackoverflow.com/comment/80470581
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46762701
has comment: http://stackoverflow.com/comment/80470591
type: Question
has title: Handling exceptions when populating pandas dataframe
tagged with: dataframe
has comment: http://stackoverflow.com/comment/80470937
score: 0
tagged with: pandas

http://stackoverflow.com/q/46809615
tagged with: python
has body: Here is my Code: dfnew=pd.DataFrame({ 'year': [2015,2016], 'month': [10, 12], 'day': [25,31]}) print(dfnew) def calc(yy,n): if yy==2016: return yy*2*n else: return yy dfnew['nv']=map(calc, dfnew['year'],2) print(dfnew['nv']) How I can get this code running without error? I want the function to be applied only on the 'Year' column of the dataframe for all rows and store output on a new column named 'nv' of the same dataframe.
upvote count: 5
type: Question
has answer: http://stackoverflow.com/a/46812520
answer count: 2
score: 5
tagged with: function
downvote count: 0
has answer: http://stackoverflow.com/a/46809743
tagged with: pandas
has title: User defined function on pandas dataframe
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/46814782
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/46814938
has comment: http://stackoverflow.com/comment/80577189
tagged with: python
type: AnsweredQuestion
has title: How does this lambda function work in python 3?
upvote count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/80595316
has comment: http://stackoverflow.com/comment/80577021
accepted answer: http://stackoverflow.com/a/46814938
type: Question
has body: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) print(pairs) Ans: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] How does the pair argument work here?
score: 0
has comment: http://stackoverflow.com/comment/80577250
answer count: 1

http://stackoverflow.com/a/46883598
type: Answer
answers question: http://stackoverflow.com/q/46882954
has comment: http://stackoverflow.com/comment/80739407
score: 0
has body: Improve your insert statement to handle already existing values: cursor.execute('INSERT IGNORE INTO user(email, password) VALUES(%s ,%s)') This way there will be no DB error, and you could handle it according to the return value.

http://stackoverflow.com/q/46826184
tagged with: binary
accepted answer: http://stackoverflow.com/a/46826302
has title: How to count number of zeros at the left of each one in an Numpy array
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/46826684
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46826289
possible better answer: http://stackoverflow.com/a/46826684
type: Question
has body: I have a numpy binary array like this: Array A = [1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0] I would like to count how many 0s are there at the left of each 1, and return it in an other array that would look like this for this for this example: nb_1s = [0, 0, 1, 2, 2, 5] There are no 0s at the left for the two first 1s so the the first two numbers of the array are 0 etc... I know that first I have to initiate an array with number of 1s in my array: def give_zeros(binary_array): binary_array = np.asarray(binary_array) nb_zeros = np.zeros(binary_array.sum()) return nb_zeros But I'm not sure on how to count the number of zeros. Should I iterate in a for loop with 'nditer'? It doesn't seem efficient as i will have to run this function on very large arrays. Do you have any ideas? Thank you.
has answer: http://stackoverflow.com/a/46826302
score: 4
has answer: http://stackoverflow.com/a/46826327
has comment: http://stackoverflow.com/comment/80599919
upvote count: 4
tagged with: numpy
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/80600098
has comment: http://stackoverflow.com/comment/80599936
favorite count: 0

http://stackoverflow.com/q/46828499
has body: Assume a simple function: def example(formula="") ... Where the argument "formula" should be one of 2400 possible chemical formulas. Would there be a way to get code completion for choosing one string from a list of 2400 strings? First idea was to chose from a list of class attributes. However, I can not use the dir() method. These formula strings are often invalid for use as attribute names. I don't see another method that would list a choice without using attributes of something. Thanks
score: 0
possible better answer: http://stackoverflow.com/a/46828639
has comment: http://stackoverflow.com/comment/80604427
has answer: http://stackoverflow.com/a/46828761
has answer: http://stackoverflow.com/a/46828639
type: Question
tagged with: code-completion
has title: (coding to get) Python code completion to choose from a list of allowable strings
answer count: 2
accepted answer: http://stackoverflow.com/a/46828761
has comment: http://stackoverflow.com/comment/80604497
has comment: http://stackoverflow.com/comment/80604675
tagged with: python
type: AnsweredQuestion

pyqt5
tags question: http://stackoverflow.com/q/46768314
tags question: http://stackoverflow.com/q/46779060
type: Tag
tags question: http://stackoverflow.com/q/46815926
tags question: http://stackoverflow.com/q/46837491
tags question: http://stackoverflow.com/q/46799206
tags question: http://stackoverflow.com/q/46773165
tags question: http://stackoverflow.com/q/46853383
tags question: http://stackoverflow.com/q/46895943
tags question: http://stackoverflow.com/q/46869472
tags question: http://stackoverflow.com/q/46785577
tags question: http://stackoverflow.com/q/46898063
tags question: http://stackoverflow.com/q/46752701
tags question: http://stackoverflow.com/q/46865289
tags question: http://stackoverflow.com/q/46818102
tags question: http://stackoverflow.com/q/46874619
tags question: http://stackoverflow.com/q/46844621
tags question: http://stackoverflow.com/q/46855815
tags question: http://stackoverflow.com/q/46893080
tags question: http://stackoverflow.com/q/46778410
tags question: http://stackoverflow.com/q/46837947
tags question: http://stackoverflow.com/q/46818396
tags question: http://stackoverflow.com/q/46795315
tags question: http://stackoverflow.com/q/46814961
tags question: http://stackoverflow.com/q/46758447
tags question: http://stackoverflow.com/q/46871570
tags question: http://stackoverflow.com/q/46878419
tags question: http://stackoverflow.com/q/46859945
tags question: http://stackoverflow.com/q/46794443
tags question: http://stackoverflow.com/q/46889571
tags question: http://stackoverflow.com/q/46869883
tags question: http://stackoverflow.com/q/46840764
tags question: http://stackoverflow.com/q/46830464
tags question: http://stackoverflow.com/q/46852457
tag name: pyqt5
tags question: http://stackoverflow.com/q/46799407
tags question: http://stackoverflow.com/q/46781292
tags question: http://stackoverflow.com/q/46851971
tags question: http://stackoverflow.com/q/46900213
tags question: http://stackoverflow.com/q/46825989
tags question: http://stackoverflow.com/q/46892542
tags question: http://stackoverflow.com/q/46876880

http://stackoverflow.com/a/46851557
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46851283
answers question: http://stackoverflow.com/q/46851283
type: Answer
has body: You need to pass the variable as a parameter. If you pass an int you need to typecast before you print it: def guess_home(coins): main_q = input("Type 'coins' to see you coin balance, or 'again' to play again") if main_q == "coins": print ("Your coins balance is: " + str(coins)) if main_q == "again": guess_game()

http://stackoverflow.com/a/46870867
downvote count: 0
type: AcceptedAnswer
has body: You could use a DictWriter, but it would be easier to just call zip and then write each pair to your CSV. import csv file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] } with open(...) as f: w = csv.writer(f) for x, y in zip(file['Formations'], file['Depth']): w.writerow([x, y])
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/46870844
score: 2
answers question: http://stackoverflow.com/q/46870844
has comment: http://stackoverflow.com/comment/80754877
has comment: http://stackoverflow.com/comment/80738523

http://stackoverflow.com/q/46903210
score: 1
has comment: http://stackoverflow.com/comment/80753088
favorite count: 0
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/80753841
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/46904139
has comment: http://stackoverflow.com/comment/80753929
has comment: http://stackoverflow.com/comment/80753672
has comment: http://stackoverflow.com/comment/80753234
type: UnansweredQuestion
has body: I wanted to include full text search in my django application. I am using whoosh-haystack for this.When I include whoosh and haystack in my installed apps,and execute the command ./manage.py, I am getting an import error. Can anyone sort this out. settings.py INSTALLED_APPS = { 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', 'whoosh', 'haystack', } when I make migration in my model the error which I got is: Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python \Python36\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 950, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 655, in _load_unlocked File …
has title: NameError: name 'base' is not defined(haystack search)
tagged with: whoosh
has comment: http://stackoverflow.com/comment/80753243
has comment: http://stackoverflow.com/comment/80753441
tagged with: django-haystack
downvote count: 0
has comment: http://stackoverflow.com/comment/80753327

http://stackoverflow.com/comment/80558270
type: QuestionComment
has text: @Reti43 Maybe it's a bit inconsistent, I'll take a look to that reference. Thanks
comment on: http://stackoverflow.com/q/46804696
score: 0
type: Comment

http://stackoverflow.com/a/47365565
has body: The first issue you faced ([INSTALL_FAILED_VERSION_DOWNGRADE]) was fixed in recent Appium server version 1.7.1, so if you are using latest server no need to search for workarounds. The second issue of not able to start Intent is more like problem with your Android app manifext.xml file, you check how it can be fixed here
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/46798761
answers question: http://stackoverflow.com/q/46798761
score: 2

http://stackoverflow.com/comment/80552647
type: AnswerComment
score: 0
has text: `'3008,\xe5\xa4\xa7\xe7\xab\x8b\xe5\x85\x89,$1$2,$1$2,$1$2,$1$2'` This is what my output is. I think there is something missing
type: Comment
comment on: http://stackoverflow.com/a/46802764

http://stackoverflow.com/comment/80741829
type: AnswerComment
has text: What is the output of print(tf.__version__) after run your python script?
score: 0
comment on: http://stackoverflow.com/a/46882595
type: Comment

http://stackoverflow.com/q/46882047
has comment: http://stackoverflow.com/comment/80711292
has title: How to split a one column Data Frame into multiple columns in pandas?
tagged with: python
has body: I'm reading a text file and it looks like this: 8 16 1 2 1.0 1 3 2.0 2 3 1.0 2 4 5.0 When I read this file, it's just a one column dataframe. I want to remove the first row and split it into a dataframe with three columns, with headers 'f', 't', 'l': 'f' 't' 'l' 0 1 2 1.0 1 1 3 2.0 2 2 3 1.0 3 2 4 5.0 How could I manipulate this?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/46882130
accepted answer: http://stackoverflow.com/a/46882130
upvote count: 1
type: Question
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/80747085
score: 0
comment on: http://stackoverflow.com/q/46899812
type: Comment
type: QuestionComment
has text: Possible duplicate of [UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte](https://stackoverflow.com/questions/22216076/unicodedecodeerror-utf8-codec-cant-decode-byte-0xa5-in-position-0-invalid-s)

http://stackoverflow.com/comment/80558154
has text: By running your code into my text file, I get the index 241, which corresponds to the line 'InChIKey=HCZNPUHZYPPINM-AWEZNQCLSA-M' +1. While what I want to get is the line 235, that is the line '//' + 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46803518
score: 0
type: Comment

http://stackoverflow.com/q/46791931
has title: Combining Two Separate WebScraped lists in Python
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/46792333
tagged with: python
accepted answer: http://stackoverflow.com/a/46792220
answer count: 4
has answer: http://stackoverflow.com/a/46792065
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46792633
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/46792220
type: Question
has answer: http://stackoverflow.com/a/46792333
downvote count: 0
has body: I am web scraping data from a car website to get prices. Right now, I am approaching the problem by creating two separate lists; one of the pricing data and another for the model of the car. Ultimately, I want to take each list and join the two together to create a CSV. The specific steps I am taking to solve this problem are the following: Establishing a connection to the website Creating two empty lists to write the data into Selecting the correct data from each part of the page Iterating over the data and storing that data into a list (This is where I'm having problems) Eventually, I am going to join the two lists together as one CSV. from bs4 import BeautifulSoup import urllib2 #1) establishing a connection to the website wiki = "http://www.morong.com/used-inventory/index.htm?start=16&amp;" req = urllib2.Request(wiki) page = urllib2.urlopen(req) soup = BeautifulSoup(page, 'lxml') #2) creating two empty lists to write the data into valueHolder = [] nameHolder = [] #3) selecting the correct data from each part of the page value = soup.findAll("span", { "class" : "value" }) name = soup.findAll("a", {"class" : "url"}) #4) iterates over rows and turns each row into a text field for row in value: valueholder = row.text for row in name: nameHolder = row.text print(valueholder) print(nameHolder) When I print valueHolder and nameHolder, I only return the last row of each for-loop. How can I print all of the values?
favorite count: 0

http://stackoverflow.com/comment/80468264
has text: I'm not sure how people are upvoting the question? its not fixing anything?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/46761367
type: Comment

http://stackoverflow.com/comment/80504456
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/46779116
has text: I'd use regex to get rid of the noise, before calling the lemmatizer.
type: Comment

http://stackoverflow.com/a/46893439
answers question: http://stackoverflow.com/q/46858761
has body: Perhaps this example will help you sort through your type discrimination: test = [123, None, "123", [123, "123"] ] for item in test: if isinstance(item, int): print item, "is an integer" elif isinstance(item, str): print item, "is a string" elif isinstance(item, list): print item, "is a list" else: print item, "is something else" Output: 123 is an integer None is something else 123 is a string [123, '123'] is a list
score: 0
type: Answer

http://stackoverflow.com/a/46840976
has comment: http://stackoverflow.com/comment/81965936
has comment: http://stackoverflow.com/comment/81501965
has comment: http://stackoverflow.com/comment/81965695
has comment: http://stackoverflow.com/comment/81967364
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82001509
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/81999434
has comment: http://stackoverflow.com/comment/82004032
answers question: http://stackoverflow.com/q/46751140
has comment: http://stackoverflow.com/comment/81965898
accepted answer of: http://stackoverflow.com/q/46751140
has comment: http://stackoverflow.com/comment/81967284
has body: As of writing, the latest Raspbian release has llvm-3.8, so per this github comment you need to install llvmlite v0.15.0 with numba v0.30.1. If you're on a different llvm then you will need to explore what versions of llvmlite and numba to use with that version of llvm. Here are the commands that got me set up to get a successful import librosa: sudo apt install libblas-dev llvm python3-pip python3-scipy virtualenv --system-site-packages -p python3 env source env/bin/activate pip install llvmlite==0.15.0 pip install numba==0.30.1 pip install librosa Note I'm using virtualenv and dragging in scipy and numpy from the system packages, otherwise it's hard to get the fortran &amp; c dependencies right plus those take ages to compile on a RPi. If you want to install system-wide then drop the 2nd and 3rd line and put sudo in front of the pip commands. I've also frozen my requirements in this requirements.txt file so if you download that then you can run a single command pip install -r requirements.txt
has comment: http://stackoverflow.com/comment/81458158
has comment: http://stackoverflow.com/comment/81942168
downvote count: 0

http://stackoverflow.com/comment/80587084
type: QuestionComment
has text: [That doesn't exist any more.](https://github.com/encode/django-rest-framework/issues/2763)
comment on: http://stackoverflow.com/q/46819746
score: 0
type: Comment

email
tags question: http://stackoverflow.com/q/46816930
tags question: http://stackoverflow.com/q/46815027
tags question: http://stackoverflow.com/q/46749147
tags question: http://stackoverflow.com/q/46778824
tags question: http://stackoverflow.com/q/46800562
tags question: http://stackoverflow.com/q/46858273
type: Tag
tag name: email

http://stackoverflow.com/q/46795098
accepted answer: http://stackoverflow.com/a/46795277
has body: I'm writing some Selenium tests in Python and I'm stuck in a situation: So, I'm trying to click in an icon what expand an tree node with some check boxes, but when I open the code file or just inspect the element I found an ' ' element declared with a class.I have tried to click on xpath element or css but don't expand that stuff :/ Here's the code line of where I'm trying to click: Someone could help?
favorite count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/80612888
upvote count: 1
tagged with: python
has title: How to expand a tree node in Selenium declared with a span tag
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46795277
has comment: http://stackoverflow.com/comment/80537611
tagged with: selenium
score: -1
type: Question
answer count: 1

http://stackoverflow.com/comment/80592702
comment on: http://stackoverflow.com/q/46821936
score: 0
type: Comment
type: QuestionComment
has text: Thank you, the camera light was blinking even after the file was written. it would only go off when the python session was closed.

http://stackoverflow.com/q/46856519
accepted answer: http://stackoverflow.com/a/46856699
has comment: http://stackoverflow.com/comment/80660894
answer count: 3
downvote count: 0
favorite count: 0
has title: Indexing a 2D List with another List
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/46856669
has answer: http://stackoverflow.com/a/46856699
upvote count: 3
has answer: http://stackoverflow.com/a/46856700
has body: If I have a list such as: lst = [[1,2,3], [4,5,6], [7,8,9]] and another list which contains a [row, column] index for an element in the list, so for example: index = [2, 1] Obviously I can get the element at index with: lst[index[0]][index[1]] However, I find that this syntax is quite clunky and doesn't sit well in a big block of code. It would also become worse with a higher dimensional list. My question: is there an easier way to do this index? It would seem that something like: lst[index] would be more readable but this isn't how Python works so isn't an option.
type: Question
possible better answer: http://stackoverflow.com/a/46856700

http://stackoverflow.com/comment/80479352
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/46764593
has text: can you paste your sys.path.append line in your code ?

http://stackoverflow.com/q/46762825
tagged with: python-2.7
score: 0
tagged with: python
tagged with: shutil
tagged with: python-3.x
type: UnansweredQuestion
has title: How to insert data into a JSON array inside a file?
has comment: http://stackoverflow.com/comment/80470994
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/80470954
type: Question
has body: Problem: I am Working on a file meta-project, which collects file information from a folder and stores it in a JSON file. My Empty JSON file looks like this db.json { "samples" : [] } Now my idea is to scan each file and insert each record into samples array like this db.json { "samples" : [ { "file_name": "ba18524fe5d5c6e99b99c7da66dbbfa094ab8f61", "file_new_location": "/home/admin/", "file_path": "/home/admin/vt_files/ba18524fe5d5c6e99b99c7da66dbbfa094ab8f61", "file_source": "VT", "md5": "149c4ac4ba0863607e033d6a5721fee7", "mime": "application_x-dosexec", "severity": "high", "sha256": "50bc946af55f0a5deb66f935229046c1ec74fb2233d71efa3ae064a073a771f5" } ] } But My issue is when ever i try to insert records, Iam not able to insert into the samples, but are coming in a single line. for file_original_name in files: file_meta = {} file_meta['file_name'] = file_original_name file_meta['file_path'] = os.path.join(root,file_original_name) file_meta['file_source'] = source file_meta['severity'] = severity file_meta['md5'] = md5(file_meta['file_path']) file_meta['sha256'] = sha256(file_meta['file_path']) mime = magic.Magic(mime=True) file_meta['mime'] = mime.from_file(file_meta['file_path']).replace('/','_') file_meta['file_new_location'] = '{}/{}/{}/{}'.format(default_root,severity,file_meta['mime'],file_original_name) try: extracted_new_dir = os.path.join(default_root,severity,file_meta['mime']) if not os.path.isdir(extracted_new_dir): os.makedirs(extracted_new_dir) if delete: move(file_meta['file_path'],file_meta['file_new_location']) else: copyfile(file_meta['file_path'],file_meta['file_new_location']) print json.dumps(file_meta,sort_keys=True,indent=4) except Exception as e: print e result[file_original_name] = (file_meta) with open('db.json','a') as f: json.dump(result , f) Any suggestions on how to solve this problem?
has answer: http://stackoverflow.com/a/46762914
answer count: 1

http://stackoverflow.com/a/53594253
upvote count: 2
has body: Try this. conn = stomp.Connection([(host, port)]) conn.set_listener('', MyListener()) conn.set_ssl(for_hosts=[(host, port)], ssl_version=ssl.PROTOCOL_TLS) conn.start() conn.connect(login, password, wait=True) conn.send(body=message, destination=queue) conn.disconnect() or conn.set_ssl(for_hosts=[(host, port)], ssl_version=_ssl.PROTOCOL_TLS)
downvote count: 0
answers question: http://stackoverflow.com/q/46770328
type: Answer
score: 2

http://stackoverflow.com/q/46810539
has comment: http://stackoverflow.com/comment/80569349
has answer: http://stackoverflow.com/a/46810773
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/80569062
has answer: http://stackoverflow.com/a/46811492
has comment: http://stackoverflow.com/comment/80569331
tagged with: python
has answer: http://stackoverflow.com/a/46811664
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80569509
possible better answer: http://stackoverflow.com/a/46811664
accepted answer: http://stackoverflow.com/a/46811492
has title: Convert a 2D array to 3D array by multiplying vector in numpy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/80569274
has comment: http://stackoverflow.com/comment/80568654
has body: Suppose I have an 2D numpy array a=[[1,-2,1,0], [1,0,0,-1]], but I want to convert it to an 3D numpy array by element-wise multiply a vector t=[[x0,x0,x0,x0],[x1,x1,x1,x1]] where xi is a 1D numpy array with 3072 size. So the result would be a*t=[[x0,-2x0,x0,0],[x1,0,0,-x1]] with the size (2,4,3072). So how should I do that in Python numpy?
tagged with: arrays

http://stackoverflow.com/q/46899206
has body: I'm a new python programmer and have code that manipulates a big number of files, operations like compressing, uncompressing, copying. To improve performance, multiprocessing is used, something like: pool = Pool(4) pool.map(do_task, tasks) There is some execution time savings which dropped from 75 to 55 seconds. Changing the number of processes doesn't seem to have an impact. I also tried to use multi-thread, the result is about the same. It appears the savings are somehow limited to a certain number no matter what I do. I have a hard time to figure out why I can't have a bigger saving. I read about terms like CPU-bound or IO-bound, but I don't know how I can practically tell whether that's what I'm running into. Is that something I can check from Activity Monitor? Or what's the suggested approach?
has title: How to get 2x, 3x performance savings with multiprocessing?
has comment: http://stackoverflow.com/comment/80746017
has comment: http://stackoverflow.com/comment/80746074
linked to: http://stackoverflow.com/q/1294382
has comment: http://stackoverflow.com/comment/80746330
score: 0
linked to: http://stackoverflow.com/q/582336
has comment: http://stackoverflow.com/comment/80745950
has comment: http://stackoverflow.com/comment/80746522
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80745967
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/80745780
has comment: http://stackoverflow.com/comment/80745838
tagged with: python-multiprocessing
type: Question

http://stackoverflow.com/q/46821037
has title: Calculate T(n)? Algorithm efficiency (Python)
has answer: http://stackoverflow.com/a/46873460
tagged with: time-complexity
downvote count: 0
answer count: 1
favorite count: 0
has body: I get the whole Big "O" thing but I'm kinda confused on the whole "finding or calculating T(n)" Heres one problem with a sequential search. Instead of just giving me the answer please tell me how you got it def sequentialSearch(alist, item): pos = 0 found = False while pos &lt; len(alist) and not found: if alist[pos] == item: found = True else: pos = pos+1 return found
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/80589482
tagged with: algorithm
has comment: http://stackoverflow.com/comment/80590700

http://stackoverflow.com/comment/80550980
comment on: http://stackoverflow.com/q/46801439
has text: @codeshark You can use queues, pipes, shared memory, but more importantly you should carefully examine why your server process would need to call a function in the request handler process. See: https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes and https://docs.python.org/3/library/multiprocessing.html#pipes-and-queues
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46904135
score: 1
upvote count: 1
has body: I want to calculate the geometric return (cumulative return) per annum for a pivot table containing monthly return and add this as a column to the table. The pivot table looks like this: In [474]: piv.tail(3) Out[474]: month 1 2 3 4 5 6 7 8 9 10 11 12 year 2015 3.0 -5.6 1.5 -0.1 0.3 -1.7 0.5 -7.0 0.3 -0.1 0.4 0.0 2016 5.2 4.7 -0.3 1.3 -6.1 0.3 3.5 -0.1 1.2 -1.9 0.7 0.9 2017 2.5 2.1 0.1 2.6 4.8 0.1 2.8 0.1 -2.1 0.5 NaN NaN tried piv['annual'] = (piv+1).cumprod(axis=1)-1 Which throws an error. Stuck here. any help appreciated.
type: Question
has answer: http://stackoverflow.com/a/46904307
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/80755004
has comment: http://stackoverflow.com/comment/80754914
favorite count: 0
has comment: http://stackoverflow.com/comment/80754955
has comment: http://stackoverflow.com/comment/80755044
tagged with: pivot-table
has title: get cumprod() for rows in pandas pivot table
tagged with: python
accepted answer: http://stackoverflow.com/a/46904307
type: AnsweredQuestion

http://stackoverflow.com/q/46878241
tagged with: multiprocessing
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has body: I need some help because I tried since two days, and I don't know how I can do this. I have function compute_desc that takes multiples arguments (5 to be exact) and I would like to run this in parallel. I have this for now: def compute_desc(coord, radius, coords, feat, verbose): # Compute here my descriptors return my_desc # numpy array (1x10 dimensions) def main(): points = np.rand.random((1000000, 4)) coords = points[:, 0:3] feat = points[:, 3] all_features = np.empty((1000000, 10)) all_features[:] = np.NAN scales = [0.5, 1, 2] for radius in scales: for index, coord in enumerate(coords): all_features[index, :] = compute_desc(coord, radius, coords, feat, False) I would like to parallelize this. I saw several solutions with a Pool, but I don't understand how it works. I tried with a pool.map(), but I can only send only one argument to the function. Here is my solution (it doesn't work): all_features = [pool.map(compute_desc, zip(point, repeat([radius, coords, feat, False] ) ) )] but I doubt it can work with a numpy array. EDIT This is my minimum code with a pool (it works now): import numpy as np from multiprocessing import Pool from itertools import repeat def compute_desc(coord, radius, coords, feat, verbose): # Compute here my descriptors my_desc = np.rand.random((1, 10)) return my_desc def compute_desc_pool(args): coord, radius, coords, feat, verbose = args compute_desc(coord, radius, coords, feat, verbose) def main(): points = np.random.rand(1000000, 4) coords = points[:, 0:3] feat = points[:, 3] scales = [0.5, 1, 2] for radius in scales: with Pool() as pool: args = zip(points, repeat(radius), repeat(coords), repeat(feat), repeat(kdtree), repeat(False)) feat_one_scale = pool.map(compute_desc_pool, args) feat_one_scale = np.array(feat_one_scale) if radius == scales[0]: all_features = feat_one_scale else: all_features = np.hstack([all_features, feat_one_scale]) # Others stuffs
possible better answer: http://stackoverflow.com/a/46889565
has answer: http://stackoverflow.com/a/46878414
has answer: http://stackoverflow.com/a/46889565
has title: Python multiprocessing pool.map with multiples arguments
upvote count: 1
tagged with: python
tagged with: parallel-processing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/46878414
score: 1

http://stackoverflow.com/a/46800920
has body: You shouldn't have to add a hook. Just add the tf.summary.image call anywhere in your model_fn/input_fn and the estimator should automatically add a summary hook for all summaries created.
has comment: http://stackoverflow.com/comment/89861172
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/46799892
has comment: http://stackoverflow.com/comment/89865469
answers question: http://stackoverflow.com/q/46799892
type: Answer
has comment: http://stackoverflow.com/comment/86994653
has comment: http://stackoverflow.com/comment/80560165
upvote count: 1

http://stackoverflow.com/q/46819188
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/80586388
score: 1
has comment: http://stackoverflow.com/comment/80585998
has body: Update: Does anyone know how to write the While loop below in Cython? I need it to be very fast. I'm not experienced with Cython but from what I can gather I would need to replace the NumPy calls with code that can be compiled in C. Is there a way to make the following code much faster, for example, by replacing the NumPy functions so that Numba can compile the while loop in nopython mode? The input variables, (rows, cols), are 1D lists/arrays of integers. import numpy as np def cluster(rows, cols): member_sets = [] centroids = [] while cols.any(): un, coun = np.unique(cols, return_counts=True) centroid = un[np.argmax(coun)] centroids.append(centroid) member_set = rows[cols == centroid] member_sets.append(member_set) rows = rows[np.in1d(cols, member_set, invert=True)] cols = cols[np.in1d(cols, member_set, invert=True)] cols = cols[np.in1d(rows, member_set, invert=True)] rows = rows[np.in1d(rows, member_set, invert=True)] return member_sets, centroids One can benchmark on the following dataset: from sklearn.neighbors import NearestNeighbors from sklearn.datasets import make_blobs X, y = make_blobs(1000, random_state=1) nbrs = NearestNeighbors(metric='euclidean', radius=3) nbrs.fit(X) adj_mat = nbrs.radius_neighbors_graph(X) rows = adj_mat.nonzero()[0] cols = adj_mat.nonzero()[1] What I am getting on my laptop: import timeit timeit.timeit("cluster(rows, cols)", globals=globals(), number=100) Output: 12.490656665991992 Is it possible to increase the speed by an order of magnitude (&lt; 1 sec) or better? Here are the results from profiling, with a dataset size of 10,000. It looks like the most expensive NumPy call is to argsort. import cProfile cProfile.run('m,c = cluster(rows, cols)') 1423 function calls in 78.965 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 1.214 1.214 78.965 78.965 &lt;ipython-input-1-44e1e663f585&gt;:3(cluster) 1 0.000 0.000 78.965 78.965 &lt;string&gt;:1(&lt;module&gt;) 14 0.000 0.000 0.064 0.…
upvote count: 2
has comment: http://stackoverflow.com/comment/80586786
tagged with: numba
has title: Python while loop execution speed up
tagged with: python
downvote count: 1
tagged with: performance
has comment: http://stackoverflow.com/comment/80655606
tagged with: cython
has comment: http://stackoverflow.com/comment/80586512
linked to: http://stackoverflow.com/q/46774685
has comment: http://stackoverflow.com/comment/80642012
tagged with: numpy
has comment: http://stackoverflow.com/comment/80586189
duplicate of: http://stackoverflow.com/q/46774685
has comment: http://stackoverflow.com/comment/80652180
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/80586436

http://stackoverflow.com/comment/80720415
comment on: http://stackoverflow.com/a/46886348
score: 0
has text: Thank you so much, You are numpy expert, this bug is really hard to find, I took almost the whole afternoon to find out it.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/46797943
upvote count: 2
has body: As simple as : &gt;&gt;&gt; string='hello im an idiot' &gt;&gt;&gt; out='' &gt;&gt;&gt; caps=True #flag to see if upper case &gt;&gt;&gt; for s in string[::-1]: #string[::-1] reverses it if s==' ': #when the char is a whitespace, directly add it to the resultant output out+=' ' continue if caps: #should be uppercase out+=s.upper() caps = False else: #should be lowercase out+=s.lower() caps = True &gt;&gt;&gt; out =&gt; 'ToIdI nA mI oLlEh'
type: Answer
accepted answer of: http://stackoverflow.com/q/46797826
score: 2
answers question: http://stackoverflow.com/q/46797826
has comment: http://stackoverflow.com/comment/80542676
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80542664

http://stackoverflow.com/a/46795585
has comment: http://stackoverflow.com/comment/83321344
downvote count: 1
answers question: http://stackoverflow.com/q/46793526
has comment: http://stackoverflow.com/comment/80574910
type: Answer
has body: If you are simply looking to play/stream audio from specific URL , you can try vlc binding for python. More details here It can be installed as pip install python-vlc Here is a sample code that stream audio directly from URL. player object has added advantage of audio-player like controls like pause, resume, stop etc. URL used is m4a url as stated in question. Source Code import vlc import time url = "http://r2---sn-q4fl6nlr.googlevideo.com/videoplayback?id=ded99df829692710&amp;itag=140&amp;source=youtube&amp;ei=DRvmWa-kDtr9oQObxIuACw&amp;pl=32&amp;ratebypass=yes&amp;mime=audio/mp4&amp;gir=yes&amp;clen=4061037&amp;lmt=1507168899082254&amp;dur=255.651&amp;signature=4380D44827E745850E8034A17DD2CF71493515B2.49EE0269B463E530D2C05D79E658319E3354F4B5&amp;key=cms1&amp;ip=103.200.41.86&amp;ipbits=0&amp;expire=1508274029&amp;sparams=clen,dur,ei,expire,gir,id,initcwndbps,ip,ipbits,ipbypass,itag,lmt,mime,mip,mm,mn,ms,mv,pl,ratebypass,source&amp;rm=sn-52vaavvoapox-itql7l,sn-h55z7z&amp;req_id=ac17cbf87900a3ee&amp;redirect_counter=2&amp;fexp=23702512&amp;cms_redirect=yes&amp;ipbypass=yes&amp;mip=2605:6000:ec02:7e00:6d00:a5a1:a309:abb6&amp;mm=30&amp;mn=sn-q4fl6nlr&amp;ms=nxu&amp;mt=1508259877&amp;mv=m" #define VLC instance instance = vlc.Instance('--input-repeat=-1', '--fullscreen') #Define VLC player player=instance.media_player_new() #Define VLC media media=instance.media_new(url) #Set player media player.set_media(media) #Play the media player.play() some of player controls &gt;&gt;&gt; play.pause() #pause play back &gt;&gt;&gt; player.play() #resume play back &gt;&gt;&gt; player.stop() #stop play back
has comment: http://stackoverflow.com/comment/80556998
score: 2
upvote count: 3

http://stackoverflow.com/comment/80745597
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46899190
score: 0
has text: What is wrong, you have a traceback ?

http://stackoverflow.com/q/46900196
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/46900220
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/46900220
has body: I have the following tuple res = [('fdetail',), ('fdetail1',)] I want to have it in two variables using Python var1 = fdetail var2 = fdetail1 Any help is highly appreciated.
tagged with: python
has title: Split tuple into variable using Python

http://stackoverflow.com/a/47102139
score: 1
upvote count: 1
has body: You are using a ClearDB plan that only permits 10 connections. The only path they offer is to upgrade to a ClearDB plan that offers more connections. If you're on Mercury, upgrade to Jupiter or Saturn. If in doubt, post your question to the ClearDB Support system. They will be able to help you best. The multi-tenant systems will not permit you to modify this parameter.
accepted answer of: http://stackoverflow.com/q/46900204
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/46900204
type: Answer

http://stackoverflow.com/a/55777866
upvote count: 3
type: Answer
has body: I unfortunately don't have a "Do exactly this to fix your problem" solution but I would suggest the following steps. Many seem obvious but I find when sorting these sorts of problems out you have to be certain of each step before moving on. Does the host system, in this case your Ubuntu VM, have multiple versions of python installed? Are you sure you are using the version you think you're using? Did you check your path variable? You need to be sure you're using your conda installation. Does the host system have different versions of conda installed? It looks like in the activated environment you checked the package is listed in conda. But is it in the package directory for your virtual environment? One way to check this is to use the find command and specify the base path for your virtual environment. Try forcing the reinstallation of the package. Try using pip instead of conda. If your environment is setup properly pip should install packages to the conda path. more desperate steps Make a new virtual environment. Add packages one by one. Examine what each package is changing. Reinstall conda. Create a new instance of your vm. Make a vm instance from a different image. Make your own image. This is just one way to troubleshoot the problem. When possible try to avoid steps 6-10 because they're rather involved. That said sometimes it's a problem with the vm and not with you.
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/46767012

http://stackoverflow.com/comment/80592168
score: 0
has text: Printing each item as it's added to the dict is an obvious first debugging step, and would have revealed your issue. Did you try anything like that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46821927

http://stackoverflow.com/comment/80529096
has text: person: your assumption was still inaccurate because the OP had written `Application(Frame, Tk)` and not `Application(tk.Frame, tk.Tk)`. If the OP had written `(tk.Frame, tk.Tk)` then your assumption would be accurate. I agree with @SamHartman. Now that you know your error you should update your answer to reflect the question. Or remove your post as providing wrong information can hurt the growth of other beginners and likely you will continue to get down votes on your answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/46778843
type: Comment

http://stackoverflow.com/comment/80750106
type: Comment
score: 0
comment on: http://stackoverflow.com/q/46901583
type: QuestionComment
has text: The numbers are generated from the ASCII values of characters from a string (English word, alphabetic only). So the list can be a range of values, as well as have duplicate values. If two numbers are the same (ie: `[51, 35, 51]` they will be ordered `[1, 2, 3]`). So they are unique in that respect.

http://stackoverflow.com/a/46764347
has comment: http://stackoverflow.com/comment/80585643
has comment: http://stackoverflow.com/comment/80556482
type: Answer
has comment: http://stackoverflow.com/comment/114129144
has comment: http://stackoverflow.com/comment/80479641
has comment: http://stackoverflow.com/comment/80556619
has comment: http://stackoverflow.com/comment/80502603
has body: You can use the mllib package to compute the L2 norm of the TF-IDF of every row. Then multiply the table with itself to get the cosine similarity as the dot product of two by two L2norms: 1. RDD rdd = sc.parallelize([[1, "Delhi, Mumbai, Gandhinagar"],[2, " Delhi, Mandi"], [3, "Hyderbad, Jaipur"]]) Compute TF-IDF: documents = rdd.map(lambda l: l[1].replace(" ", "").split(",")) from pyspark.mllib.feature import HashingTF, IDF hashingTF = HashingTF() tf = hashingTF.transform(documents) You can specify the number of features in HashingTF to make the feature matrix smaller (fewer columns). tf.cache() idf = IDF().fit(tf) tfidf = idf.transform(tf) Compute L2norm: from pyspark.mllib.feature import Normalizer labels = rdd.map(lambda l: l[0]) features = tfidf normalizer = Normalizer() data = labels.zip(normalizer.transform(features)) Compute cosine similarity by multiplying the matrix with itself: from pyspark.mllib.linalg.distributed import IndexedRowMatrix mat = IndexedRowMatrix(data).toBlockMatrix() dot = mat.multiply(mat.transpose()) dot.toLocalMatrix().toArray() array([[ 0. , 0. , 0. , 0. ], [ 0. , 1. , 0.10794634, 0. ], [ 0. , 0.10794634, 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) OR: Using a Cartesian product and the function dot on numpy arrays: data.cartesian(data)\ .map(lambda l: ((l[0][0], l[1][0]), l[0][1].dot(l[1][1])))\ .sortByKey()\ .collect() [((1, 1), 1.0), ((1, 2), 0.10794633570596117), ((1, 3), 0.0), ((2, 1), 0.10794633570596117), ((2, 2), 1.0), ((2, 3), 0.0), ((3, 1), 0.0), ((3, 2), 0.0), ((3, 3), 1.0)] 2. DataFrame Since you seem to be using dataframes, you can use the spark mlpackage instead: import pyspark.sql.functions as psf df = rdd.toDF(["ID", "Office_Loc"])\ .withColumn("Office_Loc", psf.split(psf.regexp_replace("Office_Loc", " ", ""), ',')) Compute TF-IDF: from pyspark.ml.feature import HashingTF, IDF hashingTF = HashingTF(inputCol="Office_Loc", outputCol="tf") tf = hashingTF.transform(df) idf = IDF(inputCol="tf", outputCol="feature").fit(tf) tfidf = idf.…
has comment: http://stackoverflow.com/comment/80480747
downvote count: 1
has comment: http://stackoverflow.com/comment/80504833
accepted answer of: http://stackoverflow.com/q/46758768
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/117922254
has comment: http://stackoverflow.com/comment/82843789
score: 38
upvote count: 39
answers question: http://stackoverflow.com/q/46758768

http://stackoverflow.com/comment/80568387
has text: @PM2Ring the world would be a better place if K&R actually invented the vector for C :)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/46810439
type: QuestionComment

http://stackoverflow.com/comment/80569038
comment on: http://stackoverflow.com/q/46810875
score: 0
type: Comment
type: QuestionComment
has text: You need to construct a nested list, each sublist representing a single row. For each new file, you append to the sublists. Then write it all in one go at the end with `csv.writerows()` (your current method involved opening the file on every iteration which is very inefficient). I'm not at a PC currently to create an answer.

http://stackoverflow.com/a/76866064
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/46881006
upvote count: 1
has body: tf.gather() performs exactly what you want, if I understand well what you're willing to accomplish. tf.gather( params, indices, validate_indices=None, axis=None, batch_dims=0, name=None ) Gather slices from params axis axis according to indices. indices must be an integer tensor of any dimension (often 1-D).

http://stackoverflow.com/comment/80743798
has text: @ZeroPiraeus, please read carefully my question and comments. Your last comment was nonsense (i know what my question was about, i know what `self` is, etc.).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46891886

http://stackoverflow.com/q/46751158
has comment: http://stackoverflow.com/comment/80448218
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/46751252
has answer: http://stackoverflow.com/a/46751222
has comment: http://stackoverflow.com/comment/80448295
has body: text = "This is a test for my program" new_dict = {} text_list = text.split() word_tester = 2 for word in text_list: word_tester = len(word) if len(word) == word_tester: new_dict[word_tester] = word return new_dict I am trying to build a program in python that goes through a list of strings and assigns them to a dict where the key is the amount of characters in that string and the value is the word itself (eg: 2 : be, to 3 : foo, bar). My program however only goes through and assigns some of the given list of strings. What can I do to get this to work?
type: Question
has comment: http://stackoverflow.com/comment/80448217
has title: Python - iterate through an entire list and assign it to a dict
has answer: http://stackoverflow.com/a/46751201
has answer: http://stackoverflow.com/a/46751218
tagged with: python
answer count: 4

http://stackoverflow.com/q/46891295
has body: When I try running sudo apt-get install python-pip python-dev libmysqlclient-dev I get the following Reading package lists... Done Building dependency tree Reading state information... Done libmysqlclient-dev is already the newest version. Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: python-pip : Depends: python-setuptools (>= 0.6c1) but it is not going to be installed Depends: python-requests but it is not going to be installed Recommends: python-dev-all (>= 2.6) but it is not installable E: Unable to correct problems, you have held broken packages
tagged with: python-3.4
answer count: 1
score: -2
has title: Installing MySQL Dev Client on Python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/46891506
upvote count: 0

http://stackoverflow.com/q/46891432
upvote count: 2
has answer: http://stackoverflow.com/a/46891970
tagged with: python
has body: In the Python Data Science Handbook the following example is given (the penultimate line is the one which I don't understand, as indicated): import pandas as pd import numpy as np import seaborn as sns sns.set() #Downloaded from: https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/births.csv births = pd.read_csv('births.csv') births['decades'] = (births['year'] // 10) * 10 # Rhobust sigma clipping operation - ignore this quartiles = np.percentile(births['births'], [25, 50, 75]) mu = quartiles[1] sig = 0.74 * (quartiles[2] - quartiles[0]) births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)') births['day'] = births['day'].astype(int) births.index = pd.to_datetime(10000 * births.year + 100 * births.month + births.day, format='%Y%m%d') births_by_date = births.pivot_table('births', [births.index.month, births.index.day]) #Help on the loop below births_by_date.index = [pd.datetime(2012, month, day) for (month, day) in births_by_date.index] print(births_by_date.index) I don't understand the construction of the births_by_date.index in the for loop. I understand that the loop is getting applied to the pivot table, but I've never seen what looks like the output array put before the loop. Can someone explain how this works, or direct me to an appropriate explanation please? I have tried: How do I save results of a "for" loop into a single variable? numberous tutorials such as this one: https://www.learnpython.org/en/Loops various other questions, but I can't find anything similar.
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/46891970
has answer: http://stackoverflow.com/a/46891949
has title: for loop construction with array before loop
type: Question
has comment: http://stackoverflow.com/comment/80730211
has comment: http://stackoverflow.com/comment/80730593
accepted answer: http://stackoverflow.com/a/46891949
has comment: http://stackoverflow.com/comment/80730415
answer count: 2
linked to: http://stackoverflow.com/q/29225619
downvote count: 0
has comment: http://stackoverflow.com/comment/80730089
favorite count: 0

http://stackoverflow.com/q/46857826
has answer: http://stackoverflow.com/a/46876493
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: biopython
tagged with: fasta
score: 1
upvote count: 1
type: Question
has title: Using Biopython to find and extract FASTA matches to exact DNA sequence
linked to: http://stackoverflow.com/q/13886170
downvote count: 0
answer count: 1
has body: I am trying to use Biopython to extract all of the DNA sequences from a FASTA file that contain a match with the following short DNA sequence: "GGCTCAACCCTGGA" Here is what I have so far: from Bio import SeqIO source = "rep_set_no_spaces.fasta" outfile = "rep_set_PNA_matches.fasta" seq1 = "GGCTCAACCCTGGA" # basically a function to check whether seq contains sub1 def seq_check(seq, seq1): return seq.find(seq1) seqs = SeqIO.parse(source, 'fasta') filtered = (seq for seq in seqs if seq_check(seq.seq, seq1)) SeqIO.write(filtered, outfile, 'fasta') I am trying to adapt code from this post (Filtering a FASTA file based on sequence with BioPython), but my sequence of interest is neither at the start nor end of the sequence... For example, here are some of my sequences... the 1st and 4th sequence match, but the 2nd and 3rd do not. I want to pull out sequences make a new fasta file with just those sequences that contain "GGCTCAACCCTGGA": &gt;110148arco.1D_184193 TACGGAGGGGGTTAGCGTTGTTCGGAATTACTGGGCGTAAAGCGCACGTAGGTGGATTGGAAAGTATGGGGTGAAATCCCAGGGCTCAACCCTGGAACTGCCTCATAAACTATCAGTCTAGAGTTCGAGAGAGGTGAGTGGAATTCCGAGTGTAGAGGTGAAATTCGTAGATATTCGGAGGAACACCAGTGGCGAAGGCGGCTCACTGGCTCGATACTGACACTGAGGTGCGAAAGTGTGGGGAGCAAACAGG &gt;110475arco.1D_40770 TACGGAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGCGGTTTGTTAAGTCAGCTGTGAAAGCCCTGGGCTCAACCTGGGAATTGCAGTTGATACTGGCAAGCTGGAGTACGAGAGAGGGAGGTAGAATTCCATGTGTAGCGGTGAAATGCGTAGATATATGGAGGAATACCAGTGGCGAAGGCGGCCTCCTGGCTCGATACTGACGCTGAGGTGCGAAAGCGTGGGGAGCAAACAGG &gt;110484arco.1D_190999 TACGGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGCGGTTTGTTAAGTCAGCTGTGAAAGCCCTGGGCTCAACCTGGGAATTGCAGTTGATACTGATCGACTAGAGTACGAGAGAGGGAGGTAGAATTCCACGTGTAGCGGTGAAATGCGTAGATATGTGGAGGAATACCGGTGGCGAAGGCGGCCTCCTGGCTCGATACTGACGCTGAGGTGCGAAAGCGTGGGGAGCAAACAGG &gt;110525amin.3D_40107 TACGGAGGGGGCTAGCGTTGTTCGGAATTACTGGGCGTAAAGCGTACGTAGGCGGATTAGTAAGTAAGATGTGAAATCCCAGGGCTCAACCCTGGAACTGCATTTTAAACTGCTAGTCTAGAGTTATGGAGAGGTAAGTGGAATTCCTAGTGTAGAGGTGAAATTCGTAGATATTAGGAGGAACACCAGAGGCGAAG…

http://stackoverflow.com/comment/80457302
comment on: http://stackoverflow.com/q/46755431
has text: Mox has that functionality as well, but I'm not trying to test the handling of exceptions, I want the test to fail because `should_not_be_called` should not be called, and it is... it does not throw an exception, mox does, as it should. but the mox exception (that should fail the test) is caught by the try in the code. I've added a more detailed example, hope it helps.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/46754707
has title: Python function on AWS Lambda
type: AnsweredQuestion
type: Question
answer count: 1
score: -1
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/80455215
has answer: http://stackoverflow.com/a/46755031
favorite count: 0
has comment: http://stackoverflow.com/comment/80465493
has body: I need run the following function below on the lambda AWS: def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (partial, target)) if s &gt;= target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i + 1:] subset_sum(remaining, target, partial + [n]) if __name__ == "__main__": subset_sum([1,2,3], 5) However the following error appears and I can't resolve: { "errorMessage": "'&gt;=' not supported between instances of 'int' and 'LambdaContext'", "errorType": "TypeError", "stackTrace": [ [ "/var/task/lambda_function.py", 7, "subset_sum", "if s &gt;= target:" ] ] } The original function has more values that take a long time because of this I'm running on Lambda. On the computer using py subset_sum.py it works normally.
accepted answer: http://stackoverflow.com/a/46755031
downvote count: 2
has comment: http://stackoverflow.com/comment/80455150
upvote count: 1
tagged with: python
tagged with: lambda

http://stackoverflow.com/q/46892542
has body: So, the question is on using QWebEngineView or QWebEnginePage, or something like that. I have a link which looks like Salt. I have already managed to intercept clicking on this link and force QWebEngineView to do nothing with it because all that I need is to print the text of this url ("Salt") in the python console instead of opening it. The problem is that I haven't any idea how to implement it. There was linkHovered() signal in PyQt4 which returns the title, text and url of the link when the mouse hovers over it. In PyQt5 it returns only the url. Any ideas? Some code: class MyWebEnginePage(QWebEnginePage): link_clicked = pyqtSignal(str) def acceptNavigationRequest(self, url, nav_type, is_frame): if nav_type == 0: self.link_clicked.emit(str(url)) return False else: return True self.page.link_clicked.connect(self.LEchange) def LEchange(self,url): print(url) It prints: PyQt5.QtCore.QUrl('file:///C:/salt') but if the link looks like Salt I need to get "Salt".
tagged with: hyperlink
has comment: http://stackoverflow.com/comment/80740406
upvote count: 2
has comment: http://stackoverflow.com/comment/80741167
downvote count: 1
tagged with: click
favorite count: 0
has comment: http://stackoverflow.com/comment/80736976
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: qwebenginepage
has comment: http://stackoverflow.com/comment/80732290
score: 1
has title: Get the text or title from a clicked link in QWebEnginePage
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/80740721
type: Question

http://stackoverflow.com/q/46861236
has body: I want the user to be able to enter an integer value in the Spinbox widget. If the value entered is not an integer or is an integer outside the Spinbox limits, as soon as the Spinbox loses focus, the value in the Spinbox's content must revert to a default value. In the example code, I use the Entry widget just for the Spinbox can lose focus. If the user comes back to Spinbox to enter a new value, his entry is not validated. I confirm Malcolm's remark in Interactively validating Entry widget content in tkinter that the validatecommand=command feature gets cleared as soon as this command updates the widget's value. Is there a way to get the value entered in the Spinbox repeatedly validated and not just once? from tkinter import * class GUI: def __init__(self): # root window of the whole program self.root = Tk() self.root.title('Validate Spinbox') # registering validate and invalid commands validate_cmd = (self.root.register(self.validate), '%P') invalid_cmd = (self.root.register(self.invalid)) # creating a Label items_lbl = Label(self.root, text="# of items (5-10):") items_lbl.grid(row=0, column=0) # creating a Spinbox widget self.items_var = StringVar() self.items_var.set(7) items_count = Spinbox(self.root, textvariable=self.items_var, from_=5, to=10, width=4, validate='focusout', validatecommand=validate_cmd, invalidcommand=invalid_cmd) items_count.grid(row=0, column=1) # creating an Entry widget self.entry_var = StringVar() self.entry_var.set("Input some text here") text_entry = Entry(self.root, textvariable=self.entry_var) text_entry.grid(row=1, column=0) def validate(self, entry): try: value = int(entry) valid = value in range(5, 11) except ValueError: valid = False if not valid: self.root.bell() return valid def invalid(self): self.items_var.set(7) if __name__ == '__main__': main_window = GUI() mainloop()
linked to: http://stackoverflow.com/q/4140437
tagged with: validation
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/46863849
favorite count: 0
has comment: http://stackoverflow.com/comment/80670916
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
tagged with: widget
score: 1
has comment: http://stackoverflow.com/comment/80672965
accepted answer: http://stackoverflow.com/a/46863849
upvote count: 1
type: Question
has title: Widget validation in tkinter

http://stackoverflow.com/comment/80467405
type: Comment
comment on: http://stackoverflow.com/q/46761013
type: QuestionComment
has text: So dictionary is the only way? will it be slow if I have a large set of widgets to display?
score: 0

http://stackoverflow.com/a/46781299
upvote count: 1
has comment: http://stackoverflow.com/comment/80619430
downvote count: 0
score: 1
has body: Detecting Hough lines on the image is your best bet in this case, because court colors can change from place to place and also the camera settings. Detecting the lines, and some further processing using uniform color patches should allow you to segment the court region with some accuracy.
type: Answer
answers question: http://stackoverflow.com/q/46779690

http://stackoverflow.com/q/46789102
has body: The goal of this flask application is to fill a form, parse the data of the resulting form, launch a build, zip and send this build to the user. Everything is working fine, but I want that once the form is filled, the user is redirected to a waiting page, if this is possible of course. This is my code at the moment: def create_and_download_build(form) # Some parsing in the beginning of the function, the build etc... os.system('tar -zcvf build.tar.gz dist/') headers = {"Content-Disposition": "attachment; filename=build.tar.gz"} with open('build.tar.gz', 'r+b') as data_file: data = data_file.read() response = make_response(render_template('waiting.html'), (data, headers)) return response This is where this function is declared, in my _init__.py: @app.route('/', methods=('GET', 'POST')) def index(): form = MyForm() # MyForm is a class in which there is some # wtform field (for example TextField) if form.validate_on_submit(): # This is called once the form is validated return create_and_download_build(request.form) return render_template('index.html', form=form) It doesn't work, I receive this error for the line in which I call make_response: AttributeError: 'tuple' object has no attribute 'decode' If I change make_response to : response = make_response((data, headers)), it will properly upload the file, but it will not render the waiting.html page. Same if I change it to : response = make_response(render_template('waiting.html')), it will render the template, but it will not download the file. Is there a method to do both action?
upvote count: 5
type: Question
score: 5
downvote count: 0
answer count: 1
has title: How to render a template and send a file simultaneously with flask
tagged with: flask
has answer: http://stackoverflow.com/a/46789558
linked to: http://stackoverflow.com/q/34009980
favorite count: 0
duplicate of: http://stackoverflow.com/q/34009980
tagged with: python
accepted answer: http://stackoverflow.com/a/46789558
type: AnsweredQuestion

http://stackoverflow.com/a/46870341
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/46869528
score: 19
upvote count: 19
has body: Pip and virtualenv are two separate tools. Pip is a package manager, you will use it to install packages into your virtual environment once it has been set up. Pip does not actually manage the virtual environment. Virtualenv is the tool that handles creating virtual environments. First, you should check if you have virtualenv installed with virtualenv --version. If you do not have it, you will get an error that virtualenv is not found. You can use pip to install virtualenv with pip install virtualenv. Once you have virtualenv, you can create a python 3.6 environment with virtualenv -p python3.6 /path/to/myvirtualenv. You will need an installation of python 3.6 for this command to work, so download and install python 3.6 first if you do not have it. I believe that on windows if you don't have python 3.6 in your PATH variable, you may need to point directly to the python 3.6 installation instead with virtualenv -p /path/to/mypython3.6 /path/to/myvirtualenv. See Virtualenv User Guide
accepted answer of: http://stackoverflow.com/q/46869528

http://stackoverflow.com/comment/80730358
type: Comment
type: AnswerComment
has text: @SirRobin I can't, it say that too much code in the post even if I shorten it, is there another way to send you?
comment on: http://stackoverflow.com/a/46890822
score: 0

http://stackoverflow.com/comment/80747298
type: QuestionComment
comment on: http://stackoverflow.com/q/46899816
score: 0
has text: I have a feeling it may be an environment error but I'm not sure what to do nor what is actually wrong
type: Comment

http://stackoverflow.com/q/46905419
has body: The following code df = pd.DataFrame({ 'animals': 'kot pies lis kot'.split() + [None] }, dtype='category') df.animals.apply(len) returns 4 for None: 0 3 1 4 2 3 3 3 4 4 Name: animals, dtype: int64 Is it a bug in pandas or a "feature"?
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/46905446
type: Question
has title: Apply on pandas' categorical Series with None
accepted answer: http://stackoverflow.com/a/46905446
tagged with: pandas
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/80716913
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46884759
has text: What exactly is your question?

http://stackoverflow.com/q/46759218
tagged with: python
has answer: http://stackoverflow.com/a/46993660
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/60200044
has title: Global variable Updated by and Interval Componant
type: Question
tagged with: plotly-dash
accepted answer: http://stackoverflow.com/a/46993660
answer count: 2
downvote count: 0
favorite count: 0
has body: When my dash app is launched a global variable is created (dat) by a computationally expensive function. I want dat to be updated at regular intervals but not by any user action. I understand that normal python global variables are unsuitable for use in dash due to the way memory is shared so I am using a hidden div to store the data which is updated at regular intervals. I do not want the data to be updated when the app is launched by each user, but rather want the updating to happen in the background and preferably update all users apps with the updated data. If the app had to be updated with a page refresh that's fine too, but the updated data will be available for all users. I have included an example below which performs the task that I want to do, the trouble is that storing the data in div is fine if it is a string or a numpy array, but if the data structure is more complex like a pandas dataframe (see commented lines of code) or a dictionary of pandas dataframes then the app will run, but the page won't load in a browser (Error loading layout). Maybe memoizing is the solution, though all examples I have seen seem subtly different enough from this such that I can't see how it could be used. The use of a hidden div seems like a bit of a hack to me but is recommended by the plotly help pages So my question is how can I create and update global variables in dash using more complex data structures than strings or arrays? import dash from dash.dependencies import Input, Output, Event import dash_html_components as html import dash_core_components as dcc from datetime import datetime import numpy as np import pandas as pd app = dash.Dash(__name__) def compute_expensive_data(): t=datetime.now() dat = np.array([t.minute, t.second]) #d = {'time' : pd.Series(np.array([t.minute, t.second]), index=['minute', 'second'])} #dat = pd.DataFrame(d) return dat dat = compute_expensive_data() print(dat) app.layout = html.Div([ html.H3('Original Time: Minute = ' + str(dat[0]) + ':…
upvote count: 2
has answer: http://stackoverflow.com/a/60200044

http://stackoverflow.com/a/46755809
score: 6
has comment: http://stackoverflow.com/comment/80457059
has body: The Process class requires a callable as its target. Instead of running the function in the separate process, you are calling it and passing its result (None in this case) to the Process class. Just change the following: mp.Process(target=pri()) with: mp.Process(target=pri)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/80456992
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/46755640
answers question: http://stackoverflow.com/q/46755640

http://stackoverflow.com/q/46755451
has comment: http://stackoverflow.com/comment/80473729
answer count: 1
has comment: http://stackoverflow.com/comment/80474567
has body: I know this is a known bug, but i dont know how to resolve that because i do lot of googling and after that finally back to stack to get some real solution : Here are configuration: First i install nginx by: sudo apt-get install nginx lsb_release -rd Description: Ubuntu 16.04.2 LTS Release: 16.04 apt-cache policy nginx-core nginx-core: Installed: 1.10.3-0ubuntu0.16.04.2 Candidate: 1.10.3-0ubuntu0.16.04.2 Version table: *** 1.10.3-0ubuntu0.16.04.2 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-updates/main amd64 Packages 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-security/main amd64 Packages 100 /var/lib/dpkg /status 1.9.15-0ubuntu1 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial/main amd64 Packages My nginx service config is like: nano /lib/systemd/system/nginx.service # Stop dance for nginx # ======================= # # ExecStop sends SIGSTOP (graceful stop) to the nginx process. # If, after 5s (--retry QUIT/5) nginx is still running, systemd takes control # and sends SIGTERM (fast shutdown) to the main process. # After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends # SIGKILL to all the remaining processes in the process group (KillMode=mixed). # # nginx signals reference doc: # http://nginx.org/en/docs/control.html # [Unit] Description=A high performance web server and a reverse proxy server After=network.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;' ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;' ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid TimeoutStopSec=5 KillMode=mixed [Install] WantedBy=multi-user.target My nginx.conf file is like: nano /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## send…
favorite count: 0
has comment: http://stackoverflow.com/comment/80473024
type: UnansweredQuestion
has title: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument ubuntu 16.04 xenial
tagged with: django
tagged with: python
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/46765650
has comment: http://stackoverflow.com/comment/80473898
type: Question
tagged with: nginx
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/80476285
upvote count: 2

http://stackoverflow.com/q/46849668
has title: error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
has answer: http://stackoverflow.com/a/46858057
has comment: http://stackoverflow.com/comment/80647475
has comment: http://stackoverflow.com/comment/80646640
has comment: http://stackoverflow.com/comment/80647696
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/80648596
type: Question
upvote count: 2
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/80648232
tagged with: opencv
accepted answer: http://stackoverflow.com/a/46858057
has body: I'm using python 2.7 I'm getting this error when i try to run the epsilon operation on it, this is my code import cv2 import numpy as np img = cv2.imread('img.jpeg') img = cv2.convertScaleAbs(img) epsilon = 0.01 * cv2.arcLength(img, True) approx = cv2.approxPolyDP(img, epsilon, True) hull = cv2.convexHull(img) This is the Error, Traceback (most recent call last): File "/home/decentmakeover2/lanedetect.py", line 6, in &lt;module&gt; epsilon = 0.01 * cv2.arcLength(img, True) error: /home/decentmakeover2/opencv- 3.2.0/modules/imgproc/src/shapedescr.cpp:285: error: (-215) count &gt;= 0 &amp;&amp; (depth == CV_32F || depth == CV_32S) in function arcLength Im not sure what to change here,any ideas? Edit: Traceback (most recent call last): File "/home/decentmakeover2/lanedetect.py", line 8, in &lt;module&gt; epsilon = 0.01 * cv2.arcLength(img,True) TypeError: curve data type = 6 is not supported &gt;&gt;&gt;
has answer: http://stackoverflow.com/a/62919721
downvote count: 1
has comment: http://stackoverflow.com/comment/80646844
has comment: http://stackoverflow.com/comment/80646926
possible better answer: http://stackoverflow.com/a/62919721
has comment: http://stackoverflow.com/comment/80647236
has comment: http://stackoverflow.com/comment/80646788
type: AnsweredQuestion

http://stackoverflow.com/a/46779609
answers question: http://stackoverflow.com/q/46770018
type: Answer
has body: No, it is not because of the Python version. It is because data.columns[...] expects an array of the same size, that is used as a mask (True values in the mask will include that element from data.columns, False values will skip it). It is impossible to give more details with the amount of information you have provided.
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/46770018

http://stackoverflow.com/q/46776451
has answer: http://stackoverflow.com/a/46777643
has answer: http://stackoverflow.com/a/73875008
possible better answer: http://stackoverflow.com/a/73875008
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: gtk3
accepted answer: http://stackoverflow.com/a/46777643
favorite count: 0
has title: How to set the text size of Gtk.Entry in PyGObject?
type: Question
tagged with: python
has body: I want increase the text size of Gtk.Entry . entry = Gtk.Entry() I am using Python3
upvote count: 2
tagged with: pygobject
answer count: 2

http://stackoverflow.com/q/46846081
upvote count: 2
has comment: http://stackoverflow.com/comment/80639754
tagged with: deep-learning
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/43357732
has answer: http://stackoverflow.com/a/46850617
accepted answer: http://stackoverflow.com/a/46850617
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80639708
score: 1
linked to: http://stackoverflow.com/q/40670370
tagged with: tensorflow
type: Question
has title: what is wrong with my cosine similarity? Tensorflow
tagged with: neural-network
has body: I want to use cosine similarity in my Neural network, instead of the standard dot product. I've had a look at the dot product and at the cosine similarity. In the example above they use a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a") b = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_b") normalize_a = tf.nn.l2_normalize(a,0) normalize_b = tf.nn.l2_normalize(b,0) cos_similarity=tf.reduce_sum(tf.multiply(normalize_a,normalize_b)) sess=tf.Session() cos_sim=sess.run(cos_similarity,feed_dict={a:[1,2,3],b:[2,4,6]}) However, I tried doing it my own way x = tf.placeholder(tf.float32, [None, 3], name = 'x') # input has 3 features w1 = tf.placeholder(tf.float32, [10, 3], name = 'w1') # 10 nodes in the first hidden layer cos_sim = tf.divide(tf.matmul(x, w1), tf.multiply(tf.norm(x), tf.norm(w1))) with tf.Session() as sess: sess.run(cos_sim, feed_dict = {x = np.array([[1,2,3], [4,5,6], [7,8,9], w1: np.random.uniform(0,1,size = (10,3) )}) Is my way wrong? Also, what is going on in the matrix multiplication? Are we actually multiplying the weights of one node for the inputs of different samples (within one feature)?
has comment: http://stackoverflow.com/comment/80639817

http://stackoverflow.com/q/46769464
has body: So I am piping some binary data using RDD.pipe() function to "cat", when I receive the data it is changed so i can't work with it.any I die how to fix it? I'm using python3 The code and a par of the data is as follows: line = sc.binaryFiles("files/pipevids") line.map(lambda x:x[1]).pipe("cat").take(1) and the original data: b'RIFF\xeaU\n\x00AVI LIST\x963\x00\x00hdrlavih8\x00\x00\x005\x82\x00\x00\x08L\x01\x00\x00\x00\x00\x00\x10\t\x00\x00&lt;\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x10\x00\x80\x07\x00\x008\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LIST\x10\x11\x00\x00strlstrh8\x00\x00\x00vidsFMP4\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x1e\x00\x00\x00\x00\x00\x00\x00&lt;\x00\x00\x00\x11x\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x80\x078\x04strfX\x00\x00\x00W\x00\x00\x00\x80\x07\x00\x008\x04\x00\x00\x01\x00\x18\x00FMP4\x00\xec^\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xb0\x01\x00\x00\x01\xb5\x89\x13\x00\x00\x01\x00\x00\x00\x01 \x00\xc4\x8d\x88\x00\xf5&lt;\x04\x87\x14C\x00\x00\x01\xb2Lavc57.89.100\x00JUNK\x18\x10\x00\x00\x04\x00\x00\x00\x00\x00\x00\x0000dc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00…
has comment: http://stackoverflow.com/comment/80484298
type: Question
tagged with: pyspark
score: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/80486153
has comment: http://stackoverflow.com/comment/80484225
has comment: http://stackoverflow.com/comment/80484930
answer count: 1
has answer: http://stackoverflow.com/a/46769609
has comment: http://stackoverflow.com/comment/80485249
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80485116
has title: Data change in spark pipe
has comment: http://stackoverflow.com/comment/80485641

http://stackoverflow.com/comment/80689709
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/46870241
has text: A 64-bit process can address up to 128 TiB in Windows 8.1 and later.

http://stackoverflow.com/q/46779659
has comment: http://stackoverflow.com/comment/80511096
linked to: http://stackoverflow.com/q/44744737
has body: I installed tensorflow on my mac via pip and I'm using anaconda as my IDE. when I run the command import tensoflow I'm getting the following error: Traceback (most recent call last): File "&lt;ipython-input-3-a649b509054f&gt;", line 1, in &lt;module&gt; import tensorflow File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 51, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/Applications/anaconda3/lib/python3.5/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/Applications/anaconda3/lib/python3.5/imp.py", line 343, in load_dynamic return _load(spec) ImportError: dlopen(/Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: @rpath/libcublas.8.0.dylib Referenced from: /Applications/anaconda3/lib/python3.5/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so Reason: image not found Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/install_source…
score: 0
tagged with: deep-learning
tagged with: python
has comment: http://stackoverflow.com/comment/80510974
tagged with: installation
has comment: http://stackoverflow.com/comment/80512309
accepted answer: http://stackoverflow.com/a/46780862
tagged with: tensorflow
type: AnsweredQuestion
tagged with: anaconda
has title: Unable to use tensorflow
has comment: http://stackoverflow.com/comment/80506359
has answer: http://stackoverflow.com/a/46780862
type: Question
answer count: 1

http://stackoverflow.com/comment/80599272
type: QuestionComment
has text: Ok, I restarted notebook kernel today and it works as I would expect. Now there is no difference if I predict all anomaly samples or one by one. This is so weird
score: 0
comment on: http://stackoverflow.com/q/46814467
type: Comment

http://stackoverflow.com/q/46879374
tagged with: montecarlo
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/46879436
has title: Monte Carlo dart simulator
has comment: http://stackoverflow.com/comment/80705900
answer count: 3
accepted answer: http://stackoverflow.com/a/46879436
has comment: http://stackoverflow.com/comment/80705923
possible better answer: http://stackoverflow.com/a/46879406
favorite count: 0
has answer: http://stackoverflow.com/a/46879406
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/80705920
tagged with: python
has body: I've been trying to make a dart simulator using the Monte Carlo simulation in Python 3. So far, I have written the following code: import random import math n = (input("Enter the number of darts you have. ")) count = 1 circleval = 0 squareval = 0 while count &lt;= n: y = 2*random.random()*2-1 x = 2*random.random()*2-1 if math.sqrt((x-1)**2+(y-1)**2)&lt;=1: circleval+=1 squareval+=1 else: squareval+=1 count+=1 print("Pi is " + 4*(1.*circleval/squareval)) However, when I run this I reccive the following error message: TypeError: '&lt;=' not supported between instances of 'int' and 'str'
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/46879502
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/80705943

http://stackoverflow.com/a/47305036
has comment: http://stackoverflow.com/comment/81593937
has comment: http://stackoverflow.com/comment/81580767
has comment: http://stackoverflow.com/comment/81575904
has comment: http://stackoverflow.com/comment/81573736
has comment: http://stackoverflow.com/comment/81574011
upvote count: 1
has body: Edit-1 - Using UTF8 with BOM Seems like BOM becomes important in case of windows. So you need to use below type build config { "cmd": ["F:\\Python27-14\\python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "env": { "PYTHONIOENCODING": "utf_8_sig" }, } After that it works correctly for me on windows also Original Answer I checked the issue and I didn't face the same on Python 2.7 with Sublime text. The only change being I had to add # -*- coding: utf-8 -*- to the top of the file. Which seems the missing part in this question # -*- coding: utf-8 -*- print u'\u0061' # should be 'a' print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER' After that the reversal has no impact You can see more details about this required header on Why declare unicode by string in python? Below is summary of the above link When you specify # -*- coding: utf-8 -*-, you're telling Python the source file you've saved is utf-8. The default for Python 2 is ASCII (for Python 3 it's utf-8). This just affects how the interpreter reads the characters in the file.
answers question: http://stackoverflow.com/q/46856584
has comment: http://stackoverflow.com/comment/81574679
type: Answer
has comment: http://stackoverflow.com/comment/81579871
has comment: http://stackoverflow.com/comment/81574672
downvote count: 0
has comment: http://stackoverflow.com/comment/81574013
score: 1

http://stackoverflow.com/a/46898111
has body: I can sort of see where this is coming from but normally we would need more info or more of your source code to see the real issue. But somewhere inside your code is a misplaced or a left out ". As your program iterates through it self it is coded to add those commas if you are adding code to go back and remove those commas after the fact you are adding unnecessary code. Go back through your source code and look at all your print commands that populate these areas where your finding unnecessary commas OR post more of your source code so I can find it.
has comment: http://stackoverflow.com/comment/80760034
score: 0
type: Answer
answers question: http://stackoverflow.com/q/46897988

http://stackoverflow.com/q/46864077
has comment: http://stackoverflow.com/comment/80675559
upvote count: 2
answer count: 1
favorite count: 0
tagged with: element
has title: How to simply check are all elements in array same?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/80675800
duplicate of: http://stackoverflow.com/q/3844801
score: 1
has comment: http://stackoverflow.com/comment/80675814
has comment: http://stackoverflow.com/comment/80675612
downvote count: 1
has comment: http://stackoverflow.com/comment/80675564
type: Question
has comment: http://stackoverflow.com/comment/80675737
has answer: http://stackoverflow.com/a/46864114
tagged with: arrays
has body: I have an array with a random elements. How can I check, is all that elements the same or not? Could it be possible with numpy.all ? Thanks
linked to: http://stackoverflow.com/q/3844801

http://stackoverflow.com/q/46755841
has body: I am trying to get the dataframe to print out results in order of the month. If I don't change the month to month name and leave as int (eg. 1: 4, 2: 94) it will be chronological order but the moment I change to month name, it puts in order of months in alphabetical order. If I do sort=False, it returns me in a random order. Appreciate any help I can get! Thanks! order_group_df = pd.DataFrame({'Property Name': Propertyname, 'Reported on': ReportedDateList, 'Category': Catname}) order_group_df['Reported on'] = pd.to_datetime(order_group_df['Reported on'], format='%m/%d/%Y %H:%M', errors='coerce') order_group_df = order_group_df.dropna() a = order_group_df.groupby([order_group_df['Reported on'].dt.month.apply(mapper)], sort=False).agg({'count'}).iloc[:, :-2] print a Results: count Reported on Feb 94 Mar 306 Jan 4 Jun 9 Aug 6 Sep 2 Oct 2 Nov 1 Apr 1 Jul 5
tagged with: python
has answer: http://stackoverflow.com/a/49126626
has answer: http://stackoverflow.com/a/46756243
has comment: http://stackoverflow.com/comment/80457539
has title: Pandas Dataframe month int to month name in order
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/80457239
possible better answer: http://stackoverflow.com/a/46756159
accepted answer: http://stackoverflow.com/a/46756243
has answer: http://stackoverflow.com/a/46756159
type: Question
score: 0
answer count: 3

http://stackoverflow.com/a/50878600
has comment: http://stackoverflow.com/comment/103638934
has body: Solution editing multiprocessing source code The original answer by Sergey requires you to edit multiprocessing source code as follows: Find your multiprocessing package (mine, installed via Anaconda, was in /anaconda3/lib/python3.6/multiprocessing). Open managers.py Add the key argument manager_owned=True to the AutoProxy function. Original AutoProxy: def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True): ... Edited AutoProxy: def AutoProxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True, manager_owned=True): ... Solution via code, at run time I have managed to solve the unexpected keyword argument TypeError exception without editing directly the source code of multiprocessing by instead adding these few lines of code where I use multiprocessing's Managers: import multiprocessing # Backup original AutoProxy function backup_autoproxy = multiprocessing.managers.AutoProxy # Defining a new AutoProxy that handles unwanted key argument 'manager_owned' def redefined_autoproxy(token, serializer, manager=None, authkey=None, exposed=None, incref=True, manager_owned=True): # Calling original AutoProxy without the unwanted key argument return backup_autoproxy(token, serializer, manager, authkey, exposed, incref) # Updating AutoProxy definition in multiprocessing.managers package multiprocessing.managers.AutoProxy = redefined_autoproxy
downvote count: 1
upvote count: 9
answers question: http://stackoverflow.com/q/46779860
score: 8
type: Answer
has comment: http://stackoverflow.com/comment/112815130
has comment: http://stackoverflow.com/comment/102920458
has comment: http://stackoverflow.com/comment/102927234
has comment: http://stackoverflow.com/comment/112814956

http://stackoverflow.com/comment/80572702
score: 0
has text: `collections.Counter` are not ordered
type: Comment
comment on: http://stackoverflow.com/a/46812568
type: AnswerComment

http://stackoverflow.com/q/46830344
possible better answer: http://stackoverflow.com/a/46830541
accepted answer: http://stackoverflow.com/a/46830447
has answer: http://stackoverflow.com/a/46830541
tagged with: scalar
upvote count: 2
answer count: 2
tagged with: pandas
tagged with: truthiness
has answer: http://stackoverflow.com/a/46830447
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has body: I'm trying to execute: if df_trades.loc[:, 'CASH'] != 0: df_trades.loc[:, 'CASH'] -= commission and then I get the error. df_trades.loc[:, 'CASH'] is a column of floats. I want to subtract the scalar commission from each entry in that column. For example, df_trades.loc[:, 'CASH'] prints out 2011-01-10 -2557.0000 2011-01-11 0.0000 2011-01-12 0.0000 2011-01-13 -2581.0000 If commission is 1, I want the result: 2011-01-10 -2558.0000 2011-01-11 0.0000 2011-01-12 0.0000 2011-01-13 -2582.0000
has title: Using conditional statement to subtract scalar from pandas df column gives ValueError: The truth value of a Series is ambiguous

http://stackoverflow.com/comment/80705353
type: AnswerComment
comment on: http://stackoverflow.com/a/46878739
score: 0
type: Comment
has text: This looks great, thanks for the thorough answer! I have no way to test this out either, so hopefully the OP can reply and verify that it works on the newer version of PyQt4.